diff --git a/Cargo.lock b/Cargo.lock index c5a8071e..fe3b8128 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -698,6 +698,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.10.0" @@ -848,6 +854,15 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie" version = "0.18.1" @@ -1581,11 +1596,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", "wasip2", "wasip3", + "wasm-bindgen", ] [[package]] @@ -2406,6 +2423,18 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "no_std_io2" version = "0.9.4" @@ -3087,6 +3116,7 @@ dependencies = [ "urlencoding", "uuid", "zeroize", + "zip", ] [[package]] @@ -4015,7 +4045,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50e69a15e21b2ff22c415446983978bded3244195f17d59cb113551c1e806f91" dependencies = [ "base32", - "constant_time_eq", + "constant_time_eq 0.3.1", "hmac 0.12.1", "rand 0.9.4", "sha1 0.10.6", @@ -4201,6 +4231,12 @@ dependencies = [ "rustc-hash", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.0" @@ -4869,9 +4905,23 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "zerotrie" @@ -4907,6 +4957,25 @@ dependencies = [ "syn", ] +[[package]] +name = "zip" +version = "9.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0" +dependencies = [ + "constant_time_eq 0.6.1", + "crc32fast", + "flate2", + "getrandom 0.4.2", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "zmij" version = "1.0.21" diff --git a/book/src/admin.md b/book/src/admin.md index 04ccf144..f0d99242 100644 --- a/book/src/admin.md +++ b/book/src/admin.md @@ -397,6 +397,17 @@ the flash tells you the stored name — nothing that references the original changes. The gallery sorts newest-first, so the renamed upload is the first tile. +**Import ZIP** brings in many images at once: send one `.zip` (up to +64 MB, 2000 files, 128 MB of images once unpacked) and every SVG, PNG, +JPEG or WebP in it goes through the same treatment as a single upload. +Folders are ignored — the library is flat, so `logos/sepe.svg` is stored +as `sepe.svg` — and so is anything that is not an image. Sending the +same archive again adds nothing: a file whose name and content are +already in the library is counted as already there. A file with a name +that exists but different content keeps both, as above. The page then +says how many were imported, how many were already there, and names the +ones that could not be imported, with the reason. + When editing a spec you can open a **modal picker** (search, browse, drag and drop, or upload inline without leaving the form) to select a logo or cover. A "Choose image" button auto-uploads on file select for a one-click diff --git a/crates/ruscker-admin/Cargo.toml b/crates/ruscker-admin/Cargo.toml index ab4da700..95d283a1 100644 --- a/crates/ruscker-admin/Cargo.toml +++ b/crates/ruscker-admin/Cargo.toml @@ -73,6 +73,9 @@ libc = "0.2" # Both already compile transitively (tower-http → async-compression). flate2 = "1.1" brotli = "8.0" +# Reading a .zip of images in the media library (batch import). Deflate +# only, through the flate2 already in the tree: no extra codecs. +zip = { version = "9.8", default-features = false, features = ["deflate-flate2"] } # Errors / logging anyhow = { workspace = true } diff --git a/crates/ruscker-admin/assets/i18n/en/landing.ftl b/crates/ruscker-admin/assets/i18n/en/landing.ftl index f2ec39e6..50956a2a 100644 --- a/crates/ruscker-admin/assets/i18n/en/landing.ftl +++ b/crates/ruscker-admin/assets/i18n/en/landing.ftl @@ -405,6 +405,17 @@ admin-images-delete-confirm-inuse = This image is IN USE. Deleting it resets the admin-images-search = Search images… admin-images-type-all = All types admin-images-no-match = No images match your search. +admin-images-import-zip = Import ZIP +admin-images-import-busy = Importing… +admin-images-import-hint = One .zip with many images (up to 64 MB). Folders are ignored; what is already in the library is not duplicated. +admin-images-import-summary = Import finished: { $imported } imported · { $already } already in the library · { $failed } not imported +admin-images-import-not-zip = The file sent is not a valid .zip. +admin-images-import-empty = The .zip has no images in it (SVG, PNG, JPEG or WebP). +admin-images-import-too-many = The .zip has too many files (2000 at most). Split it. +admin-images-import-too-large = The .zip is too large (up to 64 MB sent and 128 MB of unpacked images). Split it. +admin-images-import-skip-large = larger than 10 MB +admin-images-import-skip-unreadable = could not be read (damaged or password-protected) +admin-images-import-skip-save = could not be saved # Admin credentials admin-creds-title = Credential Management diff --git a/crates/ruscker-admin/assets/i18n/es/landing.ftl b/crates/ruscker-admin/assets/i18n/es/landing.ftl index c6a9ff5d..0c47dd64 100644 --- a/crates/ruscker-admin/assets/i18n/es/landing.ftl +++ b/crates/ruscker-admin/assets/i18n/es/landing.ftl @@ -405,6 +405,17 @@ admin-images-delete-confirm-inuse = Esta imagen está EN USO. Al eliminarla, los admin-images-search = Buscar imágenes… admin-images-type-all = Todos los tipos admin-images-no-match = Ninguna imagen coincide con la búsqueda. +admin-images-import-zip = Importar ZIP +admin-images-import-busy = Importando… +admin-images-import-hint = Un .zip con varias imágenes (hasta 64 MB). Las carpetas se ignoran; lo que ya está en la biblioteca no se duplica. +admin-images-import-summary = Importación terminada: { $imported } importadas · { $already } ya estaban en la biblioteca · { $failed } no importadas +admin-images-import-not-zip = El archivo enviado no es un .zip válido. +admin-images-import-empty = El .zip no contiene imágenes (SVG, PNG, JPEG o WebP). +admin-images-import-too-many = El .zip tiene demasiados archivos (máximo 2000). Divídalo. +admin-images-import-too-large = El .zip es demasiado grande (hasta 64 MB enviados y 128 MB de imágenes descomprimidas). Divídalo. +admin-images-import-skip-large = mayor que 10 MB +admin-images-import-skip-unreadable = no se pudo leer (dañado o con contraseña) +admin-images-import-skip-save = error al guardar # Admin credentials admin-creds-title = Gestión de Credenciales diff --git a/crates/ruscker-admin/assets/i18n/fr/landing.ftl b/crates/ruscker-admin/assets/i18n/fr/landing.ftl index fefb617b..ffc6a96b 100644 --- a/crates/ruscker-admin/assets/i18n/fr/landing.ftl +++ b/crates/ruscker-admin/assets/i18n/fr/landing.ftl @@ -405,6 +405,17 @@ admin-images-delete-confirm-inuse = Cette image est UTILISÉE. La supprimer rét admin-images-search = Rechercher des images… admin-images-type-all = Tous les types admin-images-no-match = Aucune image ne correspond à la recherche. +admin-images-import-zip = Importer un ZIP +admin-images-import-busy = Importation… +admin-images-import-hint = Un .zip contenant plusieurs images (64 Mo au plus). Les dossiers sont ignorés ; ce qui est déjà dans la bibliothèque n’est pas dupliqué. +admin-images-import-summary = Importation terminée : { $imported } importées · { $already } déjà dans la bibliothèque · { $failed } non importées +admin-images-import-not-zip = Le fichier envoyé n’est pas un .zip valide. +admin-images-import-empty = Le .zip ne contient aucune image (SVG, PNG, JPEG ou WebP). +admin-images-import-too-many = Le .zip contient trop de fichiers (2000 au plus). Divisez-le. +admin-images-import-too-large = Le .zip est trop volumineux (64 Mo envoyés et 128 Mo d’images décompressées au plus). Divisez-le. +admin-images-import-skip-large = plus de 10 Mo +admin-images-import-skip-unreadable = illisible (endommagé ou protégé par mot de passe) +admin-images-import-skip-save = erreur d’enregistrement # Admin credentials admin-creds-title = Gestion des Identifiants diff --git a/crates/ruscker-admin/assets/i18n/pt/landing.ftl b/crates/ruscker-admin/assets/i18n/pt/landing.ftl index 14343978..9e536214 100644 --- a/crates/ruscker-admin/assets/i18n/pt/landing.ftl +++ b/crates/ruscker-admin/assets/i18n/pt/landing.ftl @@ -409,6 +409,17 @@ admin-images-delete-confirm-inuse = Esta imagem está EM USO. Se deletar, os app admin-images-search = Buscar imagens… admin-images-type-all = Todos os tipos admin-images-no-match = Nenhuma imagem corresponde à busca. +admin-images-import-zip = Importar ZIP +admin-images-import-busy = Importando… +admin-images-import-hint = Um .zip com várias imagens (até 64 MB). As pastas são ignoradas; o que já está na biblioteca não é duplicado. +admin-images-import-summary = Importação concluída: { $imported } importadas · { $already } já estavam na biblioteca · { $failed } não importadas +admin-images-import-not-zip = O arquivo enviado não é um .zip válido. +admin-images-import-empty = O .zip não contém imagens (SVG, PNG, JPEG ou WebP). +admin-images-import-too-many = O .zip tem arquivos demais (máximo de 2000). Divida em partes. +admin-images-import-too-large = O .zip é grande demais (até 64 MB enviados e 128 MB de imagens descompactadas). Divida em partes. +admin-images-import-skip-large = maior que 10 MB +admin-images-import-skip-unreadable = não foi possível ler (arquivo danificado ou com senha) +admin-images-import-skip-save = erro ao salvar # Admin credentials admin-creds-title = Gestão de Credenciais diff --git a/crates/ruscker-admin/src/images.rs b/crates/ruscker-admin/src/images.rs index f6ef2c8a..27998d20 100644 --- a/crates/ruscker-admin/src/images.rs +++ b/crates/ruscker-admin/src/images.rs @@ -89,6 +89,33 @@ pub async fn process_upload_async( .await? } +/// At most one batch import at a time: an archive and everything unpacked +/// from it sit in memory while it is processed (up to +/// `media_zip::MAX_ZIP_BYTES` + `MAX_TOTAL_BYTES`), so two Editors +/// importing together wait in line instead of doubling that. +static ZIP_IMPORT_SLOT: LazyLock> = LazyLock::new(|| Arc::new(Semaphore::new(1))); + +/// Take the batch-import turn. Held by the route for the whole import and +/// released when dropped. +pub async fn zip_import_turn() -> Result { + ZIP_IMPORT_SLOT + .clone() + .acquire_owned() + .await + .map_err(|_| anyhow!("batch import unavailable")) +} + +/// Unpack a `.zip` of images under the same budget of blocking image jobs +/// as uploads and thumbnails: inflating is CPU work like decoding is. +pub async fn extract_zip_async( + zip_bytes: axum::body::Bytes, +) -> Result> { + run_blocking_image_job(IMAGE_JOB_SLOTS.clone(), move || { + crate::media_zip::extract_images(&zip_bytes, MAX_UPLOAD_BYTES) + }) + .await +} + /// Async migration-import entry point using the same resource budget. pub async fn process_for_import_async( raw_filename: String, diff --git a/crates/ruscker-admin/src/lib.rs b/crates/ruscker-admin/src/lib.rs index c5ccc7a1..8efff562 100644 --- a/crates/ruscker-admin/src/lib.rs +++ b/crates/ruscker-admin/src/lib.rs @@ -34,6 +34,7 @@ pub mod jobs; pub mod leader; pub mod logbuf; pub mod markdown; +pub mod media_zip; pub mod metrics_cache; pub mod mfa; pub mod oidc; diff --git a/crates/ruscker-admin/src/media_zip.rs b/crates/ruscker-admin/src/media_zip.rs new file mode 100644 index 00000000..e812e4bb --- /dev/null +++ b/crates/ruscker-admin/src/media_zip.rs @@ -0,0 +1,285 @@ +//! Reading a `.zip` of images for the media library's batch import. +//! +//! Only the *unpacking* lives here, and it is synchronous and pure (bytes +//! in, files out) so it can be tested without a server: the route runs it +//! on a blocking thread and then sends every file through the same +//! pipeline as a single upload (`images::process_upload`), which is where +//! the content is actually validated. +//! +//! A zip is an archive somebody hands us, so nothing in it is trusted: +//! +//! - **Sizes are measured, not read from the header.** An entry's declared +//! size is whatever its author wrote; each entry is read through a cap, +//! and the whole archive through a total budget — the "zip bomb" guard. +//! - **Paths are ignored.** Only an entry's final name is kept (the media +//! library is flat) and nothing is ever written to disk, so a path such +//! as `../../etc/x.svg` has nowhere to climb to; such an entry is +//! dropped anyway, with the hidden folders. +//! - **Only image extensions are unpacked.** Everything else is counted +//! and left alone, without being decompressed. + +use std::io::Read; + +/// Largest `.zip` accepted. The route's body limit sits just above it. +pub const MAX_ZIP_BYTES: usize = 64 * 1024 * 1024; +/// Entries looked at in one archive. Above this the archive is refused +/// whole: silently importing "the first N" would be a surprise. +pub const MAX_ENTRIES: usize = 2000; +/// Budget for everything unpacked from one archive, in bytes. +pub const MAX_TOTAL_BYTES: u64 = 128 * 1024 * 1024; + +/// One image file taken out of the archive. +#[derive(Debug)] +pub struct ZipFile { + /// The entry's final path component (`logos/sepe.svg` → `sepe.svg`). + pub name: String, + pub bytes: Vec, +} + +/// Why an entry that looked like an image was not unpacked. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SkipReason { + /// Larger than a single upload may be. + TooLarge, + /// Could not be read (encrypted, damaged, unsupported compression). + Unreadable, +} + +/// What came out of an archive. +#[derive(Debug, Default)] +pub struct Extracted { + pub files: Vec, + /// Image-looking entries that were not unpacked, with the reason. + pub skipped: Vec<(String, SkipReason)>, + /// Entries that are not images at all (other extensions). Folders and + /// operating-system litter (`__MACOSX/`, dot-files) are not counted. + pub not_images: usize, +} + +/// Why a whole archive was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ZipRefusal { + /// Not a readable zip archive. + NotAZip, + /// More than [`MAX_ENTRIES`] entries. + TooManyEntries, + /// The images in it unpack to more than [`MAX_TOTAL_BYTES`]. + TooLargeUnpacked, +} + +/// The extensions the media library stores (see `images::SourceKind`). +fn is_image_name(name: &str) -> bool { + let Some((_, ext)) = name.rsplit_once('.') else { + return false; + }; + matches!( + ext.to_ascii_lowercase().as_str(), + "svg" | "png" | "jpg" | "jpeg" | "webp" + ) +} + +/// The final component of an entry path, or `None` for what should not be +/// imported: a folder, a dot-file, or anything under a hidden or +/// `__MACOSX` folder (macOS stores a `._name` twin of every file there). +fn import_name(path: &str) -> Option<&str> { + let path = path.trim_end_matches('/'); + let mut parts = path.split(['/', '\\']).filter(|p| !p.is_empty()); + let name = parts.next_back()?; + if name.starts_with('.') { + return None; + } + if parts.any(|dir| dir == "__MACOSX" || dir.starts_with('.')) { + return None; + } + Some(name) +} + +/// Unpack the image files of a zip archive. `per_file_cap` is the largest +/// a single file may be once unpacked (the single-upload limit). +pub fn extract_images(zip_bytes: &[u8], per_file_cap: usize) -> Result { + extract_images_within(zip_bytes, per_file_cap, MAX_TOTAL_BYTES) +} + +/// [`extract_images`] with the total budget as a parameter, so a test can +/// reach it with small files. +fn extract_images_within( + zip_bytes: &[u8], + per_file_cap: usize, + total_cap: u64, +) -> Result { + let mut archive = + zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).map_err(|_| ZipRefusal::NotAZip)?; + if archive.len() > MAX_ENTRIES { + return Err(ZipRefusal::TooManyEntries); + } + let mut out = Extracted::default(); + let mut total: u64 = 0; + for index in 0..archive.len() { + // The name first, from the directory alone — nothing is + // decompressed for an entry that will not be imported. + let (name, is_dir) = match archive.by_index_raw(index) { + Ok(entry) => match entry.name() { + Ok(path) => (import_name(&path).map(str::to_string), entry.is_dir()), + // A name that cannot be decoded: nothing to call the file. + Err(_) => continue, + }, + Err(_) => continue, + }; + let Some(name) = name else { continue }; + if is_dir { + continue; + } + if !is_image_name(&name) { + out.not_images += 1; + continue; + } + let Ok(entry) = archive.by_index(index) else { + out.skipped.push((name, SkipReason::Unreadable)); + continue; + }; + // One byte past the cap tells "exactly at the cap" from "over it", + // whatever size the entry claims to be — and never more than what + // is left of the archive's budget (plus the same one byte). + let left = total_cap.saturating_sub(total); + let limit = (per_file_cap as u64).min(left) + 1; + let mut bytes = Vec::new(); + let read = entry.take(limit).read_to_end(&mut bytes); + // EVERY byte inflated counts, also for an entry that is then + // skipped: otherwise an archive of many oversized entries would + // make the server inflate far more than the budget, one skipped + // entry at a time (security review of this change). + total += bytes.len() as u64; + if total > total_cap { + return Err(ZipRefusal::TooLargeUnpacked); + } + match read { + Err(_) => out.skipped.push((name, SkipReason::Unreadable)), + Ok(_) if bytes.len() > per_file_cap => out.skipped.push((name, SkipReason::TooLarge)), + Ok(_) => out.files.push(ZipFile { name, bytes }), + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + /// Build a zip in memory from `(path, content)` pairs. + fn zip_of(entries: &[(&str, &[u8])]) -> Vec { + let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated); + for (path, content) in entries { + if path.ends_with('/') { + w.add_directory(*path, opts).unwrap(); + } else { + w.start_file(*path, opts).unwrap(); + w.write_all(content).unwrap(); + } + } + w.finish().unwrap().into_inner() + } + + const SVG: &[u8] = b""; + + #[test] + fn images_come_out_flat_and_the_rest_is_left_alone() { + let zip = zip_of(&[ + ("logos/", b""), + ("logos/sepe.svg", SVG), + ("logos/sub/Brasao.SVG", SVG), + ("capa.png", b"not really a png"), + ("README.md", b"# hi"), + ("__MACOSX/logos/._sepe.svg", b"resource fork"), + (".hidden/x.svg", SVG), + ("logos/.DS_Store", b"x"), + ]); + let got = extract_images(&zip, 1024).unwrap(); + let names: Vec<&str> = got.files.iter().map(|f| f.name.as_str()).collect(); + // The png is unpacked too: whether it IS one is the pipeline's call. + assert_eq!(names, ["sepe.svg", "Brasao.SVG", "capa.png"]); + assert_eq!(got.files[0].bytes, SVG); + assert_eq!(got.not_images, 1, "README.md; system litter is not counted"); + assert!(got.skipped.is_empty()); + } + + /// Folders never reach the library: only the final name is kept. And + /// an entry whose path climbs out of the archive (`..`) is dropped + /// altogether — `..` counts as a hidden folder, and no honest archive + /// has one. + #[test] + fn a_path_is_never_more_than_its_last_component() { + let zip = zip_of(&[ + ("../../etc/logo.svg", SVG), + ("a\\b\\win.svg", SVG), + ("deep/er/unix.svg", SVG), + ]); + let got = extract_images(&zip, 1024).unwrap(); + let names: Vec<&str> = got.files.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["win.svg", "unix.svg"]); + } + + /// The cap is applied to what is actually read: a highly compressible + /// entry (a tiny zip of a huge file) is skipped, not unpacked whole. + #[test] + fn an_entry_over_the_cap_is_skipped_and_the_others_still_import() { + let big = vec![b' '; 50_000]; + let zip = zip_of(&[("big.svg", &big), ("ok.svg", SVG)]); + assert!(zip.len() < 2_000, "compresses to almost nothing: {}", zip.len()); + let got = extract_images(&zip, 10_000).unwrap(); + assert_eq!(got.skipped, vec![("big.svg".to_string(), SkipReason::TooLarge)]); + assert_eq!(got.files.len(), 1); + assert_eq!(got.files[0].name, "ok.svg"); + // Exactly at the cap is fine. + let edge = vec![b' '; 10_000]; + let got = extract_images(&zip_of(&[("edge.svg", &edge)]), 10_000).unwrap(); + assert_eq!(got.files.len(), 1); + } + + /// The archive's budget counts what was inflated, not what was kept: + /// entries skipped for being too large still spend it, so many of + /// them refuse the archive instead of being inflated one after another. + #[test] + fn skipped_entries_spend_the_budget_too() { + let big = vec![b' '; 5_000]; + let entries: Vec<(String, &[u8])> = + (0..10).map(|i| (format!("big-{i}.svg"), &big[..])).collect(); + let entries: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (n.as_str(), *b)).collect(); + let zip = zip_of(&entries); + // Per-file cap 1 000: each entry is read up to 1 001 bytes and + // skipped. A budget of 4 000 is spent by the fourth one. + assert_eq!( + extract_images_within(&zip, 1_000, 4_000).unwrap_err(), + ZipRefusal::TooLargeUnpacked + ); + // With room for all ten reads, they are all just skipped. + let got = extract_images_within(&zip, 1_000, 20_000).unwrap(); + assert_eq!(got.skipped.len(), 10); + assert!(got.files.is_empty()); + // And kept files are bounded by the same budget. + let small = vec![b' '; 900]; + let zip = zip_of(&[("a.svg", &small), ("b.svg", &small), ("c.svg", &small)]); + assert_eq!( + extract_images_within(&zip, 1_000, 2_000).unwrap_err(), + ZipRefusal::TooLargeUnpacked + ); + } + + #[test] + fn what_is_not_a_zip_is_refused() { + assert_eq!(extract_images(SVG, 1024).unwrap_err(), ZipRefusal::NotAZip); + assert_eq!(extract_images(b"", 1024).unwrap_err(), ZipRefusal::NotAZip); + } + + #[test] + fn too_many_entries_refuse_the_whole_archive() { + let names: Vec = (0..=MAX_ENTRIES).map(|i| format!("{i}.txt")).collect(); + let entries: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), &b""[..])).collect(); + assert_eq!( + extract_images(&zip_of(&entries), 1024).unwrap_err(), + ZipRefusal::TooManyEntries + ); + } +} diff --git a/crates/ruscker-admin/src/routes/admin/images.rs b/crates/ruscker-admin/src/routes/admin/images.rs index f7af5d61..8f4f911b 100644 --- a/crates/ruscker-admin/src/routes/admin/images.rs +++ b/crates/ruscker-admin/src/routes/admin/images.rs @@ -7,6 +7,10 @@ //! 3. `db::images::insert` writes the BLOB + audit row //! 4. Redirect back to /admin/images //! +//! Batch import (`/admin/media/import-zip`): a `.zip` is unpacked by +//! `media_zip::extract_images` and every image in it goes through steps +//! 2–3 exactly like a single upload. +//! //! Body cap of 12 MB applied per route — slightly above the //! 10 MB cap inside `process_upload` to account for multipart //! framing overhead. @@ -53,6 +57,40 @@ pub fn routes() -> Router { get(|| async { Redirect::permanent("/admin/media") }), ) .layer(DefaultBodyLimit::max(UPLOAD_BODY_LIMIT)) + // The batch import has its own, larger body limit: one archive + // carries many images. Merged after the layer above so that limit + // does not apply to it. + .merge( + Router::new() + .route("/admin/media/import-zip", post(import_zip)) + .layer(DefaultBodyLimit::max(ZIP_BODY_LIMIT)), + ) +} + +/// The archive itself plus multipart framing. +const ZIP_BODY_LIMIT: usize = crate::media_zip::MAX_ZIP_BYTES + 1024 * 1024; + +/// What the page says once, after a form post. +#[derive(Default)] +struct Flash { + /// Set on successful upload — drives a one-shot toast. + uploaded: Option, + /// The originally-requested name when the upload was auto-renamed to + /// avoid overwriting an existing image — drives the "renamed" note. + renamed: Option, + error: Option, + /// The outcome of a batch import. + import: Option, +} + +/// The outcome of a `.zip` import, already in the viewer's language. +struct ImportFlash { + /// "12 imported · 3 already in the library · 1 not imported". + summary: String, + /// The first few files that were not imported, as `name — reason`. + problems: Vec, + /// How many more problems there were than `problems` shows. + more: usize, } #[derive(Template)] @@ -76,12 +114,10 @@ struct ImagesPage<'a> { /// `/assets/img/` appears here — drives the delete warning /// (#433). refs: String, - /// Set on successful upload — drives a one-shot toast. flash_uploaded: Option, - /// The originally-requested name when the upload was auto-renamed to - /// avoid overwriting an existing image — drives the "renamed" note. flash_renamed: Option, flash_error: Option, + flash_import: Option, } impl<'a> ImagesPage<'a> { @@ -172,7 +208,8 @@ async fn index( }; state.locales.t(loc, key, None) }); - render_index(&state, loc, theme, editor.role, None, None, flash_error).await + let flash = Flash { error: flash_error, ..Flash::default() }; + render_index(&state, loc, theme, editor.role, flash).await } async fn render_index( @@ -180,9 +217,7 @@ async fn render_index( loc: Locale, theme: Theme, role: Role, - flash_uploaded: Option, - flash_renamed: Option, - flash_error: Option, + flash: Flash, ) -> Response { let Some(pool) = state.db.as_ref() else { return ( @@ -254,9 +289,10 @@ async fn render_index( kpi_in_use, kpi_total_bytes, refs, - flash_uploaded, - flash_renamed, - flash_error, + flash_uploaded: flash.uploaded, + flash_renamed: flash.renamed, + flash_error: flash.error, + flash_import: flash.import, }; super::render(&page) } @@ -343,16 +379,183 @@ async fn upload( } } - render_index( - &state, - loc, - theme, - editor.role, - last_uploaded_name, - last_renamed_from, - last_error, - ) - .await + let flash = Flash { + uploaded: last_uploaded_name, + renamed: last_renamed_from, + error: last_error, + import: None, + }; + render_index(&state, loc, theme, editor.role, flash).await +} + +/// How many "not imported" files the page lists by name; the rest is a +/// count. +const IMPORT_PROBLEMS_SHOWN: usize = 8; + +/// Batch import: one `.zip` (form field `zip`) whose images each go +/// through the single-upload pipeline. Three rules worth knowing: +/// +/// - **Re-importing the same archive adds nothing.** A file whose name and +/// stored bytes are already in the library is counted as "already +/// there", so an archive can be sent again after adding logos to it. +/// - **A same-named file with DIFFERENT content keeps both** (`logo.svg` → +/// `logo-2.svg`), the same rule as a single upload: an image in use is +/// never replaced behind the cards that show it. +/// - **One bad file does not stop the rest.** It is reported by name. +async fn import_zip( + editor: RequireEditor, + State(state): State, + loc: Locale, + theme: Theme, + mut multipart: Multipart, +) -> Response { + let Some(pool) = state.db.as_ref() else { + return (StatusCode::SERVICE_UNAVAILABLE, "no db").into_response(); + }; + let t = |key: &str| state.locales.t(loc, key, None); + let fail = |key: &str| Flash { error: Some(t(key)), ..Flash::default() }; + + // The archive: the first non-empty `zip` field. + let mut zip_bytes: Option = None; + loop { + match multipart.next_field().await { + Ok(Some(field)) if field.name() == Some("zip") => match field.bytes().await { + Ok(b) if !b.is_empty() => { + zip_bytes = Some(b); + break; + } + Ok(_) => {} + // Over the body limit, or the connection dropped. + Err(_) => { + return render_index(&state, loc, theme, editor.role, fail("admin-images-import-too-large")).await; + } + }, + Ok(Some(_)) => {} + Ok(None) => break, + Err(_) => { + return render_index(&state, loc, theme, editor.role, fail("admin-images-import-too-large")).await; + } + } + } + let Some(zip_bytes) = zip_bytes else { + return render_index(&state, loc, theme, editor.role, fail("admin-images-import-not-zip")).await; + }; + + // One import at a time (its files sit in memory until stored), and the + // unpacking itself under the shared budget of blocking image jobs. + let _turn = match images::zip_import_turn().await { + Ok(turn) => turn, + Err(err) => { + tracing::error!(error = ?err, "zip import turn unavailable"); + return (StatusCode::SERVICE_UNAVAILABLE, "import unavailable").into_response(); + } + }; + let extracted = images::extract_zip_async(zip_bytes).await; + let extracted = match extracted { + Ok(Ok(e)) => e, + Ok(Err(refusal)) => { + use crate::media_zip::ZipRefusal; + let key = match refusal { + ZipRefusal::NotAZip => "admin-images-import-not-zip", + ZipRefusal::TooManyEntries => "admin-images-import-too-many", + ZipRefusal::TooLargeUnpacked => "admin-images-import-too-large", + }; + return render_index(&state, loc, theme, editor.role, fail(key)).await; + } + Err(err) => { + tracing::error!(error = ?err, "zip extraction task failed"); + return (StatusCode::INTERNAL_SERVER_ERROR, "import failed").into_response(); + } + }; + + // An archive with no image in it at all: say that, not "0 imported". + if extracted.files.is_empty() && extracted.skipped.is_empty() { + return render_index(&state, loc, theme, editor.role, fail("admin-images-import-empty")).await; + } + + let (mut imported, mut already) = (0usize, 0usize); + // (file name, reason) for everything that looked like an image and + // did not make it in. + let mut problems: Vec<(String, String)> = extracted + .skipped + .into_iter() + .map(|(name, why)| { + let key = match why { + crate::media_zip::SkipReason::TooLarge => "admin-images-import-skip-large", + crate::media_zip::SkipReason::Unreadable => "admin-images-import-skip-unreadable", + }; + (name, t(key)) + }) + .collect(); + for file in extracted.files { + let name = file.name.clone(); + let mut processed = match images::process_upload_async(file.name, None, file.bytes).await { + Ok(p) => p, + Err(err) => { + tracing::warn!(error = ?err, filename = %name, "zip import: file rejected"); + problems.push((name, err.to_string())); + continue; + } + }; + // Same name already in the library: the same bytes mean it is + // already there; different bytes get a free name. + match db::images::fetch_by_filename(pool, &processed.filename).await { + Ok(Some((_, stored))) if stored == processed.bytes => { + already += 1; + continue; + } + Ok(Some(_)) => match db::images::unique_filename(pool, &processed.filename).await { + Ok(unique) => processed.filename = unique, + Err(err) => { + tracing::error!(error = ?err, "unique filename failed"); + problems.push((name, t("admin-images-import-skip-save"))); + continue; + } + }, + Ok(None) => {} + Err(err) => { + tracing::error!(error = ?err, "zip import: lookup failed"); + problems.push((name, t("admin-images-import-skip-save"))); + continue; + } + } + let stored_name = processed.filename.clone(); + match db::images::insert(pool, processed, Some(editor.actor())).await { + Ok(_) => { + crate::routes::assets::invalidate_thumb(&stored_name); + imported += 1; + } + Err(err) => { + tracing::error!(error = ?err, "zip import: insert failed"); + problems.push((name, t("admin-images-import-skip-save"))); + } + } + } + tracing::info!( + actor = editor.actor(), + imported, + already, + not_imported = problems.len(), + other_files = extracted.not_images, + "media zip import" + ); + + let mut args = fluent_bundle::FluentArgs::new(); + args.set("imported", imported as i64); + args.set("already", already as i64); + args.set("failed", problems.len() as i64); + let summary = state.locales.t(loc, "admin-images-import-summary", Some(&args)); + let more = problems.len().saturating_sub(IMPORT_PROBLEMS_SHOWN); + let problems = problems + .into_iter() + .take(IMPORT_PROBLEMS_SHOWN) + .map(|(name, why)| format!("{name} — {why}")) + .collect(); + let flash = Flash { + import: Some(ImportFlash { summary, problems, more }), + ..Flash::default() + }; + render_index(&state, loc, theme, editor.role, flash).await } /// JSON shape returned by [`upload_inline`]. On success `filename` + diff --git a/crates/ruscker-admin/templates/admin/images.html b/crates/ruscker-admin/templates/admin/images.html index b6d70ba1..18728717 100644 --- a/crates/ruscker-admin/templates/admin/images.html +++ b/crates/ruscker-admin/templates/admin/images.html @@ -31,6 +31,23 @@

{{ self.t("admin-images-title") } {% when None %}{% endmatch %} +{% match flash_import %}{% when Some with (report) %} +
+ + {# One block, so the list of problems sits UNDER the summary (the + banner is a flex row). #} +
+ {{ report.summary }} + {% if !report.problems.is_empty() %} +
    + {% for line in report.problems %}
  • {{ line }}
  • {% endfor %} + {% if report.more > 0 %}
  • + {{ report.more }}
  • {% endif %} +
+ {% endif %} +
+
+{% when None %}{% endmatch %} + {# ── Upload form ──────────────────────────────────────────── #}
{{ self.t("admin-images-title") } {{ self.t("admin-images-formats-help") }}
+{# ── Batch import: one .zip with many images ────────────────── + Its own form (forms cannot nest) and its own address: the archive is + unpacked on the server and each image goes through the same pipeline + as a single upload. The button shows a busy state because a large + archive takes a few seconds and the page gives no other sign. #} +
+ + + {{ self.t("admin-images-import-hint") }} +
+ {# ── Gallery grid ─────────────────────────────────────────── #} {% if images.is_empty() %}
diff --git a/crates/ruscker-admin/tests/rbac.rs b/crates/ruscker-admin/tests/rbac.rs index ef874061..d32511a1 100644 --- a/crates/ruscker-admin/tests/rbac.rs +++ b/crates/ruscker-admin/tests/rbac.rs @@ -1874,3 +1874,111 @@ async fn without_a_catalog_only_the_token_session_is_accepted() { let status = send(st, "GET", "/admin/system", Some(&format!("{COOKIE_NAME}={token}"))).await; assert_eq!(status, StatusCode::OK); } + +// ── Media: batch import from a .zip ───────────────────────────────── + +/// A zip in memory from `(path, content)` pairs. +fn zip_of(entries: &[(&str, &[u8])]) -> Vec { + use std::io::Write; + let mut w = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (path, content) in entries { + w.start_file(*path, opts).unwrap(); + w.write_all(content).unwrap(); + } + w.finish().unwrap().into_inner() +} + +/// POST one file as `multipart/form-data` field `zip`. +async fn post_zip(state: &AppState, cookie: &str, bytes: &[u8]) -> Response { + const B: &str = "rusckerzipboundary"; + let mut body = format!( + "--{B}\r\nContent-Disposition: form-data; name=\"zip\"; filename=\"logos.zip\"\r\nContent-Type: application/zip\r\n\r\n" + ) + .into_bytes(); + body.extend_from_slice(bytes); + body.extend_from_slice(format!("\r\n--{B}--\r\n").as_bytes()); + send_request( + state.clone(), + "POST", + "/admin/media/import-zip", + Some(cookie), + Body::from(body), + Some(&format!("multipart/form-data; boundary={B}")), + ) + .await +} + +async fn media_names(state: &AppState) -> Vec { + let mut names: Vec = ruscker_admin::db::images::list_all(state.db.as_ref().unwrap()) + .await + .unwrap() + .into_iter() + .map(|i| i.filename) + // `db::open` seeds the built-in logos; only what the test sent. + .filter(|n| n.starts_with("zipt-")) + .collect(); + names.sort(); + names +} + +/// The whole import: images in folders land flat, what is not an image is +/// left alone, a broken image is reported by name without stopping the +/// rest, a second import of the same archive adds nothing, and a +/// same-named file with other content keeps both. +#[tokio::test] +async fn a_zip_of_images_is_imported_into_the_media_library() { + const A: &[u8] = b"a"; + const B: &[u8] = b"b"; + let st = db_state().await; + let c = cookie_for(&st, Role::Editor).await; + let archive = zip_of(&[ + ("logos/zipt-a.svg", A), + ("logos/outros/zipt-b.svg", B), + ("logos/LEIAME.txt", b"texto"), + ("zipt-quebrada.png", b"isto nao e um png"), + ("__MACOSX/logos/._zipt-a.svg", b"lixo do macOS"), + ]); + + let response = post_zip(&st, &c, &archive).await; + assert_eq!(response.status(), StatusCode::OK); + let page = response_body(response).await; + assert_eq!(media_names(&st).await, ["zipt-a.svg", "zipt-b.svg"]); + assert!(page.contains("zipt-quebrada.png"), "the rejected file is named"); + assert!(!page.contains("LEIAME.txt"), "a non-image is not an error"); + + // The same archive again: nothing new, nothing duplicated. + let response = post_zip(&st, &c, &archive).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(media_names(&st).await, ["zipt-a.svg", "zipt-b.svg"]); + + // Same name, other content: both are kept, as for a single upload. + let changed = zip_of(&[("zipt-a.svg", B)]); + post_zip(&st, &c, &changed).await; + assert_eq!(media_names(&st).await, ["zipt-a-2.svg", "zipt-a.svg", "zipt-b.svg"]); + let db = st.db.as_ref().unwrap(); + let (_, first) = ruscker_admin::db::images::fetch_by_filename(db, "zipt-a.svg").await.unwrap().unwrap(); + assert_eq!(first, A, "the image already there was not replaced"); +} + +#[tokio::test] +async fn a_zip_import_refuses_what_is_not_an_archive_of_images() { + let st = db_state().await; + let c = cookie_for(&st, Role::Editor).await; + // Not a zip at all. + let page = response_body(post_zip(&st, &c, b"").await).await; + assert!(page.contains(r#"role="alert""#), "an error is shown"); + // A zip with no image in it. + let page = response_body(post_zip(&st, &c, &zip_of(&[("zipt-notas.txt", b"x")])).await).await; + assert!(page.contains(r#"role="alert""#), "an error is shown"); + assert!(media_names(&st).await.is_empty()); + + // Same guard as every other write to the library: no Viewer, no + // anonymous request. + let viewer = cookie_for(&st, Role::Viewer).await; + let archive = zip_of(&[("zipt-v.svg", b"")]); + assert_eq!(post_zip(&st, &viewer, &archive).await.status(), StatusCode::FORBIDDEN); + let anonymous = send(st.clone(), "POST", "/admin/media/import-zip", None).await; + assert!(anonymous.is_redirection(), "anonymous ⇒ login, got {anonymous}"); + assert!(media_names(&st).await.is_empty()); +}