Skip to main content

rustango_cms/
rendition.rs

1//! Image renditions — resized variants of a `Media` row served at
2//! `/__media__/<filter_spec>/<media_id>`.
3//!
4//! Rendition pipeline:
5//!
6//! 1. Tera template emits `<img src="/__media__/fill-300x200/42">`
7//!    via the `rcms_image_url(media_id, filter_spec)` Tera function.
8//! 2. The public route handler looks up the [`MediaRendition`] keyed
9//!    by `(media.content_hash, filter_spec)`. On hit it streams the
10//!    cached bytes from storage; on miss it loads the original,
11//!    resizes via the [`image`] crate, writes the result, and
12//!    inserts a row.
13//! 3. `cms_media_rendition` rows are GC'd by a future
14//!    `manage cms gc-renditions --older-than 30d` verb (deferred).
15//!
16//! Dedup happens at the `(content_hash, filter_spec)` level — two
17//! `Media` rows with identical bytes share renditions automatically.
18
19use chrono::{DateTime, Utc};
20use rustango::sql::Auto;
21use rustango::Model;
22use serde::{Deserialize, Serialize};
23
24/// One row per (media, filter_spec) pair. Multiple `Media` rows
25/// sharing the same `content_hash` share renditions implicitly via
26/// the `(content_hash, filter_spec)` key — re-uploading the same
27/// image doesn't regenerate renditions.
28#[derive(Model, Debug, Clone, Serialize, Deserialize)]
29#[rustango(
30    table = "cms_media_rendition",
31    app = "cms",
32    admin(
33        list_display = "media_id, filter_spec, width, height, last_used_at",
34        ordering = "-last_used_at",
35        list_filter = "filter_spec",
36    )
37)]
38pub struct MediaRendition {
39    #[rustango(primary_key)]
40    pub id: Auto<i64>,
41
42    /// FK to `cms_media.id`. The rendition is keyed by
43    /// `(content_hash, filter_spec)` though — see module docs.
44    #[rustango(fk = "cms_media", on = "id", index)]
45    pub media_id: i64,
46
47    /// SHA-256 hex of the SOURCE bytes — same value as
48    /// `cms_media.content_hash` for the source row. Indexed for the
49    /// rendition lookup keyed on `(content_hash, filter_spec)`.
50    #[rustango(max_length = 64, index)]
51    pub content_hash: String,
52
53    /// Parsed-then-canonicalized filter spec, e.g. `"fill-300x200"`,
54    /// `"max-1200x900"`, `"width-800"`. The route handler accepts
55    /// these from URL paths; invalid specs return 400.
56    #[rustango(max_length = 64, index)]
57    pub filter_spec: String,
58
59    /// Pixel dimensions of the resized output.
60    pub width: i32,
61    pub height: i32,
62
63    /// MIME type of the rendered bytes. Usually `image/webp` for
64    /// re-encoded sources, but PNG / JPEG passthrough when the
65    /// filter is just a resize.
66    #[rustango(max_length = 128)]
67    pub mime: String,
68
69    /// Storage backend key, resolved as `<tenant_slug>/<storage_key>`
70    /// by [`crate::media_storage`] — local disk by default, S3/R2/MinIO
71    /// when the host installs a backend. Renditions use the
72    /// `renditions/<hash>-<spec>.<ext>` shape.
73    #[rustango(max_length = 512)]
74    pub storage_key: String,
75
76    /// File size in bytes — used by the eventual GC to prioritize
77    /// large or stale renditions.
78    pub size: i64,
79
80    /// Bumped on every successful serve so a GC pass can prune
81    /// renditions that haven't been viewed in N days.
82    pub last_used_at: chrono::DateTime<chrono::Utc>,
83
84    #[rustango(auto_now_add)]
85    pub created_at: Auto<DateTime<Utc>>,
86}
87
88// ---------- filter spec ----------
89
90/// Parsed filter spec — what the URL looked like, broken down into a
91/// resize operation.
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub enum FilterOp {
94    /// Resize so the result EXACTLY fits the box, cropping overflow.
95    Fill { w: u32, h: u32 },
96    /// Resize so the result fits WITHIN the box, preserving aspect.
97    Max { w: u32, h: u32 },
98    /// Resize to a target width, scale height to preserve aspect.
99    Width(u32),
100    /// Resize to a target height, scale width to preserve aspect.
101    Height(u32),
102}
103
104/// Encoding hints — applied after the geometric resize. Filter
105/// pipeline spec encodes these as `|format-X|quality-N|bgcolor-XYZ`
106/// chained after the resize op. All optional; defaults match the
107/// source format (JPEG → JPEG, anything else → PNG).
108///
109/// `Format::Auto` is reserved for future content-negotiation via
110/// the `Accept` header — today it behaves like `Format::Webp`.
111#[derive(Debug, Clone, Copy, PartialEq, Default)]
112pub struct EncodingOps {
113    pub format: Option<EncodeFormat>,
114    /// 1..=100 — applied to JPEG / WebP / AVIF encoders. PNG ignores.
115    pub quality: Option<u8>,
116    /// RGB background painted under transparent pixels before
117    /// encoding to a non-alpha format. Hex triplet — e.g.
118    /// `bgcolor-fff` or `bgcolor-ffffff` (3 or 6 hex chars).
119    pub background: Option<(u8, u8, u8)>,
120}
121
122#[derive(Debug, Clone, Copy, PartialEq)]
123pub enum EncodeFormat {
124    Jpeg,
125    Png,
126    Webp,
127    /// AVIF. Encoding requires the `avif` crate feature; without
128    /// it, `encode` returns a clear error. Parsing + the URL spec always
129    /// recognize `format-avif`.
130    Avif,
131    /// Content negotiation — picks the best the request accepts.
132    /// v0 behaves like WebP (browsers all support it). Future: read
133    /// the `Accept` header to pick AVIF when supported.
134    Auto,
135}
136
137impl EncodeFormat {
138    fn parse(s: &str) -> Option<Self> {
139        Some(match s {
140            "jpeg" | "jpg" => Self::Jpeg,
141            "png" => Self::Png,
142            "webp" => Self::Webp,
143            "avif" => Self::Avif,
144            "auto" => Self::Auto,
145            _ => return None,
146        })
147    }
148    fn canonical(self) -> &'static str {
149        match self {
150            Self::Jpeg => "jpeg",
151            Self::Png => "png",
152            Self::Webp => "webp",
153            Self::Avif => "avif",
154            Self::Auto => "auto",
155        }
156    }
157    fn mime(self) -> &'static str {
158        match self {
159            Self::Jpeg => "image/jpeg",
160            Self::Png => "image/png",
161            Self::Avif => "image/avif",
162            Self::Webp | Self::Auto => "image/webp",
163        }
164    }
165    fn ext(self) -> &'static str {
166        match self {
167            Self::Jpeg => "jpg",
168            Self::Png => "png",
169            Self::Avif => "avif",
170            Self::Webp | Self::Auto => "webp",
171        }
172    }
173}
174
175/// One end-to-end filter pipeline: an optional resize + optional
176/// encoding hints. Parsed from a pipe-separated spec like
177/// `fill-300x200|format-webp|quality-75|bgcolor-fff`. The first
178/// segment must be a resize op (`fill`/`max`/`width`/`height`);
179/// remaining segments classify into `EncodingOps`.
180///
181/// Backward compat: bare specs without a `|` (e.g. `fill-300x200`)
182/// parse to a pipeline with no encoding hints, mirroring the v0.2
183/// behavior.
184#[derive(Debug, Clone, Copy, PartialEq)]
185pub struct FilterPipeline {
186    pub geometric: FilterOp,
187    pub encoding: EncodingOps,
188}
189
190#[derive(Debug, thiserror::Error)]
191pub enum FilterError {
192    #[error("unknown filter spec `{0}` — expected fill-WxH | max-WxH | width-W | height-H")]
193    Unknown(String),
194    #[error("invalid dimensions in `{0}`")]
195    BadDimensions(String),
196    #[error("invalid encoding op `{0}` — expected format-X | quality-N | bgcolor-XYZ")]
197    BadEncoding(String),
198}
199
200impl FilterPipeline {
201    /// Parse a pipe-separated spec into a pipeline. The first
202    /// segment must be a resize op; subsequent segments encode
203    /// hints.
204    pub fn parse(raw: &str) -> Result<Self, FilterError> {
205        let mut parts = raw.split('|');
206        let head = parts.next().unwrap_or("");
207        let geometric = FilterOp::parse(head)?;
208        let mut encoding = EncodingOps::default();
209        for seg in parts {
210            let seg = seg.trim();
211            if seg.is_empty() {
212                continue;
213            }
214            if let Some(rest) = seg.strip_prefix("format-") {
215                encoding.format = Some(
216                    EncodeFormat::parse(rest)
217                        .ok_or_else(|| FilterError::BadEncoding(seg.to_owned()))?,
218                );
219            } else if let Some(rest) = seg.strip_prefix("quality-") {
220                let n: u8 = rest
221                    .parse()
222                    .map_err(|_| FilterError::BadEncoding(seg.to_owned()))?;
223                if !(1..=100).contains(&n) {
224                    return Err(FilterError::BadEncoding(seg.to_owned()));
225                }
226                encoding.quality = Some(n);
227            } else if let Some(rest) = seg.strip_prefix("bgcolor-") {
228                encoding.background = Some(
229                    parse_hex_rgb(rest).ok_or_else(|| FilterError::BadEncoding(seg.to_owned()))?,
230                );
231            } else {
232                return Err(FilterError::BadEncoding(seg.to_owned()));
233            }
234        }
235        Ok(Self {
236            geometric,
237            encoding,
238        })
239    }
240
241    /// Canonical string form (round-trips through `parse`).
242    /// Encoding hints are emitted only when non-default.
243    pub fn canonical(&self) -> String {
244        let mut out = self.geometric.canonical();
245        if let Some(fmt) = self.encoding.format {
246            out.push('|');
247            out.push_str("format-");
248            out.push_str(fmt.canonical());
249        }
250        if let Some(q) = self.encoding.quality {
251            out.push_str(&format!("|quality-{q}"));
252        }
253        if let Some((r, g, b)) = self.encoding.background {
254            out.push_str(&format!("|bgcolor-{r:02x}{g:02x}{b:02x}"));
255        }
256        out
257    }
258}
259
260/// Parse `fff` or `ffffff` into `(R, G, B)` bytes. 4-digit alpha
261/// shorthand is intentionally rejected — bgcolor flattens, alpha
262/// has no place.
263fn parse_hex_rgb(s: &str) -> Option<(u8, u8, u8)> {
264    let s = s.trim_start_matches('#');
265    let hex = match s.len() {
266        3 => {
267            // Expand `fff` → `ffffff`
268            let mut out = String::with_capacity(6);
269            for c in s.chars() {
270                out.push(c);
271                out.push(c);
272            }
273            out
274        }
275        6 => s.to_owned(),
276        _ => return None,
277    };
278    crate::theme::parse_rgb6(&hex)
279}
280
281impl FilterOp {
282    /// Parse a URL-shape spec: `fill-300x200`, `max-1200x900`,
283    /// `width-800`, `height-600`. Hyphens, lowercase only.
284    pub fn parse(raw: &str) -> Result<Self, FilterError> {
285        let raw = raw.trim();
286        // Helper: parse `WxH` after a known prefix.
287        let parse_pair = |s: &str| -> Result<(u32, u32), FilterError> {
288            let (w, h) = s
289                .split_once('x')
290                .ok_or_else(|| FilterError::BadDimensions(raw.to_owned()))?;
291            let w: u32 = w
292                .parse()
293                .map_err(|_| FilterError::BadDimensions(raw.to_owned()))?;
294            let h: u32 = h
295                .parse()
296                .map_err(|_| FilterError::BadDimensions(raw.to_owned()))?;
297            if w == 0 || h == 0 || w > 8192 || h > 8192 {
298                return Err(FilterError::BadDimensions(raw.to_owned()));
299            }
300            Ok((w, h))
301        };
302        if let Some(rest) = raw.strip_prefix("fill-") {
303            let (w, h) = parse_pair(rest)?;
304            return Ok(Self::Fill { w, h });
305        }
306        if let Some(rest) = raw.strip_prefix("max-") {
307            let (w, h) = parse_pair(rest)?;
308            return Ok(Self::Max { w, h });
309        }
310        if let Some(rest) = raw.strip_prefix("width-") {
311            let n: u32 = rest
312                .parse()
313                .map_err(|_| FilterError::BadDimensions(raw.to_owned()))?;
314            if n == 0 || n > 8192 {
315                return Err(FilterError::BadDimensions(raw.to_owned()));
316            }
317            return Ok(Self::Width(n));
318        }
319        if let Some(rest) = raw.strip_prefix("height-") {
320            let n: u32 = rest
321                .parse()
322                .map_err(|_| FilterError::BadDimensions(raw.to_owned()))?;
323            if n == 0 || n > 8192 {
324                return Err(FilterError::BadDimensions(raw.to_owned()));
325            }
326            return Ok(Self::Height(n));
327        }
328        Err(FilterError::Unknown(raw.to_owned()))
329    }
330
331    /// Canonical string form (round-trips through `parse`).
332    pub fn canonical(&self) -> String {
333        match self {
334            Self::Fill { w, h } => format!("fill-{w}x{h}"),
335            Self::Max { w, h } => format!("max-{w}x{h}"),
336            Self::Width(n) => format!("width-{n}"),
337            Self::Height(n) => format!("height-{n}"),
338        }
339    }
340}
341
342/// Apply `op` to `original` (decoded image) and return the resized
343/// image. Filters are cheap-and-correct (Lanczos3). For `Fill`,
344/// `focal` (when `Some`) shifts the crop so the focal point stays
345/// inside the target rectangle — passes (0.5, 0.5) for "no focal
346/// set, use geometric center" semantics.
347pub fn apply(
348    original: &image::DynamicImage,
349    op: FilterOp,
350    focal: Option<(f32, f32)>,
351) -> image::DynamicImage {
352    use image::imageops::FilterType;
353    let (sw, sh) = (original.width(), original.height());
354    match op {
355        FilterOp::Fill { w, h } => {
356            // Resize-to-fill: scale so the smaller side covers the
357            // target, then crop around the focal point. The focal
358            // point is in source-image coordinates as a 0..1
359            // fraction; it rides along with the uniform scale.
360            let scale_w = w as f32 / sw as f32;
361            let scale_h = h as f32 / sh as f32;
362            let scale = scale_w.max(scale_h);
363            let new_w = (sw as f32 * scale).round() as u32;
364            let new_h = (sh as f32 * scale).round() as u32;
365            let resized = original.resize_exact(new_w, new_h, FilterType::Lanczos3);
366            let (fx, fy) = focal.unwrap_or((0.5, 0.5));
367            let fx = fx.clamp(0.0, 1.0);
368            let fy = fy.clamp(0.0, 1.0);
369            // Center the crop on the focal point in resized
370            // coordinates, then clamp so the crop stays inside.
371            let max_x = new_w.saturating_sub(w);
372            let max_y = new_h.saturating_sub(h);
373            let target_x = (fx * new_w as f32) - (w as f32 / 2.0);
374            let target_y = (fy * new_h as f32) - (h as f32 / 2.0);
375            let x_off = target_x.clamp(0.0, max_x as f32) as u32;
376            let y_off = target_y.clamp(0.0, max_y as f32) as u32;
377            resized.crop_imm(x_off, y_off, w.min(new_w), h.min(new_h))
378        }
379        FilterOp::Max { w, h } => original.resize(w, h, FilterType::Lanczos3),
380        FilterOp::Width(n) => {
381            let h = (sh as f32 * (n as f32 / sw as f32)).round() as u32;
382            original.resize_exact(n, h.max(1), FilterType::Lanczos3)
383        }
384        FilterOp::Height(n) => {
385            let w = (sw as f32 * (n as f32 / sh as f32)).round() as u32;
386            original.resize_exact(w.max(1), n, FilterType::Lanczos3)
387        }
388    }
389}
390
391/// Encode `image` per the supplied [`EncodingOps`], applying
392/// background-color flattening when targeting a non-alpha format
393/// (JPEG). Returns `(bytes, mime, extension)`. When `encoding.format`
394/// is `None`, falls back to `source_mime` (JPEG passthrough, anything
395/// else → PNG) to preserve the v0.2 behavior.
396///
397/// # Errors
398/// Encoder failures from the [`image`] crate.
399pub fn encode(
400    image: &image::DynamicImage,
401    encoding: &EncodingOps,
402    source_mime: &str,
403) -> Result<(Vec<u8>, String, String), String> {
404    use image::codecs::jpeg::JpegEncoder;
405    let format = encoding.format.unwrap_or_else(|| {
406        if source_mime == "image/jpeg" || source_mime == "image/jpg" {
407            EncodeFormat::Jpeg
408        } else if source_mime == "image/webp" {
409            EncodeFormat::Webp
410        } else {
411            EncodeFormat::Png
412        }
413    });
414
415    // Background-color flatten when targeting a non-alpha format.
416    // PNG + WebP both honour alpha; JPEG doesn't.
417    let needs_flatten = matches!(format, EncodeFormat::Jpeg) || encoding.background.is_some();
418    let prepared: image::DynamicImage = if needs_flatten && encoding.background.is_some() {
419        let (r, g, b) = encoding.background.unwrap();
420        flatten_onto_background(image, r, g, b)
421    } else if matches!(format, EncodeFormat::Jpeg) && image.color().has_alpha() {
422        // No explicit bgcolor but JPEG demands opaque — flatten on
423        // white by default.
424        flatten_onto_background(image, 255, 255, 255)
425    } else {
426        image.clone()
427    };
428
429    let mut out: Vec<u8> = Vec::new();
430    match format {
431        EncodeFormat::Jpeg => {
432            let quality = encoding.quality.unwrap_or(85);
433            let mut cur = std::io::Cursor::new(&mut out);
434            let mut enc = JpegEncoder::new_with_quality(&mut cur, quality);
435            enc.encode_image(&prepared)
436                .map_err(|e| format!("encode jpeg: {e}"))?;
437        }
438        EncodeFormat::Png => {
439            // PNG is lossless; `quality` doesn't apply.
440            let mut cur = std::io::Cursor::new(&mut out);
441            prepared
442                .write_to(&mut cur, image::ImageFormat::Png)
443                .map_err(|e| format!("encode png: {e}"))?;
444        }
445        EncodeFormat::Webp | EncodeFormat::Auto => {
446            // The `image` crate's WebP encoder is lossless by
447            // default. The `quality` knob is accepted for API
448            // symmetry but ignored — swapping in a lossy WebP
449            // encoder is a feature-flag follow-up.
450            let mut cur = std::io::Cursor::new(&mut out);
451            prepared
452                .write_to(&mut cur, image::ImageFormat::WebP)
453                .map_err(|e| format!("encode webp: {e}"))?;
454        }
455        EncodeFormat::Avif => {
456            // #398 — AVIF, gated behind the `avif` feature (pulls the
457            // ravif/rav1e encoder). AVIF supports alpha, so no flatten.
458            #[cfg(feature = "avif")]
459            {
460                // Quality 1..=100; default 61.
461                // Speed 1..=10 (higher = faster/larger); 4 balances both.
462                let quality = encoding.quality.unwrap_or(61);
463                let mut cur = std::io::Cursor::new(&mut out);
464                let enc =
465                    image::codecs::avif::AvifEncoder::new_with_speed_quality(&mut cur, 4, quality);
466                prepared
467                    .write_with_encoder(enc)
468                    .map_err(|e| format!("encode avif: {e}"))?;
469            }
470            #[cfg(not(feature = "avif"))]
471            {
472                let _ = &prepared;
473                return Err(
474                    "AVIF output requires building rustango-cms with the `avif` feature".to_owned(),
475                );
476            }
477        }
478    }
479    Ok((out, format.mime().to_owned(), format.ext().to_owned()))
480}
481
482/// Composite `src` onto a solid (r, g, b) background. Used by the
483/// JPEG path (no alpha) + the explicit `bgcolor-XYZ` op.
484fn flatten_onto_background(src: &image::DynamicImage, r: u8, g: u8, b: u8) -> image::DynamicImage {
485    use image::GenericImageView;
486    let (w, h) = src.dimensions();
487    let mut buf = image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 255]));
488    let rgba = src.to_rgba8();
489    image::imageops::overlay(&mut buf, &rgba, 0, 0);
490    image::DynamicImage::ImageRgba8(buf)
491}
492
493// ---------- Hard crop (#24) ----------
494
495/// [`crop_image`] on the blocking pool: a full decode + encode
496/// is hundreds of milliseconds of CPU for a large photo, and inline it
497/// parked a Tokio worker for all of it.
498///
499/// # Errors
500/// As [`crop_image`].
501pub async fn crop_image_off_runtime(
502    bytes: Vec<u8>,
503    source_mime: String,
504    (x, y, w, h): (u32, u32, u32, u32),
505) -> Result<(Vec<u8>, String), String> {
506    rustango::__private_runtime::tokio::task::spawn_blocking(move || {
507        crop_image(&bytes, &source_mime, x, y, w, h)
508    })
509    .await
510    .map_err(|e| format!("crop worker failed: {e}"))?
511}
512
513/// [`strip_exif_if_image`] on the blocking pool. Returns the bytes
514/// to store — the re-encoded ones when EXIF was stripped, else the input —
515/// and the decoded dimensions.
516pub async fn strip_exif_off_runtime(bytes: Vec<u8>, mime: String) -> (Vec<u8>, Option<(u32, u32)>) {
517    if !mime.starts_with("image/") || mime == "image/svg+xml" {
518        return (bytes, None);
519    }
520    rustango::__private_runtime::tokio::task::spawn_blocking(move || {
521        let (stripped, dims) = strip_exif_if_image(&bytes, &mime);
522        (stripped.unwrap_or(bytes), dims)
523    })
524    .await
525    .unwrap_or_else(|e| std::panic::resume_unwind(e.into_panic()))
526}
527
528/// Decode `bytes`, crop to `(x, y, w, h)` in source-pixel coords,
529/// and re-encode in the same format. Returns `(cropped_bytes, mime)`.
530/// SVG inputs are rejected — vector crop is a different surface.
531///
532/// # Errors
533/// * Image-decode failure (corrupt or unsupported format)
534/// * Crop rectangle outside the source bounds
535/// * Re-encode failure
536pub fn crop_image(
537    bytes: &[u8],
538    source_mime: &str,
539    x: u32,
540    y: u32,
541    w: u32,
542    h: u32,
543) -> Result<(Vec<u8>, String), String> {
544    if source_mime == "image/svg+xml" {
545        return Err(
546            "Cropping SVG sources isn't supported — clone first, edit the markup directly."
547                .to_owned(),
548        );
549    }
550    let img = image::load_from_memory(bytes).map_err(|e| format!("decode source: {e}"))?;
551    let (sw, sh) = (img.width(), img.height());
552    if w == 0 || h == 0 {
553        return Err("Crop rectangle must have non-zero width + height.".to_owned());
554    }
555    if x.saturating_add(w) > sw || y.saturating_add(h) > sh {
556        return Err(format!(
557            "Crop rectangle ({x},{y},{w},{h}) is outside the source ({sw}×{sh})."
558        ));
559    }
560    let cropped = img.crop_imm(x, y, w, h);
561    let mut out: Vec<u8> = Vec::new();
562    let out_mime = if source_mime == "image/jpeg" || source_mime == "image/jpg" {
563        let mut cur = std::io::Cursor::new(&mut out);
564        cropped
565            .write_to(&mut cur, image::ImageFormat::Jpeg)
566            .map_err(|e| format!("encode jpeg: {e}"))?;
567        "image/jpeg".to_owned()
568    } else if source_mime == "image/webp" {
569        let mut cur = std::io::Cursor::new(&mut out);
570        cropped
571            .write_to(&mut cur, image::ImageFormat::WebP)
572            .map_err(|e| format!("encode webp: {e}"))?;
573        "image/webp".to_owned()
574    } else {
575        // Default to PNG (lossless) for everything else — PNG, GIF,
576        // BMP all funnel into a PNG output. Editors who want a
577        // specific format can re-upload.
578        let mut cur = std::io::Cursor::new(&mut out);
579        cropped
580            .write_to(&mut cur, image::ImageFormat::Png)
581            .map_err(|e| format!("encode png: {e}"))?;
582        "image/png".to_owned()
583    };
584    Ok((out, out_mime))
585}
586
587/// Re-encode an image's bytes to strip EXIF metadata. Returns
588/// `(Some(stripped_bytes), Some((width, height)))` on success; for
589/// non-image MIMEs or SVGs returns `(None, None)`; for decode errors
590/// returns `(None, None)` so the caller can keep the original bytes.
591///
592/// `image::DynamicImage::write_to` never emits EXIF, so the decode +
593/// re-encode pass is pixel-equivalent without GPS / camera serial /
594/// timestamp metadata leaking through.
595#[must_use]
596pub fn strip_exif_if_image(bytes: &[u8], mime: &str) -> (Option<Vec<u8>>, Option<(u32, u32)>) {
597    if !mime.starts_with("image/") || mime == "image/svg+xml" {
598        return (None, None);
599    }
600    let img = match image::load_from_memory(bytes) {
601        Ok(img) => img,
602        Err(e) => {
603            tracing::warn!(
604                target: "rustango_cms::rendition",
605                mime, error = %e,
606                "EXIF strip: decode failed, keeping original bytes"
607            );
608            return (None, None);
609        }
610    };
611    let dims = (img.width(), img.height());
612    let format = match mime {
613        "image/jpeg" | "image/jpg" => image::ImageFormat::Jpeg,
614        "image/png" => image::ImageFormat::Png,
615        "image/webp" => image::ImageFormat::WebP,
616        "image/gif" => image::ImageFormat::Gif,
617        "image/avif" => image::ImageFormat::Avif,
618        // Fall back to PNG (lossless) for less-common inputs.
619        _ => image::ImageFormat::Png,
620    };
621    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
622    {
623        let mut cur = std::io::Cursor::new(&mut out);
624        if let Err(e) = img.write_to(&mut cur, format) {
625            tracing::warn!(
626                target: "rustango_cms::rendition",
627                mime, error = %e,
628                "EXIF strip: re-encode failed, keeping original bytes"
629            );
630            return (None, Some(dims));
631        }
632    }
633    (Some(out), Some(dims))
634}
635
636// ---------- Tera integration ----------
637
638/// Register `rcms_image_url(media_id, filter)` on the user's Tera
639/// instance. Templates write
640/// `<img src="{{ rcms_image_url(media_id=42, filter="fill-300x200") }}">`
641/// and the URL gets resolved lazily by the
642/// [`crate::rendition_route::router`] route. The function only
643/// validates the filter spec; it does NOT touch the DB, so it stays
644/// sync + cheap.
645///
646/// Call once during Tera setup, alongside
647/// `rustango_cms::admin::register_templates(&mut tera)`.
648pub fn register_tera_function(tera: &mut tera::Tera) {
649    tera.register_function("rcms_image_url", RcmsImageUrlFn);
650    // #426 — responsive helpers. `srcset` emits the `srcset` value;
651    // `picture` emits a full multi-format `<picture>`.
652    tera.register_function("rcms_image_srcset", RcmsImageSrcsetFn);
653    tera.register_function("rcms_image_srcset_dpi", RcmsImageSrcsetDpiFn);
654    tera.register_function("rcms_picture", RcmsPictureFn);
655}
656
657/// `is_safe = true` so Tera autoescape doesn't mangle `/` into
658/// `&#x2F;` in the rendered URL. The output is a static-shape
659/// URL (`/__media__/<spec>/<id>[?v=<hash>]`) under CMS control —
660/// no user input flows into it.
661struct RcmsImageUrlFn;
662
663impl tera::Function for RcmsImageUrlFn {
664    fn call(
665        &self,
666        args: &std::collections::HashMap<String, tera::Value>,
667    ) -> tera::Result<tera::Value> {
668        rcms_image_url(args)
669    }
670    fn is_safe(&self) -> bool {
671        true
672    }
673}
674
675fn rcms_image_url(
676    args: &std::collections::HashMap<String, tera::Value>,
677) -> tera::Result<tera::Value> {
678    let media_id = parse_media_id_arg(args)
679        .ok_or_else(|| tera::Error::msg("rcms_image_url: `media_id` (i64) is required"))?;
680    let filter = args
681        .get("filter")
682        .and_then(tera::Value::as_str)
683        .ok_or_else(|| tera::Error::msg("rcms_image_url: `filter` (string) is required"))?;
684    let op =
685        FilterOp::parse(filter).map_err(|e| tera::Error::msg(format!("rcms_image_url: {e}")))?;
686    // Optional content-hash cache-buster. The route serves renditions
687    // with `Cache-Control: immutable`, so when the underlying bytes
688    // change (e.g. an in-place crop) the URL must change too. Callers
689    // pass `v=<media.content_hash>`; `rendition_url` truncates to 12
690    // hex chars. `rendition_url` also appends the `s=` signature when
691    // signed URLs are enabled (#425).
692    let v = args.get("v").and_then(tera::Value::as_str);
693    Ok(tera::Value::String(rendition_url(
694        media_id,
695        &op.canonical(),
696        v,
697    )))
698}
699
700// ---- #426 — responsive image helpers (srcset + <picture>) --------
701
702impl FilterOp {
703    /// Nominal target width for a `srcset` `w` descriptor. Height-only
704    /// specs have no width to advertise → `None` (skipped from srcset).
705    fn nominal_width(self) -> Option<u32> {
706        match self {
707            Self::Fill { w, .. } | Self::Max { w, .. } | Self::Width(w) => Some(w),
708            Self::Height(_) => None,
709        }
710    }
711
712    /// Multiply every pixel dimension by `factor` — the rendition for a
713    /// `factor`× pixel-density (retina) variant. Dimensions
714    /// saturate at the 8192 cap the parser enforces.
715    fn scaled(self, factor: u32) -> Self {
716        let cap = |n: u32| n.saturating_mul(factor).min(8192);
717        match self {
718            Self::Fill { w, h } => Self::Fill {
719                w: cap(w),
720                h: cap(h),
721            },
722            Self::Max { w, h } => Self::Max {
723                w: cap(w),
724                h: cap(h),
725            },
726            Self::Width(w) => Self::Width(cap(w)),
727            Self::Height(h) => Self::Height(cap(h)),
728        }
729    }
730}
731
732/// `media_id` arg shared by every image helper — accepts an `i64` or a
733/// trimmed non-empty stringified integer (the live-preview shape).
734fn parse_media_id_arg(args: &std::collections::HashMap<String, tera::Value>) -> Option<i64> {
735    args.get("media_id").and_then(|v| {
736        v.as_i64().or_else(|| {
737            v.as_str()
738                .map(str::trim)
739                .filter(|s| !s.is_empty())
740                .and_then(|s| s.parse::<i64>().ok())
741        })
742    })
743}
744
745/// Parse the `filters` arg (a Tera array of spec strings) into
746/// pipelines, surfacing a clear error on a bad spec or wrong shape.
747fn parse_filters_arg(
748    args: &std::collections::HashMap<String, tera::Value>,
749    fn_name: &str,
750) -> tera::Result<Vec<FilterPipeline>> {
751    let arr = args
752        .get("filters")
753        .and_then(|v| v.as_array())
754        .ok_or_else(|| {
755            tera::Error::msg(format!(
756                "{fn_name}: `filters` (array of spec strings) is required"
757            ))
758        })?;
759    arr.iter()
760        .map(|v| {
761            let s = v.as_str().ok_or_else(|| {
762                tera::Error::msg(format!("{fn_name}: each filter must be a string"))
763            })?;
764            FilterPipeline::parse(s).map_err(|e| tera::Error::msg(format!("{fn_name}: {e}")))
765        })
766        .collect()
767}
768
769/// Build a concrete rendition URL for `spec` — parsed + canonicalized,
770/// signed when signed URLs are enabled. Returns `None` for an
771/// invalid spec. `content_hash` is the optional `v=` cache-buster.
772/// Used by the JSON API to emit ready-to-use rendition URLs
773/// (clients can't sign a `{filter_spec}` template themselves).
774#[must_use]
775pub fn rendition_url_for(media_id: i64, spec: &str, content_hash: Option<&str>) -> Option<String> {
776    let pipeline = FilterPipeline::parse(spec).ok()?;
777    Some(rendition_url(media_id, &pipeline.canonical(), content_hash))
778}
779
780/// Build the rendition URL `/__media__/<spec>/<id>[?v=…][&s=…]` —
781/// signs it when signed URLs are enabled.
782fn rendition_url(media_id: i64, canonical_spec: &str, v: Option<&str>) -> String {
783    let base = match v {
784        Some(v) if !v.is_empty() => format!(
785            "/__media__/{canonical_spec}/{media_id}?v={}",
786            &v[..12.min(v.len())]
787        ),
788        _ => format!("/__media__/{canonical_spec}/{media_id}"),
789    };
790    maybe_sign(base, canonical_spec, media_id)
791}
792
793// ---- #425 — signed rendition URLs (enumeration / CPU-DoS guard) ----
794
795/// Process-wide signing key for rendition URLs. `None` = signing off.
796static SIGNING_KEY: std::sync::OnceLock<Option<Vec<u8>>> = std::sync::OnceLock::new();
797
798/// Enable **signed rendition URLs**. Once a key is set, every
799/// `rcms_image_url` / `rcms_image_srcset` / `rcms_picture` URL carries
800/// an HMAC `s=` over `(canonical_spec, media_id)`, and the rendition
801/// route ([`crate::rendition_route`]) rejects requests whose signature
802/// is missing or forged — closing the media-id-enumeration + arbitrary-
803/// spec CPU-DoS surface.
804///
805/// **Opt-in + backward compatible:** when no key is set (and the
806/// `RCMS_RENDITION_SIGNING_KEY` env var is unset) URLs stay unsigned and
807/// the route serves exactly as before.
808///
809/// Call once at startup, before serving. The key MUST be stable across
810/// restarts — URLs are baked into cached HTML, so a per-boot random key
811/// would 403 every image after a restart. Source it from your config.
812///
813/// The first read fixes the key, so a call after it — or a second call
814/// with another key — cannot take effect; it is logged as an error rather
815/// than dropped, since it can leave rendition signing off.
816pub fn set_signing_key(key: impl Into<Vec<u8>>) {
817    let key = key.into();
818    if let Err(rejected) = SIGNING_KEY.set(Some(key)) {
819        if SIGNING_KEY.get() != Some(&rejected) {
820            tracing::error!(
821                target: "rustango_cms::rendition",
822                "set_signing_key called after the key was already fixed (set earlier, or read \
823                 from RCMS_RENDITION_SIGNING_KEY); this call has no effect — set it before serving"
824            );
825        }
826    }
827}
828
829/// The active key, or `None` when signing is off. Falls back to the
830/// `RCMS_RENDITION_SIGNING_KEY` env var the first time it's read.
831fn signing_key() -> Option<&'static [u8]> {
832    SIGNING_KEY
833        .get_or_init(|| {
834            crate::config::var("RENDITION_SIGNING_KEY").map(String::into_bytes)
835        })
836        .as_deref()
837}
838
839/// HMAC-SHA256(key, "spec:id") truncated to 16 hex chars (64-bit — a
840/// short, URL-friendly MAC; ample against forgery for a DoS guard).
841fn rendition_sig(key: &[u8], canonical_spec: &str, media_id: i64) -> String {
842    let msg = format!("{canonical_spec}:{media_id}");
843    let full = crate::signing::hmac_sha256_hex(key, msg.as_bytes());
844    full[..16].to_owned()
845}
846
847/// Whether `supplied` is the correct signature for `(spec, id)` under
848/// `key`. Constant-time compare so a near-miss leaks nothing.
849fn sig_ok(key: &[u8], canonical_spec: &str, media_id: i64, supplied: Option<&str>) -> bool {
850    let expected = rendition_sig(key, canonical_spec, media_id);
851    supplied.is_some_and(|s| crate::signing::constant_time_eq(s.as_bytes(), expected.as_bytes()))
852}
853
854/// Append the `s=` signature when signing is enabled; pass the URL
855/// through untouched otherwise.
856fn maybe_sign(url: String, canonical_spec: &str, media_id: i64) -> String {
857    match signing_key() {
858        Some(key) => {
859            let sig = rendition_sig(key, canonical_spec, media_id);
860            let sep = if url.contains('?') { '&' } else { '?' };
861            format!("{url}{sep}s={sig}")
862        }
863        None => url,
864    }
865}
866
867/// Verify a rendition request's `s=` signature. Returns `true` when
868/// signing is disabled (open contract) OR `sig` matches `(spec, id)`.
869/// The route calls this before the DB lookup + rendition work so a
870/// forged request costs nothing.
871#[must_use]
872pub fn verify_rendition_sig(canonical_spec: &str, media_id: i64, sig: Option<&str>) -> bool {
873    match signing_key() {
874        None => true,
875        Some(key) => sig_ok(key, canonical_spec, media_id, sig),
876    }
877}
878
879/// `srcset` value from parsed specs: `"<url> <w>w, …"`. Height-only
880/// specs (no nominal width) are skipped.
881fn build_srcset(media_id: i64, specs: &[FilterPipeline], v: Option<&str>) -> String {
882    specs
883        .iter()
884        .filter_map(|sp| {
885            sp.geometric
886                .nominal_width()
887                .map(|w| format!("{} {w}w", rendition_url(media_id, &sp.canonical(), v)))
888        })
889        .collect::<Vec<_>>()
890        .join(", ")
891}
892
893/// `srcset` with pixel-density (`Nx`) descriptors (retina/DPI): the
894/// `base` spec rendered at each density — its dimensions multiplied by
895/// the density — e.g. `width-400` → `"…/width-400/42 1x, …/width-800/42 2x"`.
896/// Densities are de-duplicated + sorted ascending; non-positive dropped.
897fn build_dpi_srcset(
898    media_id: i64,
899    base: &FilterPipeline,
900    densities: &[u32],
901    v: Option<&str>,
902) -> String {
903    let mut ds: Vec<u32> = densities.iter().copied().filter(|d| *d > 0).collect();
904    ds.sort_unstable();
905    ds.dedup();
906    ds.iter()
907        .map(|d| {
908            let spec = FilterPipeline {
909                geometric: base.geometric.scaled(*d),
910                encoding: base.encoding,
911            };
912            format!("{} {d}x", rendition_url(media_id, &spec.canonical(), v))
913        })
914        .collect::<Vec<_>>()
915        .join(", ")
916}
917
918fn attr_escape(s: &str) -> String {
919    s.replace('&', "&amp;")
920        .replace('<', "&lt;")
921        .replace('>', "&gt;")
922        .replace('"', "&quot;")
923}
924
925/// `<source type=…>` MIME for a format token (the `<picture>` source
926/// selector). Unknown tokens are skipped by the caller.
927fn format_mime(fmt: &str) -> Option<&'static str> {
928    Some(match fmt {
929        "avif" => "image/avif",
930        "webp" | "auto" => "image/webp",
931        "jpeg" | "jpg" => "image/jpeg",
932        "png" => "image/png",
933        _ => return None,
934    })
935}
936
937/// Build a `<picture>`: one `<source>` per modern format (a
938/// `|format-X` variant of `specs`) + an `<img>` fallback (the base
939/// specs, widest as `src`). `alt`/`sizes` are HTML-attribute-escaped.
940fn build_picture(
941    media_id: i64,
942    specs: &[FilterPipeline],
943    formats: &[String],
944    alt: &str,
945    sizes: Option<&str>,
946    v: Option<&str>,
947) -> String {
948    let sizes_attr = sizes
949        .filter(|s| !s.is_empty())
950        .map(|s| format!(" sizes=\"{}\"", attr_escape(s)))
951        .unwrap_or_default();
952    let mut out = String::from("<picture>");
953    for fmt in formats {
954        let (Some(mime), Some(parsed)) = (format_mime(fmt), EncodeFormat::parse(fmt)) else {
955            continue;
956        };
957        let variant: Vec<FilterPipeline> = specs
958            .iter()
959            .map(|sp| {
960                let mut s = *sp;
961                s.encoding.format = Some(parsed);
962                s
963            })
964            .collect();
965        let srcset = build_srcset(media_id, &variant, v);
966        if !srcset.is_empty() {
967            out.push_str(&format!(
968                "<source type=\"{mime}\" srcset=\"{srcset}\"{sizes_attr}>"
969            ));
970        }
971    }
972    let base_srcset = build_srcset(media_id, specs, v);
973    let fallback = specs
974        .iter()
975        .max_by_key(|sp| sp.geometric.nominal_width().unwrap_or(0))
976        .map(|sp| rendition_url(media_id, &sp.canonical(), v))
977        .unwrap_or_default();
978    let srcset_attr = if base_srcset.is_empty() {
979        String::new()
980    } else {
981        format!(" srcset=\"{base_srcset}\"")
982    };
983    out.push_str(&format!(
984        "<img src=\"{fallback}\"{srcset_attr}{sizes_attr} alt=\"{}\" loading=\"lazy\" decoding=\"async\"></picture>",
985        attr_escape(alt),
986    ));
987    out
988}
989
990/// `rcms_image_srcset(media_id, filters=[…], [v])` → the `srcset`
991/// value (no markup). `is_safe` — output is CMS-controlled URLs.
992struct RcmsImageSrcsetFn;
993impl tera::Function for RcmsImageSrcsetFn {
994    fn call(
995        &self,
996        args: &std::collections::HashMap<String, tera::Value>,
997    ) -> tera::Result<tera::Value> {
998        let media_id = parse_media_id_arg(args)
999            .ok_or_else(|| tera::Error::msg("rcms_image_srcset: `media_id` (i64) is required"))?;
1000        let specs = parse_filters_arg(args, "rcms_image_srcset")?;
1001        let v = args.get("v").and_then(tera::Value::as_str);
1002        Ok(tera::Value::String(build_srcset(media_id, &specs, v)))
1003    }
1004    fn is_safe(&self) -> bool {
1005        true
1006    }
1007}
1008
1009/// `rcms_image_srcset_dpi(media_id, filter="width-400", [densities=[1,2]],
1010/// [v])` → a pixel-density `srcset` (`Nx` descriptors) of one base spec
1011/// at each density. `is_safe` — CMS-controlled URLs.
1012struct RcmsImageSrcsetDpiFn;
1013impl tera::Function for RcmsImageSrcsetDpiFn {
1014    fn call(
1015        &self,
1016        args: &std::collections::HashMap<String, tera::Value>,
1017    ) -> tera::Result<tera::Value> {
1018        let media_id = parse_media_id_arg(args).ok_or_else(|| {
1019            tera::Error::msg("rcms_image_srcset_dpi: `media_id` (i64) is required")
1020        })?;
1021        let filter = args
1022            .get("filter")
1023            .and_then(tera::Value::as_str)
1024            .ok_or_else(|| {
1025                tera::Error::msg("rcms_image_srcset_dpi: `filter` (string) is required")
1026            })?;
1027        let base = FilterPipeline::parse(filter)
1028            .map_err(|e| tera::Error::msg(format!("rcms_image_srcset_dpi: {e}")))?;
1029        let densities: Vec<u32> = args
1030            .get("densities")
1031            .and_then(|v| v.as_array())
1032            .map(|a| {
1033                a.iter()
1034                    .filter_map(|x| x.as_u64().map(|n| n as u32))
1035                    .collect()
1036            })
1037            .unwrap_or_else(|| vec![1, 2]);
1038        let v = args.get("v").and_then(tera::Value::as_str);
1039        Ok(tera::Value::String(build_dpi_srcset(
1040            media_id, &base, &densities, v,
1041        )))
1042    }
1043    fn is_safe(&self) -> bool {
1044        true
1045    }
1046}
1047
1048/// `rcms_picture(media_id, filters=[…], [formats=["avif","webp"]],
1049/// [alt], [sizes], [v])` → a full `<picture>`. `is_safe` — URLs are
1050/// CMS-controlled and `alt`/`sizes` are escaped internally.
1051struct RcmsPictureFn;
1052impl tera::Function for RcmsPictureFn {
1053    fn call(
1054        &self,
1055        args: &std::collections::HashMap<String, tera::Value>,
1056    ) -> tera::Result<tera::Value> {
1057        let media_id = parse_media_id_arg(args)
1058            .ok_or_else(|| tera::Error::msg("rcms_picture: `media_id` (i64) is required"))?;
1059        let specs = parse_filters_arg(args, "rcms_picture")?;
1060        let formats: Vec<String> = args
1061            .get("formats")
1062            .and_then(|v| v.as_array())
1063            .map(|a| {
1064                a.iter()
1065                    .filter_map(|x| x.as_str().map(str::to_owned))
1066                    .collect()
1067            })
1068            .unwrap_or_else(|| vec!["avif".to_owned(), "webp".to_owned()]);
1069        let alt = args.get("alt").and_then(tera::Value::as_str).unwrap_or("");
1070        let sizes = args.get("sizes").and_then(tera::Value::as_str);
1071        let v = args.get("v").and_then(tera::Value::as_str);
1072        Ok(tera::Value::String(build_picture(
1073            media_id, &specs, &formats, alt, sizes, v,
1074        )))
1075    }
1076    fn is_safe(&self) -> bool {
1077        true
1078    }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083    use super::*;
1084
1085    /// A large decode + re-encode must not freeze the runtime.
1086    #[rustango::__private_runtime::tokio::test(flavor = "current_thread")]
1087    async fn image_work_runs_off_the_runtime() {
1088        use rustango::__private_runtime::tokio;
1089        use std::sync::atomic::{AtomicUsize, Ordering};
1090        let img = image::RgbImage::from_fn(1200, 900, |x, y| image::Rgb([(x % 251) as u8, (y % 241) as u8, 90]));
1091        let mut jpeg = Vec::new();
1092        image::DynamicImage::ImageRgb8(img)
1093            .write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
1094            .expect("encode");
1095
1096        let ticks = std::sync::Arc::new(AtomicUsize::new(0));
1097        let t = std::sync::Arc::clone(&ticks);
1098        let ticker = tokio::spawn(async move {
1099            loop {
1100                tokio::time::sleep(std::time::Duration::from_millis(1)).await;
1101                t.fetch_add(1, Ordering::Relaxed);
1102            }
1103        });
1104        let (stored, dims) = strip_exif_off_runtime(jpeg, "image/jpeg".into()).await;
1105        let after_strip = ticks.load(Ordering::Relaxed);
1106        let (cropped, _) = crop_image_off_runtime(stored, "image/jpeg".into(), (0, 0, 600, 450))
1107            .await
1108            .expect("crop");
1109        let after_crop = ticks.load(Ordering::Relaxed);
1110        ticker.abort();
1111        assert_eq!(dims, Some((1200, 900)));
1112        assert!(!cropped.is_empty());
1113        assert!(after_strip >= 2, "strip stalled the runtime ({after_strip} ticks)");
1114        assert!(after_crop >= after_strip + 2, "crop stalled the runtime");
1115    }
1116
1117    #[test]
1118    fn bgcolor_with_non_ascii_bytes_is_an_error_not_a_panic() {
1119        assert!(FilterPipeline::parse("width-10|bgcolor-a\u{e9}\u{20ac}").is_err());
1120        assert!(FilterPipeline::parse("width-10|bgcolor-a\u{e9}").is_err());
1121        assert!(FilterPipeline::parse("width-10|bgcolor-fff").is_ok());
1122    }
1123
1124    #[test]
1125    fn parses_fill() {
1126        assert_eq!(
1127            FilterOp::parse("fill-300x200").unwrap(),
1128            FilterOp::Fill { w: 300, h: 200 }
1129        );
1130    }
1131
1132    #[test]
1133    fn parses_max() {
1134        assert_eq!(
1135            FilterOp::parse("max-1200x900").unwrap(),
1136            FilterOp::Max { w: 1200, h: 900 }
1137        );
1138    }
1139
1140    #[test]
1141    fn parses_width() {
1142        assert_eq!(FilterOp::parse("width-800").unwrap(), FilterOp::Width(800));
1143    }
1144
1145    #[test]
1146    fn parses_height() {
1147        assert_eq!(
1148            FilterOp::parse("height-600").unwrap(),
1149            FilterOp::Height(600)
1150        );
1151    }
1152
1153    #[test]
1154    fn rejects_garbage() {
1155        assert!(FilterOp::parse("nope").is_err());
1156        assert!(FilterOp::parse("fill-30000x30000").is_err()); // > 8192
1157        assert!(FilterOp::parse("fill-0x0").is_err());
1158        assert!(FilterOp::parse("fill-300").is_err());
1159    }
1160
1161    #[test]
1162    fn canonical_roundtrips() {
1163        for raw in ["fill-300x200", "max-1200x900", "width-800", "height-600"] {
1164            let parsed = FilterOp::parse(raw).unwrap();
1165            assert_eq!(parsed.canonical(), raw);
1166        }
1167    }
1168
1169    // --- #253 — rcms_image_url Tera function registration + arg shape
1170
1171    fn fresh_tera() -> tera::Tera {
1172        let mut tera = tera::Tera::default();
1173        register_tera_function(&mut tera);
1174        tera
1175    }
1176
1177    fn render_one(src: &str, ctx_values: &[(&str, tera::Value)]) -> tera::Result<String> {
1178        let mut tera = fresh_tera();
1179        tera.add_raw_template("t.html", src)?;
1180        let mut ctx = tera::Context::new();
1181        for (k, v) in ctx_values {
1182            ctx.insert(*k, v);
1183        }
1184        tera.render("t.html", &ctx)
1185    }
1186
1187    #[test]
1188    fn image_url_accepts_int_id() {
1189        let out = render_one(
1190            r#"{{ rcms_image_url(media_id=42, filter="width-1600") }}"#,
1191            &[],
1192        )
1193        .unwrap();
1194        assert_eq!(out, "/__media__/width-1600/42");
1195    }
1196
1197    #[test]
1198    fn image_url_accepts_stringified_id() {
1199        // Stream-block storage shape — the block JSON carries
1200        // `media_id` as a string after live-preview / form posts.
1201        let out = render_one(
1202            r#"{{ rcms_image_url(media_id=v, filter="width-1600") }}"#,
1203            &[("v", tera::Value::String("99".to_owned()))],
1204        )
1205        .unwrap();
1206        assert_eq!(out, "/__media__/width-1600/99");
1207    }
1208
1209    #[test]
1210    fn image_url_trims_whitespace_around_string_id() {
1211        let out = render_one(
1212            r#"{{ rcms_image_url(media_id=v, filter="max-1200x900") }}"#,
1213            &[("v", tera::Value::String("  17  ".to_owned()))],
1214        )
1215        .unwrap();
1216        assert_eq!(out, "/__media__/max-1200x900/17");
1217    }
1218
1219    #[test]
1220    fn image_url_empty_string_id_errors() {
1221        let err = render_one(
1222            r#"{{ rcms_image_url(media_id=v, filter="width-1600") }}"#,
1223            &[("v", tera::Value::String("".to_owned()))],
1224        )
1225        .unwrap_err();
1226        assert!(
1227            format!("{err:?}").contains("media_id"),
1228            "expected media_id error, got `{err:?}`"
1229        );
1230    }
1231
1232    #[test]
1233    fn image_url_missing_filter_errors() {
1234        let err = render_one(r#"{{ rcms_image_url(media_id=42) }}"#, &[]).unwrap_err();
1235        assert!(
1236            format!("{err:?}").contains("filter"),
1237            "expected filter error, got `{err:?}`"
1238        );
1239    }
1240
1241    #[test]
1242    fn image_url_with_content_hash_buster() {
1243        let out = render_one(
1244            r#"{{ rcms_image_url(media_id=42, filter="width-800", v="abc123def456hash") }}"#,
1245            &[],
1246        )
1247        .unwrap();
1248        assert_eq!(out, "/__media__/width-800/42?v=abc123def456");
1249    }
1250
1251    // --- #79 — encoding pipeline -------------------------------
1252
1253    #[test]
1254    fn pipeline_parses_bare_resize() {
1255        let p = FilterPipeline::parse("fill-300x200").unwrap();
1256        assert_eq!(p.geometric, FilterOp::Fill { w: 300, h: 200 });
1257        assert_eq!(p.encoding, EncodingOps::default());
1258    }
1259
1260    #[test]
1261    fn pipeline_parses_chained_encoding() {
1262        let p = FilterPipeline::parse("fill-300x200|format-webp|quality-75|bgcolor-fff").unwrap();
1263        assert_eq!(p.geometric, FilterOp::Fill { w: 300, h: 200 });
1264        assert_eq!(p.encoding.format, Some(EncodeFormat::Webp));
1265        assert_eq!(p.encoding.quality, Some(75));
1266        assert_eq!(p.encoding.background, Some((255, 255, 255)));
1267    }
1268
1269    #[test]
1270    fn pipeline_canonical_roundtrips() {
1271        // #398 — AVIF specs now parse (encoding is gated behind the
1272        // `avif` feature, but the URL spec is always recognized).
1273        let raw = "max-1200x900|format-avif|quality-80";
1274        let parsed = FilterPipeline::parse(raw).unwrap();
1275        assert_eq!(parsed.encoding.format, Some(EncodeFormat::Avif));
1276        assert_eq!(parsed.canonical(), raw);
1277        let raw = "fill-300x200|format-webp|quality-75|bgcolor-ffffff";
1278        let parsed = FilterPipeline::parse(raw).unwrap();
1279        assert_eq!(parsed.canonical(), raw);
1280    }
1281
1282    #[test]
1283    #[cfg(not(feature = "avif"))]
1284    fn avif_encode_errors_clearly_without_feature() {
1285        let img = image::DynamicImage::new_rgb8(2, 2);
1286        let ops = EncodingOps {
1287            format: Some(EncodeFormat::Avif),
1288            quality: None,
1289            background: None,
1290        };
1291        let err = encode(&img, &ops, "image/png").unwrap_err();
1292        assert!(err.contains("avif"), "got: {err}");
1293    }
1294
1295    #[test]
1296    #[cfg(feature = "avif")]
1297    fn avif_encode_produces_avif_bytes() {
1298        let img = image::DynamicImage::new_rgb8(8, 8);
1299        let ops = EncodingOps {
1300            format: Some(EncodeFormat::Avif),
1301            quality: Some(50),
1302            background: None,
1303        };
1304        let (bytes, mime, ext) = encode(&img, &ops, "image/png").unwrap();
1305        assert!(!bytes.is_empty());
1306        assert_eq!(mime, "image/avif");
1307        assert_eq!(ext, "avif");
1308    }
1309
1310    #[test]
1311    fn pipeline_rejects_garbage_segments() {
1312        assert!(FilterPipeline::parse("fill-300x200|format-jpegxl").is_err());
1313        assert!(FilterPipeline::parse("fill-300x200|quality-0").is_err());
1314        assert!(FilterPipeline::parse("fill-300x200|quality-101").is_err());
1315        assert!(FilterPipeline::parse("fill-300x200|bgcolor-xxxx").is_err());
1316        assert!(FilterPipeline::parse("fill-300x200|nonsense").is_err());
1317    }
1318
1319    #[test]
1320    fn parse_hex_rgb_three_and_six_digit() {
1321        assert_eq!(super::parse_hex_rgb("fff"), Some((255, 255, 255)));
1322        assert_eq!(super::parse_hex_rgb("ff0000"), Some((255, 0, 0)));
1323        assert_eq!(super::parse_hex_rgb("#abcdef"), Some((171, 205, 239)));
1324        assert_eq!(super::parse_hex_rgb("ff"), None);
1325        assert_eq!(super::parse_hex_rgb("ffffff00"), None); // RGBA not supported
1326    }
1327}
1328
1329#[cfg(test)]
1330mod responsive_tests {
1331    use super::{build_dpi_srcset, build_picture, build_srcset, FilterPipeline};
1332
1333    fn specs(raw: &[&str]) -> Vec<FilterPipeline> {
1334        raw.iter()
1335            .map(|s| FilterPipeline::parse(s).unwrap())
1336            .collect()
1337    }
1338
1339    #[test]
1340    fn srcset_emits_url_and_width_descriptor() {
1341        let out = build_srcset(42, &specs(&["fill-400x300", "fill-800x600"]), None);
1342        assert_eq!(
1343            out,
1344            "/__media__/fill-400x300/42 400w, /__media__/fill-800x600/42 800w"
1345        );
1346    }
1347
1348    #[test]
1349    fn srcset_skips_height_only_specs() {
1350        // `height-200` has no nominal width → dropped; `width-600` stays.
1351        let out = build_srcset(7, &specs(&["height-200", "width-600"]), None);
1352        assert_eq!(out, "/__media__/width-600/7 600w");
1353    }
1354
1355    #[test]
1356    fn srcset_appends_cache_buster_truncated() {
1357        let out = build_srcset(1, &specs(&["width-300"]), Some("0123456789abcdef"));
1358        assert_eq!(out, "/__media__/width-300/1?v=0123456789ab 300w");
1359    }
1360
1361    #[test]
1362    fn dpi_srcset_scales_width_per_density() {
1363        let base = FilterPipeline::parse("width-400").unwrap();
1364        assert_eq!(
1365            build_dpi_srcset(42, &base, &[1, 2], None),
1366            "/__media__/width-400/42 1x, /__media__/width-800/42 2x"
1367        );
1368    }
1369
1370    #[test]
1371    fn dpi_srcset_scales_both_fill_dims_and_dedups_densities() {
1372        let base = FilterPipeline::parse("fill-200x100").unwrap();
1373        // Densities deduped + sorted + 0 dropped.
1374        let out = build_dpi_srcset(7, &base, &[2, 1, 2, 0], None);
1375        assert_eq!(
1376            out,
1377            "/__media__/fill-200x100/7 1x, /__media__/fill-400x200/7 2x"
1378        );
1379    }
1380
1381    #[test]
1382    fn dpi_srcset_caps_at_8192() {
1383        let base = FilterPipeline::parse("width-5000").unwrap();
1384        // 5000×2 = 10000 → capped to 8192.
1385        assert_eq!(
1386            build_dpi_srcset(1, &base, &[2], None),
1387            "/__media__/width-8192/1 2x"
1388        );
1389    }
1390
1391    #[test]
1392    fn rendition_url_for_parses_and_rejects_bad_spec() {
1393        // #431 — the public API builder: canonicalizes + (with no
1394        // signing key in tests) emits the plain URL; bad spec → None.
1395        assert_eq!(
1396            super::rendition_url_for(42, "width-800", Some("abc123def456ZZ")),
1397            Some("/__media__/width-800/42?v=abc123def456".to_owned())
1398        );
1399        assert_eq!(super::rendition_url_for(42, "not-a-spec", None), None);
1400    }
1401
1402    #[test]
1403    fn picture_has_source_per_format_and_img_fallback() {
1404        let html = build_picture(
1405            42,
1406            &specs(&["width-400", "width-800"]),
1407            &["avif".to_owned(), "webp".to_owned()],
1408            "A <photo> & more",
1409            Some("100vw"),
1410            None,
1411        );
1412        // One <source> per format, with the format folded into the spec.
1413        assert!(html.contains(r#"<source type="image/avif" srcset="/__media__/width-400|format-avif/42 400w, /__media__/width-800|format-avif/42 800w" sizes="100vw">"#), "{html}");
1414        assert!(html.contains(r#"<source type="image/webp" srcset="/__media__/width-400|format-webp/42 400w, /__media__/width-800|format-webp/42 800w" sizes="100vw">"#), "{html}");
1415        // Fallback <img>: widest as src + base srcset, alt escaped.
1416        assert!(
1417            html.contains(r#"<img src="/__media__/width-800/42""#),
1418            "{html}"
1419        );
1420        assert!(
1421            html.contains(r#"alt="A &lt;photo&gt; &amp; more""#),
1422            "{html}"
1423        );
1424        assert!(
1425            html.starts_with("<picture>") && html.ends_with("</picture>"),
1426            "{html}"
1427        );
1428    }
1429
1430    #[test]
1431    fn picture_skips_unknown_format_token() {
1432        let html = build_picture(
1433            5,
1434            &specs(&["width-500"]),
1435            &["bogus".to_owned(), "webp".to_owned()],
1436            "",
1437            None,
1438            None,
1439        );
1440        assert!(!html.contains("bogus"), "{html}");
1441        assert!(html.contains(r#"type="image/webp""#), "{html}");
1442    }
1443
1444    #[test]
1445    fn tera_functions_render_end_to_end() {
1446        // Exercises the `filters=[…]` array-arg parsing + registration
1447        // + the `is_safe` (no slash-escaping) contract.
1448        let mut tera = tera::Tera::default();
1449        super::register_tera_function(&mut tera);
1450        tera.add_raw_template(
1451            "s.html",
1452            r#"{{ rcms_image_srcset(media_id=42, filters=["width-400", "width-800"]) }}"#,
1453        )
1454        .unwrap();
1455        assert_eq!(
1456            tera.render("s.html", &tera::Context::new()).unwrap(),
1457            "/__media__/width-400/42 400w, /__media__/width-800/42 800w"
1458        );
1459        tera.add_raw_template(
1460            "p.html",
1461            r#"{{ rcms_picture(media_id=7, filters=["width-600"], formats=["webp"], alt="hi") }}"#,
1462        )
1463        .unwrap();
1464        let p = tera.render("p.html", &tera::Context::new()).unwrap();
1465        assert!(p.contains(r#"type="image/webp""#), "{p}");
1466        assert!(p.contains(r#"alt="hi""#), "{p}");
1467        assert!(p.starts_with("<picture>"), "{p}");
1468    }
1469}
1470
1471#[cfg(test)]
1472mod sign_tests {
1473    use super::{maybe_sign, rendition_sig, sig_ok, verify_rendition_sig};
1474
1475    #[test]
1476    fn sig_is_deterministic_16_hex_and_input_sensitive() {
1477        let k = b"secret";
1478        let a = rendition_sig(k, "fill-400x300", 42);
1479        assert_eq!(a.len(), 16);
1480        assert!(a.chars().all(|c| c.is_ascii_hexdigit()), "{a}");
1481        assert_eq!(a, rendition_sig(k, "fill-400x300", 42)); // stable
1482        assert_ne!(a, rendition_sig(k, "fill-400x300", 43)); // media id
1483        assert_ne!(a, rendition_sig(k, "fill-401x300", 42)); // spec
1484        assert_ne!(a, rendition_sig(b"other-key", "fill-400x300", 42)); // key
1485    }
1486
1487    #[test]
1488    fn sig_ok_accepts_correct_rejects_forged_or_missing() {
1489        let k = b"secret";
1490        let good = rendition_sig(k, "width-800", 7);
1491        assert!(sig_ok(k, "width-800", 7, Some(&good)));
1492        assert!(!sig_ok(k, "width-800", 7, Some("deadbeefdeadbeef"))); // forged
1493        assert!(!sig_ok(k, "width-800", 7, None)); // missing
1494        assert!(!sig_ok(k, "width-800", 8, Some(&good))); // right sig, wrong id
1495    }
1496
1497    #[test]
1498    fn disabled_signing_is_open_and_unsigned() {
1499        // No key configured (and RCMS_RENDITION_SIGNING_KEY unset in the
1500        // test env) → signing off: URLs pass through untouched and every
1501        // request verifies. This is the default, backward-compatible path.
1502        assert_eq!(
1503            maybe_sign("/__media__/width-800/7".to_owned(), "width-800", 7),
1504            "/__media__/width-800/7"
1505        );
1506        assert!(verify_rendition_sig("width-800", 7, None));
1507    }
1508}