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    /// Pick for the image: JPEG for an opaque raster image, PNG (or
132    /// WebP for a WebP source) when it has transparent pixels. Also
133    /// what happens when no format is given. See [`auto_format`].
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/// The output format for `format-auto` or no format at all.
392///
393/// Lossless PNG and WebP keep photos at megabytes, so an image with
394/// no transparent pixel becomes a JPEG; one with transparency keeps
395/// it (WebP stays WebP, everything else becomes PNG). An alpha
396/// channel whose pixels are all opaque counts as opaque — many photos
397/// are saved as RGBA without using it.
398#[must_use]
399pub fn auto_format(image: &image::DynamicImage, source_mime: &str) -> EncodeFormat {
400    if !has_transparency(image) {
401        EncodeFormat::Jpeg
402    } else if source_mime == "image/webp" {
403        EncodeFormat::Webp
404    } else {
405        EncodeFormat::Png
406    }
407}
408
409/// Whether any pixel is less than fully opaque.
410fn has_transparency(image: &image::DynamicImage) -> bool {
411    if !image.color().has_alpha() {
412        return false;
413    }
414    match image.as_rgba8() {
415        Some(buf) => buf.pixels().any(|p| p[3] < u8::MAX),
416        None => image.to_rgba8().pixels().any(|p| p[3] < u8::MAX),
417    }
418}
419
420/// Encode `image` per the supplied [`EncodingOps`], applying
421/// background-color flattening when targeting a non-alpha format
422/// (JPEG). Returns `(bytes, mime, extension)`. With no format, or
423/// `format-auto`, the format comes from [`auto_format`].
424///
425/// # Errors
426/// Encoder failures from the [`image`] crate.
427pub fn encode(
428    image: &image::DynamicImage,
429    encoding: &EncodingOps,
430    source_mime: &str,
431) -> Result<(Vec<u8>, String, String), String> {
432    use image::codecs::jpeg::JpegEncoder;
433    let format = match encoding.format {
434        None | Some(EncodeFormat::Auto) => auto_format(image, source_mime),
435        Some(explicit) => explicit,
436    };
437
438    // Background-color flatten when targeting a non-alpha format.
439    // PNG + WebP both honour alpha; JPEG doesn't.
440    let needs_flatten = matches!(format, EncodeFormat::Jpeg) || encoding.background.is_some();
441    let prepared: image::DynamicImage = if needs_flatten && encoding.background.is_some() {
442        let (r, g, b) = encoding.background.unwrap();
443        flatten_onto_background(image, r, g, b)
444    } else if matches!(format, EncodeFormat::Jpeg) && image.color().has_alpha() {
445        // No explicit bgcolor but JPEG demands opaque — flatten on
446        // white by default.
447        flatten_onto_background(image, 255, 255, 255)
448    } else {
449        image.clone()
450    };
451
452    let mut out: Vec<u8> = Vec::new();
453    match format {
454        EncodeFormat::Jpeg => {
455            let quality = encoding.quality.unwrap_or(85);
456            let mut cur = std::io::Cursor::new(&mut out);
457            let mut enc = JpegEncoder::new_with_quality(&mut cur, quality);
458            enc.encode_image(&prepared)
459                .map_err(|e| format!("encode jpeg: {e}"))?;
460        }
461        EncodeFormat::Png => {
462            // PNG is lossless; `quality` doesn't apply.
463            let mut cur = std::io::Cursor::new(&mut out);
464            prepared
465                .write_to(&mut cur, image::ImageFormat::Png)
466                .map_err(|e| format!("encode png: {e}"))?;
467        }
468        EncodeFormat::Webp | EncodeFormat::Auto => {
469            // The `image` crate's WebP encoder is lossless by
470            // default. The `quality` knob is accepted for API
471            // symmetry but ignored — swapping in a lossy WebP
472            // encoder is a feature-flag follow-up.
473            let mut cur = std::io::Cursor::new(&mut out);
474            prepared
475                .write_to(&mut cur, image::ImageFormat::WebP)
476                .map_err(|e| format!("encode webp: {e}"))?;
477        }
478        EncodeFormat::Avif => {
479            // #398 — AVIF, gated behind the `avif` feature (pulls the
480            // ravif/rav1e encoder). AVIF supports alpha, so no flatten.
481            #[cfg(feature = "avif")]
482            {
483                // Quality 1..=100; default 61.
484                // Speed 1..=10 (higher = faster/larger); 4 balances both.
485                let quality = encoding.quality.unwrap_or(61);
486                let mut cur = std::io::Cursor::new(&mut out);
487                let enc =
488                    image::codecs::avif::AvifEncoder::new_with_speed_quality(&mut cur, 4, quality);
489                prepared
490                    .write_with_encoder(enc)
491                    .map_err(|e| format!("encode avif: {e}"))?;
492            }
493            #[cfg(not(feature = "avif"))]
494            {
495                let _ = &prepared;
496                return Err(
497                    "AVIF output requires building rustango-cms with the `avif` feature".to_owned(),
498                );
499            }
500        }
501    }
502    Ok((out, format.mime().to_owned(), format.ext().to_owned()))
503}
504
505/// Composite `src` onto a solid (r, g, b) background. Used by the
506/// JPEG path (no alpha) + the explicit `bgcolor-XYZ` op.
507fn flatten_onto_background(src: &image::DynamicImage, r: u8, g: u8, b: u8) -> image::DynamicImage {
508    use image::GenericImageView;
509    let (w, h) = src.dimensions();
510    let mut buf = image::RgbaImage::from_pixel(w, h, image::Rgba([r, g, b, 255]));
511    let rgba = src.to_rgba8();
512    image::imageops::overlay(&mut buf, &rgba, 0, 0);
513    image::DynamicImage::ImageRgba8(buf)
514}
515
516// ---------- Hard crop (#24) ----------
517
518/// [`crop_image`] on the blocking pool: a full decode + encode
519/// is hundreds of milliseconds of CPU for a large photo, and inline it
520/// parked a Tokio worker for all of it.
521///
522/// # Errors
523/// As [`crop_image`].
524pub async fn crop_image_off_runtime(
525    bytes: Vec<u8>,
526    source_mime: String,
527    (x, y, w, h): (u32, u32, u32, u32),
528) -> Result<(Vec<u8>, String), String> {
529    rustango::__private_runtime::tokio::task::spawn_blocking(move || {
530        crop_image(&bytes, &source_mime, x, y, w, h)
531    })
532    .await
533    .map_err(|e| format!("crop worker failed: {e}"))?
534}
535
536/// [`strip_exif_if_image`] on the blocking pool. Returns the bytes
537/// to store — the re-encoded ones when EXIF was stripped, else the input —
538/// and the decoded dimensions.
539pub async fn strip_exif_off_runtime(bytes: Vec<u8>, mime: String) -> (Vec<u8>, Option<(u32, u32)>) {
540    if !mime.starts_with("image/") || mime == "image/svg+xml" {
541        return (bytes, None);
542    }
543    rustango::__private_runtime::tokio::task::spawn_blocking(move || {
544        let (stripped, dims) = strip_exif_if_image(&bytes, &mime);
545        (stripped.unwrap_or(bytes), dims)
546    })
547    .await
548    .unwrap_or_else(|e| std::panic::resume_unwind(e.into_panic()))
549}
550
551/// Decode `bytes`, crop to `(x, y, w, h)` in source-pixel coords,
552/// and re-encode in the same format. Returns `(cropped_bytes, mime)`.
553/// SVG inputs are rejected — vector crop is a different surface.
554///
555/// # Errors
556/// * Image-decode failure (corrupt or unsupported format)
557/// * Crop rectangle outside the source bounds
558/// * Re-encode failure
559pub fn crop_image(
560    bytes: &[u8],
561    source_mime: &str,
562    x: u32,
563    y: u32,
564    w: u32,
565    h: u32,
566) -> Result<(Vec<u8>, String), String> {
567    if source_mime == "image/svg+xml" {
568        return Err(
569            "Cropping SVG sources isn't supported — clone first, edit the markup directly."
570                .to_owned(),
571        );
572    }
573    let img = image::load_from_memory(bytes).map_err(|e| format!("decode source: {e}"))?;
574    let (sw, sh) = (img.width(), img.height());
575    if w == 0 || h == 0 {
576        return Err("Crop rectangle must have non-zero width + height.".to_owned());
577    }
578    if x.saturating_add(w) > sw || y.saturating_add(h) > sh {
579        return Err(format!(
580            "Crop rectangle ({x},{y},{w},{h}) is outside the source ({sw}×{sh})."
581        ));
582    }
583    let cropped = img.crop_imm(x, y, w, h);
584    let mut out: Vec<u8> = Vec::new();
585    let out_mime = if source_mime == "image/jpeg" || source_mime == "image/jpg" {
586        let mut cur = std::io::Cursor::new(&mut out);
587        cropped
588            .write_to(&mut cur, image::ImageFormat::Jpeg)
589            .map_err(|e| format!("encode jpeg: {e}"))?;
590        "image/jpeg".to_owned()
591    } else if source_mime == "image/webp" {
592        let mut cur = std::io::Cursor::new(&mut out);
593        cropped
594            .write_to(&mut cur, image::ImageFormat::WebP)
595            .map_err(|e| format!("encode webp: {e}"))?;
596        "image/webp".to_owned()
597    } else {
598        // Default to PNG (lossless) for everything else — PNG, GIF,
599        // BMP all funnel into a PNG output. Editors who want a
600        // specific format can re-upload.
601        let mut cur = std::io::Cursor::new(&mut out);
602        cropped
603            .write_to(&mut cur, image::ImageFormat::Png)
604            .map_err(|e| format!("encode png: {e}"))?;
605        "image/png".to_owned()
606    };
607    Ok((out, out_mime))
608}
609
610/// Re-encode an image's bytes to strip EXIF metadata. Returns
611/// `(Some(stripped_bytes), Some((width, height)))` on success; for
612/// non-image MIMEs or SVGs returns `(None, None)`; for decode errors
613/// returns `(None, None)` so the caller can keep the original bytes.
614///
615/// `image::DynamicImage::write_to` never emits EXIF, so the decode +
616/// re-encode pass is pixel-equivalent without GPS / camera serial /
617/// timestamp metadata leaking through.
618#[must_use]
619pub fn strip_exif_if_image(bytes: &[u8], mime: &str) -> (Option<Vec<u8>>, Option<(u32, u32)>) {
620    if !mime.starts_with("image/") || mime == "image/svg+xml" {
621        return (None, None);
622    }
623    let img = match image::load_from_memory(bytes) {
624        Ok(img) => img,
625        Err(e) => {
626            tracing::warn!(
627                target: "rustango_cms::rendition",
628                mime, error = %e,
629                "EXIF strip: decode failed, keeping original bytes"
630            );
631            return (None, None);
632        }
633    };
634    let dims = (img.width(), img.height());
635    let format = match mime {
636        "image/jpeg" | "image/jpg" => image::ImageFormat::Jpeg,
637        "image/png" => image::ImageFormat::Png,
638        "image/webp" => image::ImageFormat::WebP,
639        "image/gif" => image::ImageFormat::Gif,
640        "image/avif" => image::ImageFormat::Avif,
641        // Fall back to PNG (lossless) for less-common inputs.
642        _ => image::ImageFormat::Png,
643    };
644    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
645    {
646        let mut cur = std::io::Cursor::new(&mut out);
647        if let Err(e) = img.write_to(&mut cur, format) {
648            tracing::warn!(
649                target: "rustango_cms::rendition",
650                mime, error = %e,
651                "EXIF strip: re-encode failed, keeping original bytes"
652            );
653            return (None, Some(dims));
654        }
655    }
656    (Some(out), Some(dims))
657}
658
659// ---------- Tera integration ----------
660
661/// Register `rcms_image_url(media_id, filter)` on the user's Tera
662/// instance. Templates write
663/// `<img src="{{ rcms_image_url(media_id=42, filter="fill-300x200") }}">`
664/// and the URL gets resolved lazily by the
665/// [`crate::rendition_route::router`] route. The function only
666/// validates the filter spec; it does NOT touch the DB, so it stays
667/// sync + cheap.
668///
669/// Call once during Tera setup, alongside
670/// `rustango_cms::admin::register_templates(&mut tera)`.
671pub fn register_tera_function(tera: &mut tera::Tera) {
672    tera.register_function("rcms_image_url", RcmsImageUrlFn);
673    // #426 — responsive helpers. `srcset` emits the `srcset` value;
674    // `picture` emits a full multi-format `<picture>`.
675    tera.register_function("rcms_image_srcset", RcmsImageSrcsetFn);
676    tera.register_function("rcms_image_srcset_dpi", RcmsImageSrcsetDpiFn);
677    tera.register_function("rcms_picture", RcmsPictureFn);
678}
679
680/// `is_safe = true` so Tera autoescape doesn't mangle `/` into
681/// `&#x2F;` in the rendered URL. The output is a static-shape
682/// URL (`/__media__/<spec>/<id>[?v=<hash>]`) under CMS control —
683/// no user input flows into it.
684struct RcmsImageUrlFn;
685
686impl tera::Function for RcmsImageUrlFn {
687    fn call(
688        &self,
689        args: &std::collections::HashMap<String, tera::Value>,
690    ) -> tera::Result<tera::Value> {
691        rcms_image_url(args)
692    }
693    fn is_safe(&self) -> bool {
694        true
695    }
696}
697
698fn rcms_image_url(
699    args: &std::collections::HashMap<String, tera::Value>,
700) -> tera::Result<tera::Value> {
701    let media_id = parse_media_id_arg(args)
702        .ok_or_else(|| tera::Error::msg("rcms_image_url: `media_id` (i64) is required"))?;
703    let filter = args
704        .get("filter")
705        .and_then(tera::Value::as_str)
706        .ok_or_else(|| tera::Error::msg("rcms_image_url: `filter` (string) is required"))?;
707    // A full pipeline (`width-800|format-jpeg`), like the srcset and
708    // picture helpers; a bare resize op is a pipeline with no hints.
709    let pipeline = FilterPipeline::parse(filter)
710        .map_err(|e| tera::Error::msg(format!("rcms_image_url: {e}")))?;
711    // Optional content-hash cache-buster. The route serves renditions
712    // with `Cache-Control: immutable`, so when the underlying bytes
713    // change (e.g. an in-place crop) the URL must change too. Callers
714    // pass `v=<media.content_hash>`; `rendition_url` truncates to 12
715    // hex chars. `rendition_url` also appends the `s=` signature when
716    // signed URLs are enabled (#425).
717    let v = args.get("v").and_then(tera::Value::as_str);
718    Ok(tera::Value::String(rendition_url(
719        media_id,
720        &pipeline.canonical(),
721        v,
722    )))
723}
724
725// ---- #426 — responsive image helpers (srcset + <picture>) --------
726
727impl FilterOp {
728    /// Nominal target width for a `srcset` `w` descriptor. Height-only
729    /// specs have no width to advertise → `None` (skipped from srcset).
730    fn nominal_width(self) -> Option<u32> {
731        match self {
732            Self::Fill { w, .. } | Self::Max { w, .. } | Self::Width(w) => Some(w),
733            Self::Height(_) => None,
734        }
735    }
736
737    /// Multiply every pixel dimension by `factor` — the rendition for a
738    /// `factor`× pixel-density (retina) variant. Dimensions
739    /// saturate at the 8192 cap the parser enforces.
740    fn scaled(self, factor: u32) -> Self {
741        let cap = |n: u32| n.saturating_mul(factor).min(8192);
742        match self {
743            Self::Fill { w, h } => Self::Fill {
744                w: cap(w),
745                h: cap(h),
746            },
747            Self::Max { w, h } => Self::Max {
748                w: cap(w),
749                h: cap(h),
750            },
751            Self::Width(w) => Self::Width(cap(w)),
752            Self::Height(h) => Self::Height(cap(h)),
753        }
754    }
755}
756
757/// `media_id` arg shared by every image helper — accepts an `i64` or a
758/// trimmed non-empty stringified integer (the live-preview shape).
759fn parse_media_id_arg(args: &std::collections::HashMap<String, tera::Value>) -> Option<i64> {
760    args.get("media_id").and_then(|v| {
761        v.as_i64().or_else(|| {
762            v.as_str()
763                .map(str::trim)
764                .filter(|s| !s.is_empty())
765                .and_then(|s| s.parse::<i64>().ok())
766        })
767    })
768}
769
770/// Parse the `filters` arg (a Tera array of spec strings) into
771/// pipelines, surfacing a clear error on a bad spec or wrong shape.
772fn parse_filters_arg(
773    args: &std::collections::HashMap<String, tera::Value>,
774    fn_name: &str,
775) -> tera::Result<Vec<FilterPipeline>> {
776    let arr = args
777        .get("filters")
778        .and_then(|v| v.as_array())
779        .ok_or_else(|| {
780            tera::Error::msg(format!(
781                "{fn_name}: `filters` (array of spec strings) is required"
782            ))
783        })?;
784    arr.iter()
785        .map(|v| {
786            let s = v.as_str().ok_or_else(|| {
787                tera::Error::msg(format!("{fn_name}: each filter must be a string"))
788            })?;
789            FilterPipeline::parse(s).map_err(|e| tera::Error::msg(format!("{fn_name}: {e}")))
790        })
791        .collect()
792}
793
794/// Build a concrete rendition URL for `spec` — parsed + canonicalized,
795/// signed when signed URLs are enabled. Returns `None` for an
796/// invalid spec. `content_hash` is the optional `v=` cache-buster.
797/// Used by the JSON API to emit ready-to-use rendition URLs
798/// (clients can't sign a `{filter_spec}` template themselves).
799#[must_use]
800pub fn rendition_url_for(media_id: i64, spec: &str, content_hash: Option<&str>) -> Option<String> {
801    let pipeline = FilterPipeline::parse(spec).ok()?;
802    Some(rendition_url(media_id, &pipeline.canonical(), content_hash))
803}
804
805/// Build the rendition URL `/__media__/<spec>/<id>[?v=…][&s=…]` —
806/// signs it when signed URLs are enabled.
807fn rendition_url(media_id: i64, canonical_spec: &str, v: Option<&str>) -> String {
808    let base = match v {
809        Some(v) if !v.is_empty() => format!(
810            "/__media__/{canonical_spec}/{media_id}?v={}",
811            &v[..12.min(v.len())]
812        ),
813        _ => format!("/__media__/{canonical_spec}/{media_id}"),
814    };
815    maybe_sign(base, canonical_spec, media_id)
816}
817
818// ---- #425 — signed rendition URLs (enumeration / CPU-DoS guard) ----
819
820/// The rendition signing key and how strictly it is enforced.
821#[derive(PartialEq, Eq)]
822struct SigningKey {
823    bytes: Vec<u8>,
824    /// Set explicitly (`set_signing_key` / `RCMS_RENDITION_SIGNING_KEY`):
825    /// every request must be signed. Otherwise the key is derived from
826    /// the CMS secret and an unsigned request is served, capped.
827    strict: bool,
828}
829
830static SIGNING_KEY: std::sync::OnceLock<SigningKey> = std::sync::OnceLock::new();
831
832/// Make rendition signing **strict** with your own key: every request to
833/// the rendition route must then carry a valid `s=` signature, so media
834/// ids can't be enumerated and no unsigned size is ever generated.
835///
836/// Without it, URLs the CMS renders (`rcms_image_url` / `rcms_image_srcset`
837/// / `rcms_picture`) are still signed — with a key derived from the CMS
838/// secret — and always served; unsigned URLs, such as the ones API clients
839/// build from `download_url_template`, are served too, but an anonymous
840/// visitor can only create [`max_unsigned_variants`] sizes of an image
841/// that way (#643).
842///
843/// Call once at startup, before serving. The key MUST be stable across
844/// restarts — URLs are baked into cached HTML, so a per-boot random key
845/// would 403 every image after a restart. Source it from your config.
846///
847/// The first read fixes the key, so a call after it — or a second call
848/// with another key — cannot take effect; it is logged as an error.
849pub fn set_signing_key(key: impl Into<Vec<u8>>) {
850    let key = SigningKey { bytes: key.into(), strict: true };
851    if let Err(rejected) = SIGNING_KEY.set(key) {
852        if SIGNING_KEY.get() != Some(&rejected) {
853            tracing::error!(
854                target: "rustango_cms::rendition",
855                "set_signing_key called after the key was already fixed (set earlier, or read \
856                 from RCMS_RENDITION_SIGNING_KEY); this call has no effect — set it before serving"
857            );
858        }
859    }
860}
861
862/// Fix the signing key (reading or generating the CMS key file if it is
863/// derived). The rendition router calls this at boot; call
864/// [`set_signing_key`] before it.
865pub fn init_signing() {
866    let _ = signing_key();
867}
868
869/// The active key: `set_signing_key`'s, else `RCMS_RENDITION_SIGNING_KEY`
870/// (both strict), else one derived from the CMS secret (lenient).
871fn signing_key() -> &'static SigningKey {
872    SIGNING_KEY.get_or_init(|| match crate::config::var("RENDITION_SIGNING_KEY") {
873        Some(k) => SigningKey { bytes: k.into_bytes(), strict: true },
874        None => {
875            tracing::info!(
876                target: "rustango_cms::rendition",
877                max_variants = max_unsigned_variants(),
878                "image URLs the CMS renders are signed; unsigned ones (API clients) are capped per \
879                 image — set RCMS_RENDITION_SIGNING_KEY to require a signature on every request"
880            );
881            SigningKey { bytes: crate::signing::derived_key("rendition-url"), strict: false }
882        }
883    })
884}
885
886/// Default for [`max_unsigned_variants`].
887pub const DEFAULT_MAX_UNSIGNED_VARIANTS: usize = 128;
888
889/// Without a strict key, the most distinct renditions unsigned anonymous
890/// requests may cause to exist for one image (#643):
891/// `RCMS_RENDITION_MAX_UNSIGNED`, else [`DEFAULT_MAX_UNSIGNED_VARIANTS`].
892/// Sizes already generated keep serving; a new one past the cap gets
893/// `429`. Signed URLs (every image URL the CMS renders) never count
894/// against it, so a visitor can't use up the slots a page needs.
895/// Signed-in editors are not capped.
896#[must_use]
897pub fn max_unsigned_variants() -> usize {
898    static MAX: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
899    *MAX.get_or_init(|| parse_max_unsigned(crate::config::var("RENDITION_MAX_UNSIGNED").as_deref()))
900}
901
902fn parse_max_unsigned(raw: Option<&str>) -> usize {
903    raw.and_then(|v| v.trim().parse::<usize>().ok())
904        .filter(|n| *n > 0)
905        .unwrap_or(DEFAULT_MAX_UNSIGNED_VARIANTS)
906}
907
908/// HMAC-SHA256(key, "spec:id") truncated to 16 hex chars (64-bit — a
909/// short, URL-friendly MAC; ample against forgery for a DoS guard).
910fn rendition_sig(key: &[u8], canonical_spec: &str, media_id: i64) -> String {
911    let msg = format!("{canonical_spec}:{media_id}");
912    let full = crate::signing::hmac_sha256_hex(key, msg.as_bytes());
913    full[..16].to_owned()
914}
915
916/// Whether `supplied` is the correct signature for `(spec, id)` under
917/// `key`. Constant-time compare so a near-miss leaks nothing.
918fn sig_ok(key: &[u8], canonical_spec: &str, media_id: i64, supplied: Option<&str>) -> bool {
919    let expected = rendition_sig(key, canonical_spec, media_id);
920    supplied.is_some_and(|s| crate::signing::constant_time_eq(s.as_bytes(), expected.as_bytes()))
921}
922
923/// Append the `s=` signature.
924fn maybe_sign(url: String, canonical_spec: &str, media_id: i64) -> String {
925    sign_with(&signing_key().bytes, url, canonical_spec, media_id)
926}
927
928fn sign_with(key: &[u8], url: String, canonical_spec: &str, media_id: i64) -> String {
929    let sig = rendition_sig(key, canonical_spec, media_id);
930    let sep = if url.contains('?') { '&' } else { '?' };
931    format!("{url}{sep}s={sig}")
932}
933
934/// What a rendition request's `s=` signature says.
935#[derive(Debug, Clone, Copy, PartialEq, Eq)]
936pub enum RenditionSig {
937    /// A valid signature: serve, uncapped.
938    Valid,
939    /// No valid signature, and no strict key: serve, capped for
940    /// anonymous visitors ([`max_unsigned_variants`]).
941    Unsigned,
942    /// No valid signature under a strict key: refuse.
943    Rejected,
944}
945
946/// Check a rendition request's signature. The route calls this before
947/// the DB lookup + rendition work so a forged request costs nothing.
948#[must_use]
949pub fn check_rendition_sig(canonical_spec: &str, media_id: i64, sig: Option<&str>) -> RenditionSig {
950    let key = signing_key();
951    classify_sig(&key.bytes, key.strict, canonical_spec, media_id, sig)
952}
953
954/// Under a derived (lenient) key a signature that doesn't verify counts
955/// as none: it may come from another replica's or an earlier process's
956/// generated key, or a page cached before a restart, and refusing it would
957/// break those images while a forged one gains nothing over no signature.
958fn classify_sig(key: &[u8], strict: bool, canonical_spec: &str, media_id: i64, sig: Option<&str>) -> RenditionSig {
959    if sig_ok(key, canonical_spec, media_id, sig) {
960        RenditionSig::Valid
961    } else if strict {
962        RenditionSig::Rejected
963    } else {
964        RenditionSig::Unsigned
965    }
966}
967
968/// `srcset` value from parsed specs: `"<url> <w>w, …"`. Height-only
969/// specs (no nominal width) are skipped.
970fn build_srcset(media_id: i64, specs: &[FilterPipeline], v: Option<&str>) -> String {
971    specs
972        .iter()
973        .filter_map(|sp| {
974            sp.geometric
975                .nominal_width()
976                .map(|w| format!("{} {w}w", rendition_url(media_id, &sp.canonical(), v)))
977        })
978        .collect::<Vec<_>>()
979        .join(", ")
980}
981
982/// `srcset` with pixel-density (`Nx`) descriptors (retina/DPI): the
983/// `base` spec rendered at each density — its dimensions multiplied by
984/// the density — e.g. `width-400` → `"…/width-400/42 1x, …/width-800/42 2x"`.
985/// Densities are de-duplicated + sorted ascending; non-positive dropped.
986fn build_dpi_srcset(
987    media_id: i64,
988    base: &FilterPipeline,
989    densities: &[u32],
990    v: Option<&str>,
991) -> String {
992    let mut ds: Vec<u32> = densities.iter().copied().filter(|d| *d > 0).collect();
993    ds.sort_unstable();
994    ds.dedup();
995    ds.iter()
996        .map(|d| {
997            let spec = FilterPipeline {
998                geometric: base.geometric.scaled(*d),
999                encoding: base.encoding,
1000            };
1001            format!("{} {d}x", rendition_url(media_id, &spec.canonical(), v))
1002        })
1003        .collect::<Vec<_>>()
1004        .join(", ")
1005}
1006
1007fn attr_escape(s: &str) -> String {
1008    s.replace('&', "&amp;")
1009        .replace('<', "&lt;")
1010        .replace('>', "&gt;")
1011        .replace('"', "&quot;")
1012}
1013
1014/// `<source type=…>` MIME for a format token (the `<picture>` source
1015/// selector). Unknown tokens are skipped by the caller.
1016fn format_mime(fmt: &str) -> Option<&'static str> {
1017    Some(match fmt {
1018        "avif" => "image/avif",
1019        "webp" => "image/webp",
1020        "jpeg" | "jpg" => "image/jpeg",
1021        "png" => "image/png",
1022        _ => return None,
1023    })
1024}
1025
1026/// Build a `<picture>`: one `<source>` per modern format (a
1027/// `|format-X` variant of `specs`) + an `<img>` fallback (the base
1028/// specs, widest as `src`). `alt`/`sizes` are HTML-attribute-escaped.
1029fn build_picture(
1030    media_id: i64,
1031    specs: &[FilterPipeline],
1032    formats: &[String],
1033    alt: &str,
1034    sizes: Option<&str>,
1035    v: Option<&str>,
1036) -> String {
1037    let sizes_attr = sizes
1038        .filter(|s| !s.is_empty())
1039        .map(|s| format!(" sizes=\"{}\"", attr_escape(s)))
1040        .unwrap_or_default();
1041    let mut out = String::from("<picture>");
1042    for fmt in formats {
1043        let (Some(mime), Some(parsed)) = (format_mime(fmt), EncodeFormat::parse(fmt)) else {
1044            continue;
1045        };
1046        let variant: Vec<FilterPipeline> = specs
1047            .iter()
1048            .map(|sp| {
1049                let mut s = *sp;
1050                s.encoding.format = Some(parsed);
1051                s
1052            })
1053            .collect();
1054        let srcset = build_srcset(media_id, &variant, v);
1055        if !srcset.is_empty() {
1056            out.push_str(&format!(
1057                "<source type=\"{mime}\" srcset=\"{srcset}\"{sizes_attr}>"
1058            ));
1059        }
1060    }
1061    let base_srcset = build_srcset(media_id, specs, v);
1062    let fallback = specs
1063        .iter()
1064        .max_by_key(|sp| sp.geometric.nominal_width().unwrap_or(0))
1065        .map(|sp| rendition_url(media_id, &sp.canonical(), v))
1066        .unwrap_or_default();
1067    let srcset_attr = if base_srcset.is_empty() {
1068        String::new()
1069    } else {
1070        format!(" srcset=\"{base_srcset}\"")
1071    };
1072    out.push_str(&format!(
1073        "<img src=\"{fallback}\"{srcset_attr}{sizes_attr} alt=\"{}\" loading=\"lazy\" decoding=\"async\"></picture>",
1074        attr_escape(alt),
1075    ));
1076    out
1077}
1078
1079/// `rcms_image_srcset(media_id, filters=[…], [v])` → the `srcset`
1080/// value (no markup). `is_safe` — output is CMS-controlled URLs.
1081struct RcmsImageSrcsetFn;
1082impl tera::Function for RcmsImageSrcsetFn {
1083    fn call(
1084        &self,
1085        args: &std::collections::HashMap<String, tera::Value>,
1086    ) -> tera::Result<tera::Value> {
1087        let media_id = parse_media_id_arg(args)
1088            .ok_or_else(|| tera::Error::msg("rcms_image_srcset: `media_id` (i64) is required"))?;
1089        let specs = parse_filters_arg(args, "rcms_image_srcset")?;
1090        let v = args.get("v").and_then(tera::Value::as_str);
1091        Ok(tera::Value::String(build_srcset(media_id, &specs, v)))
1092    }
1093    fn is_safe(&self) -> bool {
1094        true
1095    }
1096}
1097
1098/// `rcms_image_srcset_dpi(media_id, filter="width-400", [densities=[1,2]],
1099/// [v])` → a pixel-density `srcset` (`Nx` descriptors) of one base spec
1100/// at each density. `is_safe` — CMS-controlled URLs.
1101struct RcmsImageSrcsetDpiFn;
1102impl tera::Function for RcmsImageSrcsetDpiFn {
1103    fn call(
1104        &self,
1105        args: &std::collections::HashMap<String, tera::Value>,
1106    ) -> tera::Result<tera::Value> {
1107        let media_id = parse_media_id_arg(args).ok_or_else(|| {
1108            tera::Error::msg("rcms_image_srcset_dpi: `media_id` (i64) is required")
1109        })?;
1110        let filter = args
1111            .get("filter")
1112            .and_then(tera::Value::as_str)
1113            .ok_or_else(|| {
1114                tera::Error::msg("rcms_image_srcset_dpi: `filter` (string) is required")
1115            })?;
1116        let base = FilterPipeline::parse(filter)
1117            .map_err(|e| tera::Error::msg(format!("rcms_image_srcset_dpi: {e}")))?;
1118        let densities: Vec<u32> = args
1119            .get("densities")
1120            .and_then(|v| v.as_array())
1121            .map(|a| {
1122                a.iter()
1123                    .filter_map(|x| x.as_u64().map(|n| n as u32))
1124                    .collect()
1125            })
1126            .unwrap_or_else(|| vec![1, 2]);
1127        let v = args.get("v").and_then(tera::Value::as_str);
1128        Ok(tera::Value::String(build_dpi_srcset(
1129            media_id, &base, &densities, v,
1130        )))
1131    }
1132    fn is_safe(&self) -> bool {
1133        true
1134    }
1135}
1136
1137/// `rcms_picture(media_id, filters=[…], [formats=["avif","webp"]],
1138/// [alt], [sizes], [v])` → a full `<picture>`. `is_safe` — URLs are
1139/// CMS-controlled and `alt`/`sizes` are escaped internally.
1140struct RcmsPictureFn;
1141impl tera::Function for RcmsPictureFn {
1142    fn call(
1143        &self,
1144        args: &std::collections::HashMap<String, tera::Value>,
1145    ) -> tera::Result<tera::Value> {
1146        let media_id = parse_media_id_arg(args)
1147            .ok_or_else(|| tera::Error::msg("rcms_picture: `media_id` (i64) is required"))?;
1148        let specs = parse_filters_arg(args, "rcms_picture")?;
1149        let formats: Vec<String> = args
1150            .get("formats")
1151            .and_then(|v| v.as_array())
1152            .map(|a| {
1153                a.iter()
1154                    .filter_map(|x| x.as_str().map(str::to_owned))
1155                    .collect()
1156            })
1157            .unwrap_or_else(|| vec!["avif".to_owned(), "webp".to_owned()]);
1158        let alt = args.get("alt").and_then(tera::Value::as_str).unwrap_or("");
1159        let sizes = args.get("sizes").and_then(tera::Value::as_str);
1160        let v = args.get("v").and_then(tera::Value::as_str);
1161        Ok(tera::Value::String(build_picture(
1162            media_id, &specs, &formats, alt, sizes, v,
1163        )))
1164    }
1165    fn is_safe(&self) -> bool {
1166        true
1167    }
1168}
1169
1170#[cfg(test)]
1171mod tests {
1172    use super::*;
1173
1174    /// A large decode + re-encode must not freeze the runtime.
1175    #[rustango::__private_runtime::tokio::test(flavor = "current_thread")]
1176    async fn image_work_runs_off_the_runtime() {
1177        use rustango::__private_runtime::tokio;
1178        use std::sync::atomic::{AtomicUsize, Ordering};
1179        let img = image::RgbImage::from_fn(1200, 900, |x, y| image::Rgb([(x % 251) as u8, (y % 241) as u8, 90]));
1180        let mut jpeg = Vec::new();
1181        image::DynamicImage::ImageRgb8(img)
1182            .write_to(&mut std::io::Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
1183            .expect("encode");
1184
1185        let ticks = std::sync::Arc::new(AtomicUsize::new(0));
1186        let t = std::sync::Arc::clone(&ticks);
1187        let ticker = tokio::spawn(async move {
1188            loop {
1189                tokio::time::sleep(std::time::Duration::from_millis(1)).await;
1190                t.fetch_add(1, Ordering::Relaxed);
1191            }
1192        });
1193        let (stored, dims) = strip_exif_off_runtime(jpeg, "image/jpeg".into()).await;
1194        let after_strip = ticks.load(Ordering::Relaxed);
1195        let (cropped, _) = crop_image_off_runtime(stored, "image/jpeg".into(), (0, 0, 600, 450))
1196            .await
1197            .expect("crop");
1198        let after_crop = ticks.load(Ordering::Relaxed);
1199        ticker.abort();
1200        assert_eq!(dims, Some((1200, 900)));
1201        assert!(!cropped.is_empty());
1202        assert!(after_strip >= 2, "strip stalled the runtime ({after_strip} ticks)");
1203        assert!(after_crop >= after_strip + 2, "crop stalled the runtime");
1204    }
1205
1206    #[test]
1207    fn bgcolor_with_non_ascii_bytes_is_an_error_not_a_panic() {
1208        assert!(FilterPipeline::parse("width-10|bgcolor-a\u{e9}\u{20ac}").is_err());
1209        assert!(FilterPipeline::parse("width-10|bgcolor-a\u{e9}").is_err());
1210        assert!(FilterPipeline::parse("width-10|bgcolor-fff").is_ok());
1211    }
1212
1213    #[test]
1214    fn parses_fill() {
1215        assert_eq!(
1216            FilterOp::parse("fill-300x200").unwrap(),
1217            FilterOp::Fill { w: 300, h: 200 }
1218        );
1219    }
1220
1221    #[test]
1222    fn parses_max() {
1223        assert_eq!(
1224            FilterOp::parse("max-1200x900").unwrap(),
1225            FilterOp::Max { w: 1200, h: 900 }
1226        );
1227    }
1228
1229    #[test]
1230    fn parses_width() {
1231        assert_eq!(FilterOp::parse("width-800").unwrap(), FilterOp::Width(800));
1232    }
1233
1234    #[test]
1235    fn parses_height() {
1236        assert_eq!(
1237            FilterOp::parse("height-600").unwrap(),
1238            FilterOp::Height(600)
1239        );
1240    }
1241
1242    #[test]
1243    fn rejects_garbage() {
1244        assert!(FilterOp::parse("nope").is_err());
1245        assert!(FilterOp::parse("fill-30000x30000").is_err()); // > 8192
1246        assert!(FilterOp::parse("fill-0x0").is_err());
1247        assert!(FilterOp::parse("fill-300").is_err());
1248    }
1249
1250    #[test]
1251    fn canonical_roundtrips() {
1252        for raw in ["fill-300x200", "max-1200x900", "width-800", "height-600"] {
1253            let parsed = FilterOp::parse(raw).unwrap();
1254            assert_eq!(parsed.canonical(), raw);
1255        }
1256    }
1257
1258    // --- #253 — rcms_image_url Tera function registration + arg shape
1259
1260    fn fresh_tera() -> tera::Tera {
1261        let mut tera = tera::Tera::default();
1262        register_tera_function(&mut tera);
1263        tera
1264    }
1265
1266    fn render_one(src: &str, ctx_values: &[(&str, tera::Value)]) -> tera::Result<String> {
1267        let mut tera = fresh_tera();
1268        tera.add_raw_template("t.html", src)?;
1269        let mut ctx = tera::Context::new();
1270        for (k, v) in ctx_values {
1271            ctx.insert(*k, v);
1272        }
1273        tera.render("t.html", &ctx)
1274    }
1275
1276    #[test]
1277    fn image_url_accepts_int_id() {
1278        let out = render_one(
1279            r#"{{ rcms_image_url(media_id=42, filter="width-1600") }}"#,
1280            &[],
1281        )
1282        .unwrap();
1283        assert_eq!(crate::rendition::strip_sig(&out), "/__media__/width-1600/42");
1284    }
1285
1286    #[test]
1287    fn image_url_accepts_stringified_id() {
1288        // Stream-block storage shape — the block JSON carries
1289        // `media_id` as a string after live-preview / form posts.
1290        let out = render_one(
1291            r#"{{ rcms_image_url(media_id=v, filter="width-1600") }}"#,
1292            &[("v", tera::Value::String("99".to_owned()))],
1293        )
1294        .unwrap();
1295        assert_eq!(crate::rendition::strip_sig(&out), "/__media__/width-1600/99");
1296    }
1297
1298    #[test]
1299    fn image_url_trims_whitespace_around_string_id() {
1300        let out = render_one(
1301            r#"{{ rcms_image_url(media_id=v, filter="max-1200x900") }}"#,
1302            &[("v", tera::Value::String("  17  ".to_owned()))],
1303        )
1304        .unwrap();
1305        assert_eq!(crate::rendition::strip_sig(&out), "/__media__/max-1200x900/17");
1306    }
1307
1308    #[test]
1309    fn image_url_empty_string_id_errors() {
1310        let err = render_one(
1311            r#"{{ rcms_image_url(media_id=v, filter="width-1600") }}"#,
1312            &[("v", tera::Value::String("".to_owned()))],
1313        )
1314        .unwrap_err();
1315        assert!(
1316            format!("{err:?}").contains("media_id"),
1317            "expected media_id error, got `{err:?}`"
1318        );
1319    }
1320
1321    #[test]
1322    fn image_url_missing_filter_errors() {
1323        let err = render_one(r#"{{ rcms_image_url(media_id=42) }}"#, &[]).unwrap_err();
1324        assert!(
1325            format!("{err:?}").contains("filter"),
1326            "expected filter error, got `{err:?}`"
1327        );
1328    }
1329
1330    #[test]
1331    fn image_url_with_content_hash_buster() {
1332        let out = render_one(
1333            r#"{{ rcms_image_url(media_id=42, filter="width-800", v="abc123def456hash") }}"#,
1334            &[],
1335        )
1336        .unwrap();
1337        assert_eq!(crate::rendition::strip_sig(&out), "/__media__/width-800/42?v=abc123def456");
1338    }
1339
1340    // --- #79 — encoding pipeline -------------------------------
1341
1342    #[test]
1343    fn pipeline_parses_bare_resize() {
1344        let p = FilterPipeline::parse("fill-300x200").unwrap();
1345        assert_eq!(p.geometric, FilterOp::Fill { w: 300, h: 200 });
1346        assert_eq!(p.encoding, EncodingOps::default());
1347    }
1348
1349    #[test]
1350    fn pipeline_parses_chained_encoding() {
1351        let p = FilterPipeline::parse("fill-300x200|format-webp|quality-75|bgcolor-fff").unwrap();
1352        assert_eq!(p.geometric, FilterOp::Fill { w: 300, h: 200 });
1353        assert_eq!(p.encoding.format, Some(EncodeFormat::Webp));
1354        assert_eq!(p.encoding.quality, Some(75));
1355        assert_eq!(p.encoding.background, Some((255, 255, 255)));
1356    }
1357
1358    #[test]
1359    fn pipeline_canonical_roundtrips() {
1360        // #398 — AVIF specs now parse (encoding is gated behind the
1361        // `avif` feature, but the URL spec is always recognized).
1362        let raw = "max-1200x900|format-avif|quality-80";
1363        let parsed = FilterPipeline::parse(raw).unwrap();
1364        assert_eq!(parsed.encoding.format, Some(EncodeFormat::Avif));
1365        assert_eq!(parsed.canonical(), raw);
1366        let raw = "fill-300x200|format-webp|quality-75|bgcolor-ffffff";
1367        let parsed = FilterPipeline::parse(raw).unwrap();
1368        assert_eq!(parsed.canonical(), raw);
1369    }
1370
1371    #[test]
1372    #[cfg(not(feature = "avif"))]
1373    fn avif_encode_errors_clearly_without_feature() {
1374        let img = image::DynamicImage::new_rgb8(2, 2);
1375        let ops = EncodingOps {
1376            format: Some(EncodeFormat::Avif),
1377            quality: None,
1378            background: None,
1379        };
1380        let err = encode(&img, &ops, "image/png").unwrap_err();
1381        assert!(err.contains("avif"), "got: {err}");
1382    }
1383
1384    #[test]
1385    #[cfg(feature = "avif")]
1386    fn avif_encode_produces_avif_bytes() {
1387        let img = image::DynamicImage::new_rgb8(8, 8);
1388        let ops = EncodingOps {
1389            format: Some(EncodeFormat::Avif),
1390            quality: Some(50),
1391            background: None,
1392        };
1393        let (bytes, mime, ext) = encode(&img, &ops, "image/png").unwrap();
1394        assert!(!bytes.is_empty());
1395        assert_eq!(mime, "image/avif");
1396        assert_eq!(ext, "avif");
1397    }
1398
1399    #[test]
1400    fn pipeline_rejects_garbage_segments() {
1401        assert!(FilterPipeline::parse("fill-300x200|format-jpegxl").is_err());
1402        assert!(FilterPipeline::parse("fill-300x200|quality-0").is_err());
1403        assert!(FilterPipeline::parse("fill-300x200|quality-101").is_err());
1404        assert!(FilterPipeline::parse("fill-300x200|bgcolor-xxxx").is_err());
1405        assert!(FilterPipeline::parse("fill-300x200|nonsense").is_err());
1406    }
1407
1408    #[test]
1409    fn parse_hex_rgb_three_and_six_digit() {
1410        assert_eq!(super::parse_hex_rgb("fff"), Some((255, 255, 255)));
1411        assert_eq!(super::parse_hex_rgb("ff0000"), Some((255, 0, 0)));
1412        assert_eq!(super::parse_hex_rgb("#abcdef"), Some((171, 205, 239)));
1413        assert_eq!(super::parse_hex_rgb("ff"), None);
1414        assert_eq!(super::parse_hex_rgb("ffffff00"), None); // RGBA not supported
1415    }
1416
1417    /// `rcms_image_url` takes the same pipelines as the srcset and
1418    /// picture helpers; it used to reject anything after a `|`.
1419    #[test]
1420    fn image_url_accepts_a_pipeline() {
1421        let out = render_one(
1422            r#"{{ rcms_image_url(media_id=42, filter="width-800|format-jpeg|quality-80") }}"#,
1423            &[],
1424        )
1425        .unwrap();
1426        assert_eq!(crate::rendition::strip_sig(&out), "/__media__/width-800|format-jpeg|quality-80/42");
1427    }
1428
1429    fn rgba(px: [u8; 4]) -> image::DynamicImage {
1430        image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(4, 4, image::Rgba(px)))
1431    }
1432
1433    #[test]
1434    fn auto_format_picks_jpeg_for_opaque_and_keeps_transparency() {
1435        let opaque_rgb = image::DynamicImage::new_rgb8(4, 4);
1436        assert_eq!(auto_format(&opaque_rgb, "image/png"), EncodeFormat::Jpeg);
1437        // An alpha channel nobody uses is still opaque.
1438        assert_eq!(auto_format(&rgba([9, 9, 9, 255]), "image/png"), EncodeFormat::Jpeg);
1439        let mut one_clear = image::RgbaImage::from_pixel(4, 4, image::Rgba([9, 9, 9, 255]));
1440        one_clear.put_pixel(3, 3, image::Rgba([0, 0, 0, 0]));
1441        let one_clear = image::DynamicImage::ImageRgba8(one_clear);
1442        assert_eq!(auto_format(&one_clear, "image/png"), EncodeFormat::Png);
1443        assert_eq!(auto_format(&one_clear, "image/webp"), EncodeFormat::Webp);
1444        assert_eq!(auto_format(&opaque_rgb, "image/jpeg"), EncodeFormat::Jpeg);
1445    }
1446
1447    /// No format given: an opaque PNG photo comes out as a JPEG (the
1448    /// built-in image block's case), a transparent one stays PNG, and
1449    /// an explicit format still wins.
1450    #[test]
1451    fn encode_without_a_format_follows_auto_format() {
1452        let none = EncodingOps { format: None, quality: None, background: None };
1453        let (_, mime, ext) = encode(&rgba([200, 90, 40, 255]), &none, "image/png").unwrap();
1454        assert_eq!((mime.as_str(), ext.as_str()), ("image/jpeg", "jpg"));
1455        let (_, mime, _) = encode(&rgba([200, 90, 40, 0]), &none, "image/png").unwrap();
1456        assert_eq!(mime, "image/png");
1457        let auto = EncodingOps { format: Some(EncodeFormat::Auto), ..none };
1458        let (_, mime, _) = encode(&rgba([200, 90, 40, 255]), &auto, "image/png").unwrap();
1459        assert_eq!(mime, "image/jpeg");
1460        let png = EncodingOps { format: Some(EncodeFormat::Png), ..none };
1461        let (_, mime, _) = encode(&rgba([200, 90, 40, 255]), &png, "image/png").unwrap();
1462        assert_eq!(mime, "image/png");
1463    }
1464}
1465
1466#[cfg(test)]
1467mod responsive_tests {
1468    use super::{build_picture, FilterPipeline};
1469
1470    // URLs carry a process-key signature; these tests compare the rest.
1471    fn build_srcset(id: i64, specs: &[FilterPipeline], v: Option<&str>) -> String {
1472        crate::rendition::strip_sig(&super::build_srcset(id, specs, v))
1473    }
1474    fn build_dpi_srcset(id: i64, base: &FilterPipeline, densities: &[u32], v: Option<&str>) -> String {
1475        crate::rendition::strip_sig(&super::build_dpi_srcset(id, base, densities, v))
1476    }
1477
1478    fn specs(raw: &[&str]) -> Vec<FilterPipeline> {
1479        raw.iter()
1480            .map(|s| FilterPipeline::parse(s).unwrap())
1481            .collect()
1482    }
1483
1484    #[test]
1485    fn srcset_emits_url_and_width_descriptor() {
1486        let out = build_srcset(42, &specs(&["fill-400x300", "fill-800x600"]), None);
1487        assert_eq!(
1488            out,
1489            "/__media__/fill-400x300/42 400w, /__media__/fill-800x600/42 800w"
1490        );
1491    }
1492
1493    #[test]
1494    fn srcset_skips_height_only_specs() {
1495        // `height-200` has no nominal width → dropped; `width-600` stays.
1496        let out = build_srcset(7, &specs(&["height-200", "width-600"]), None);
1497        assert_eq!(out, "/__media__/width-600/7 600w");
1498    }
1499
1500    #[test]
1501    fn srcset_appends_cache_buster_truncated() {
1502        let out = build_srcset(1, &specs(&["width-300"]), Some("0123456789abcdef"));
1503        assert_eq!(out, "/__media__/width-300/1?v=0123456789ab 300w");
1504    }
1505
1506    #[test]
1507    fn dpi_srcset_scales_width_per_density() {
1508        let base = FilterPipeline::parse("width-400").unwrap();
1509        assert_eq!(
1510            build_dpi_srcset(42, &base, &[1, 2], None),
1511            "/__media__/width-400/42 1x, /__media__/width-800/42 2x"
1512        );
1513    }
1514
1515    #[test]
1516    fn dpi_srcset_scales_both_fill_dims_and_dedups_densities() {
1517        let base = FilterPipeline::parse("fill-200x100").unwrap();
1518        // Densities deduped + sorted + 0 dropped.
1519        let out = build_dpi_srcset(7, &base, &[2, 1, 2, 0], None);
1520        assert_eq!(
1521            out,
1522            "/__media__/fill-200x100/7 1x, /__media__/fill-400x200/7 2x"
1523        );
1524    }
1525
1526    #[test]
1527    fn dpi_srcset_caps_at_8192() {
1528        let base = FilterPipeline::parse("width-5000").unwrap();
1529        // 5000×2 = 10000 → capped to 8192.
1530        assert_eq!(
1531            build_dpi_srcset(1, &base, &[2], None),
1532            "/__media__/width-8192/1 2x"
1533        );
1534    }
1535
1536    #[test]
1537    fn rendition_url_for_parses_and_rejects_bad_spec() {
1538        // #431 — the public API builder: canonicalizes (and signs);
1539        // bad spec → None.
1540        assert_eq!(
1541            super::rendition_url_for(42, "width-800", Some("abc123def456ZZ")).map(|u| crate::rendition::strip_sig(&u)),
1542            Some("/__media__/width-800/42?v=abc123def456".to_owned())
1543        );
1544        assert_eq!(super::rendition_url_for(42, "not-a-spec", None), None);
1545    }
1546
1547    #[test]
1548    fn picture_has_source_per_format_and_img_fallback() {
1549        let html = build_picture(
1550            42,
1551            &specs(&["width-400", "width-800"]),
1552            &["avif".to_owned(), "webp".to_owned()],
1553            "A <photo> & more",
1554            Some("100vw"),
1555            None,
1556        );
1557        let html = crate::rendition::strip_sig(&html);
1558        // One <source> per format, with the format folded into the spec.
1559        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}");
1560        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}");
1561        // Fallback <img>: widest as src + base srcset, alt escaped.
1562        assert!(
1563            html.contains(r#"<img src="/__media__/width-800/42""#),
1564            "{html}"
1565        );
1566        assert!(
1567            html.contains(r#"alt="A &lt;photo&gt; &amp; more""#),
1568            "{html}"
1569        );
1570        assert!(
1571            html.starts_with("<picture>") && html.ends_with("</picture>"),
1572            "{html}"
1573        );
1574    }
1575
1576    /// `auto` is decided per image, so it can't be declared as a
1577    /// `<source type>`; the `<img>` fallback covers it.
1578    #[test]
1579    fn picture_does_not_declare_auto_as_a_source_type() {
1580        let html = crate::rendition::strip_sig(&build_picture(5, &specs(&["width-500"]), &["auto".to_owned()], "", None, None));
1581        assert!(!html.contains("<source"), "{html}");
1582        assert!(html.contains(r#"<img src="/__media__/width-500/5""#), "{html}");
1583    }
1584
1585    #[test]
1586    fn picture_skips_unknown_format_token() {
1587        let html = build_picture(
1588            5,
1589            &specs(&["width-500"]),
1590            &["bogus".to_owned(), "webp".to_owned()],
1591            "",
1592            None,
1593            None,
1594        );
1595        assert!(!html.contains("bogus"), "{html}");
1596        assert!(html.contains(r#"type="image/webp""#), "{html}");
1597    }
1598
1599    #[test]
1600    fn tera_functions_render_end_to_end() {
1601        // Exercises the `filters=[…]` array-arg parsing + registration
1602        // + the `is_safe` (no slash-escaping) contract.
1603        let mut tera = tera::Tera::default();
1604        super::register_tera_function(&mut tera);
1605        tera.add_raw_template(
1606            "s.html",
1607            r#"{{ rcms_image_srcset(media_id=42, filters=["width-400", "width-800"]) }}"#,
1608        )
1609        .unwrap();
1610        assert_eq!(
1611            crate::rendition::strip_sig(&tera.render("s.html", &tera::Context::new()).unwrap()),
1612            "/__media__/width-400/42 400w, /__media__/width-800/42 800w"
1613        );
1614        tera.add_raw_template(
1615            "p.html",
1616            r#"{{ rcms_picture(media_id=7, filters=["width-600"], formats=["webp"], alt="hi") }}"#,
1617        )
1618        .unwrap();
1619        let p = tera.render("p.html", &tera::Context::new()).unwrap();
1620        assert!(p.contains(r#"type="image/webp""#), "{p}");
1621        assert!(p.contains(r#"alt="hi""#), "{p}");
1622        assert!(p.starts_with("<picture>"), "{p}");
1623    }
1624}
1625
1626/// A rendition URL with its `s=` signature removed, for tests that
1627/// compare whole URLs (the signature depends on the process key).
1628#[cfg(test)]
1629pub(crate) fn strip_sig(url: &str) -> String {
1630    let re = regex::Regex::new(r"[?&]s=[0-9a-f]{16}").expect("regex");
1631    re.replace_all(url, "").into_owned()
1632}
1633
1634#[cfg(test)]
1635mod sign_tests {
1636    use super::{classify_sig, parse_max_unsigned, rendition_sig, sig_ok, sign_with, RenditionSig, DEFAULT_MAX_UNSIGNED_VARIANTS};
1637
1638    #[test]
1639    fn sig_is_deterministic_16_hex_and_input_sensitive() {
1640        let k = b"secret";
1641        let a = rendition_sig(k, "fill-400x300", 42);
1642        assert_eq!(a.len(), 16);
1643        assert!(a.chars().all(|c| c.is_ascii_hexdigit()), "{a}");
1644        assert_eq!(a, rendition_sig(k, "fill-400x300", 42)); // stable
1645        assert_ne!(a, rendition_sig(k, "fill-400x300", 43)); // media id
1646        assert_ne!(a, rendition_sig(k, "fill-401x300", 42)); // spec
1647        assert_ne!(a, rendition_sig(b"other-key", "fill-400x300", 42)); // key
1648    }
1649
1650    #[test]
1651    fn sig_ok_accepts_correct_rejects_forged_or_missing() {
1652        let k = b"secret";
1653        let good = rendition_sig(k, "width-800", 7);
1654        assert!(sig_ok(k, "width-800", 7, Some(&good)));
1655        assert!(!sig_ok(k, "width-800", 7, Some("deadbeefdeadbeef"))); // forged
1656        assert!(!sig_ok(k, "width-800", 7, None)); // missing
1657        assert!(!sig_ok(k, "width-800", 8, Some(&good))); // right sig, wrong id
1658    }
1659
1660    #[test]
1661    fn the_unsigned_variant_cap_reads_a_positive_number() {
1662        assert_eq!(parse_max_unsigned(None), DEFAULT_MAX_UNSIGNED_VARIANTS);
1663        assert_eq!(parse_max_unsigned(Some(" 64 ")), 64);
1664        assert_eq!(parse_max_unsigned(Some("0")), DEFAULT_MAX_UNSIGNED_VARIANTS);
1665        assert_eq!(parse_max_unsigned(Some("lots")), DEFAULT_MAX_UNSIGNED_VARIANTS);
1666    }
1667
1668    #[test]
1669    fn a_lenient_key_serves_signed_free_and_unsigned_capped() {
1670        let k = b"derived";
1671        let good = rendition_sig(k, "width-800", 7);
1672        assert_eq!(classify_sig(k, false, "width-800", 7, Some(&good)), RenditionSig::Valid);
1673        // An API client's unsigned URL is served (capped by the route).
1674        assert_eq!(classify_sig(k, false, "width-800", 7, None), RenditionSig::Unsigned);
1675        // A signature from another key (a replica, a restart) or a forged
1676        // or empty one is served like no signature: capped, not broken.
1677        assert_eq!(classify_sig(k, false, "width-800", 7, Some("deadbeefdeadbeef")), RenditionSig::Unsigned);
1678        assert_eq!(classify_sig(k, false, "width-800", 7, Some("")), RenditionSig::Unsigned);
1679    }
1680
1681    #[test]
1682    fn a_strict_key_requires_a_signature() {
1683        let k = b"explicit";
1684        let good = rendition_sig(k, "width-800", 7);
1685        assert_eq!(classify_sig(k, true, "width-800", 7, Some(&good)), RenditionSig::Valid);
1686        assert_eq!(classify_sig(k, true, "width-800", 7, None), RenditionSig::Rejected);
1687        assert_eq!(classify_sig(k, true, "width-800", 7, Some("deadbeefdeadbeef")), RenditionSig::Rejected);
1688    }
1689
1690    #[test]
1691    fn signing_appends_s_after_any_query() {
1692        let k = b"k";
1693        let sig = rendition_sig(k, "width-800", 7);
1694        assert_eq!(sign_with(k, "/__media__/width-800/7".into(), "width-800", 7), format!("/__media__/width-800/7?s={sig}"));
1695        assert_eq!(sign_with(k, "/__media__/width-800/7?v=ab".into(), "width-800", 7), format!("/__media__/width-800/7?v=ab&s={sig}"));
1696    }
1697}