mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-01 18:35:04 -06:00
security: bound token expansion, sanitize the name fallback, regular-file sidecar reads, recased sidecar guard
* engine: cap token expansion, clean the catalog-name fallback, bound sidecar and raw reads, protect recased sidecars, cap graphic pixels
This commit is contained in:
@@ -600,11 +600,15 @@ impl ExportOptions {
|
||||
let base = if self.naming.trim().is_empty() { "{name}" } else { self.naming.as_str() };
|
||||
let n = seq + self.start_number.max(1) as usize - 1;
|
||||
let name = crate::rename::expand_tokens(base, p, n, 3);
|
||||
let mut name: String = name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '\0') { '_' } else { c }).collect();
|
||||
// the catalog's own file name is cleaned the same way: a name from a supplied catalog may hold separators
|
||||
let clean = |s: &str| -> String { s.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '\0') { '_' } else { c }).collect() };
|
||||
let mut name = clean(&name);
|
||||
let (stem, ext) = p.file_name.rsplit_once('.').unwrap_or((&p.file_name, ""));
|
||||
let ext = clean(ext);
|
||||
let ext = ext.as_str();
|
||||
if name.trim().is_empty() {
|
||||
// every token came out empty (no title, no capture time…): keep the original name
|
||||
name = stem.to_string();
|
||||
name = clean(stem);
|
||||
}
|
||||
if self.format == ExportFormat::Original {
|
||||
let base = name.trim_end_matches('.');
|
||||
|
||||
@@ -1525,3 +1525,50 @@ fn export_weights_follow_the_source_and_output_sizes() {
|
||||
assert_eq!(render_weight(0, 0, SourceLevel::Full, 0), 0);
|
||||
assert!(render_weight(usize::MAX, 1, SourceLevel::Full, usize::MAX) > 0, "no overflow");
|
||||
}
|
||||
|
||||
/// A catalog's file name never adds a folder level through the empty-naming fallback or the original's extension.
|
||||
#[test]
|
||||
fn file_name_fallback_and_extension_are_one_path_component() {
|
||||
let empty = |format| ExportOptions { format, naming: "{title}".into(), ..Default::default() };
|
||||
for name in ["../../x.jpg", "..\\y.jpg", "a/b/c.jpg"] {
|
||||
let f = empty(ExportFormat::Jpeg).file_name_for(&named(name), 1);
|
||||
assert!(!f.contains(['/', '\\']), "{f}");
|
||||
}
|
||||
let f = empty(ExportFormat::Original).file_name_for(&named("x.a/../b"), 1);
|
||||
assert!(!f.contains(['/', '\\']), "{f}");
|
||||
assert_eq!(empty(ExportFormat::Jpeg).file_name_for(&named("IMG_1.jpg"), 1), "IMG_1.jpg");
|
||||
}
|
||||
|
||||
/// A graphic is read within 8192 x 8192 pixels: a PNG header declaring more is refused before any pixel is allocated.
|
||||
#[test]
|
||||
fn a_graphic_past_the_pixel_cap_is_refused_before_it_is_decoded() {
|
||||
fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in data {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
let mut ihdr = b"IHDR".to_vec();
|
||||
ihdr.extend(10_000u32.to_be_bytes());
|
||||
ihdr.extend(10_000u32.to_be_bytes());
|
||||
ihdr.extend([8, 0, 0, 0, 0]);
|
||||
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
png.extend(13u32.to_be_bytes());
|
||||
png.extend(&ihdr);
|
||||
png.extend(crc32(&ihdr).to_be_bytes());
|
||||
// the start of the image data, so the header is read to its end (no pixels follow)
|
||||
png.extend(0u32.to_be_bytes());
|
||||
png.extend(b"IDAT");
|
||||
png.extend(crc32(b"IDAT").to_be_bytes());
|
||||
let dir = std::env::temp_dir().join(format!("lc-graphic-cap-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("huge.png");
|
||||
std::fs::write(&path, &png).unwrap();
|
||||
let e = read_graphic(&path.to_string_lossy()).unwrap_err();
|
||||
assert!(e.contains("too large") || e.contains("10000"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -236,6 +236,9 @@ pub(crate) fn watermark_logo(path: &str) -> Option<std::sync::Arc<Rgba8>> {
|
||||
Some(img)
|
||||
}
|
||||
|
||||
/// Most pixels of a watermark or layout graphic (8192 x 8192).
|
||||
const MAX_GRAPHIC_PIXELS: u64 = 1 << 26;
|
||||
|
||||
/// Most bytes of a watermark or layout graphic file.
|
||||
const MAX_GRAPHIC_BYTES: u64 = 256 << 20;
|
||||
|
||||
@@ -244,7 +247,9 @@ const MAX_GRAPHIC_BYTES: u64 = 256 << 20;
|
||||
/// The error says why it couldn't be read or decoded.
|
||||
pub fn read_graphic(path: &str) -> Result<Rgba8, String> {
|
||||
let bytes = crate::read_file::read_regular(path, MAX_GRAPHIC_BYTES).map_err(|e| format!("can't read {path}: {e}"))?;
|
||||
let decoded = lightcraft_codecs::decode(&bytes, Default::default()).map_err(|e| format!("can't decode {path}: {e}"))?;
|
||||
// a graphic is a logo or a layout image, not a photo: its decode is held to 8192 x 8192 pixels, not the general gigapixel
|
||||
let opts = lightcraft_codecs::DecodeOptions { max_pixels: MAX_GRAPHIC_PIXELS, ..Default::default() };
|
||||
let decoded = lightcraft_codecs::decode(&bytes, opts).map_err(|e| format!("can't decode {path}: {e}"))?;
|
||||
Ok(decoded.to_srgb8().into_oriented(lightcraft_geom::Orientation::from_exif(decoded.orientation)))
|
||||
}
|
||||
|
||||
|
||||
@@ -122,9 +122,15 @@ impl OriginalGuard {
|
||||
self.others = std::sync::OnceLock::new();
|
||||
let mut put = |file: String, p: PathBuf, what: String| self.by_name.entry(file.to_lowercase()).or_default().push((p, what));
|
||||
put(name.clone(), path.to_path_buf(), format!("the original of {label}"));
|
||||
// every sidecar name the reader accepts (`.xmp`, `.XMP`, `.Xmp`, a recased photo extension), not only lowercase ones
|
||||
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
|
||||
put(format!("{stem}.xmp"), path.with_extension("xmp"), format!("the XMP sidecar of {label}"));
|
||||
put(format!("{name}.xmp"), PathBuf::from(format!("{}.xmp", path.to_string_lossy())), format!("the XMP sidecar of {label}"));
|
||||
for c in crate::sidecar::sidecar_candidates(&path.to_string_lossy(), crate::sidecar::SidecarNaming::Stem) {
|
||||
if let Some(file) = c.file_name().map(|n| n.to_string_lossy().to_string()) {
|
||||
put(file, c, format!("the XMP sidecar of {label}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Err` (a message for the user) when writing `target` would replace a protected file, or
|
||||
@@ -331,6 +337,24 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidecars_the_reader_accepts_in_other_cases_are_protected() {
|
||||
let d = std::env::temp_dir().join(format!("lc-originals-case-sidecar-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let orig = d.join("IMG_1.jpg");
|
||||
std::fs::write(&orig, b"original").unwrap();
|
||||
let mut c = Catalog::default();
|
||||
let p = Photo::new(PhotoId(1), Source::File { path: orig.to_string_lossy().to_string() }, "IMG_1.jpg", "JPEG", 10, 10, "2026-01-01");
|
||||
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
|
||||
let g = OriginalGuard::new(&c);
|
||||
for name in ["IMG_1.XMP", "IMG_1.Xmp", "IMG_1.JPG.xmp", "IMG_1.jpg.XMP"] {
|
||||
std::fs::write(d.join(name), b"<x/>").unwrap();
|
||||
assert!(g.check(&d.join(name)).unwrap_err().contains("sidecar"), "{name}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sidecar_that_isnt_there_yet_is_protected_too() {
|
||||
let d = std::env::temp_dir().join(format!("lc-originals-new-sidecar-{}", std::process::id()));
|
||||
|
||||
@@ -622,3 +622,14 @@ fn photos_sharing_a_target_name_do_not_rescan_the_suffixes_already_claimed() {
|
||||
assert_eq!(names.len(), 300);
|
||||
assert!(checks.get() <= 3 * 300, "{} disk checks", checks.get());
|
||||
}
|
||||
|
||||
/// A token repeated many times with a long value is cut at the expansion cap, not multiplied into gigabytes.
|
||||
#[test]
|
||||
fn token_expansion_stops_at_the_output_cap() {
|
||||
let mut p = sample_photo();
|
||||
p.meta.title = "é".repeat(100_000);
|
||||
let out = expand_tokens(&"{title}".repeat(10_000), &p, 1, 1);
|
||||
assert!(out.len() <= tokens::MAX_EXPANDED_BYTES && out.len() > tokens::MAX_EXPANDED_BYTES - 2, "{}", out.len());
|
||||
p.meta.title = "Harbour".into();
|
||||
assert_eq!(expand_tokens("a-{title}-b", &p, 1, 1), "a-Harbour-b", "ordinary templates are unchanged");
|
||||
}
|
||||
|
||||
@@ -205,6 +205,20 @@ pub fn expand(template: &str, p: &Photo, seq: usize) -> String {
|
||||
if ext.is_empty() { stem_out } else { format!("{stem_out}.{ext}") }
|
||||
}
|
||||
|
||||
/// Most bytes one expansion yields (far above any file name or overlay line). A token repeated many times
|
||||
/// with a long metadata value would otherwise multiply into gigabytes; the result is cut at this size.
|
||||
pub const MAX_EXPANDED_BYTES: usize = 1 << 20;
|
||||
|
||||
/// `s` appended to `out`, cut at a character boundary where `out` would pass [`MAX_EXPANDED_BYTES`].
|
||||
fn push_capped(out: &mut String, s: &str) {
|
||||
let room = MAX_EXPANDED_BYTES.saturating_sub(out.len());
|
||||
let mut n = s.len().min(room);
|
||||
while !s.is_char_boundary(n) {
|
||||
n -= 1;
|
||||
}
|
||||
out.push_str(&s[..n]);
|
||||
}
|
||||
|
||||
/// The template's tokens replaced for `p` (no extension added, nothing sanitized). A bare `{seq}`
|
||||
/// is zero-padded to `seq_width` digits.
|
||||
pub fn expand_tokens(template: &str, p: &Photo, seq: usize, seq_width: usize) -> String {
|
||||
@@ -225,9 +239,12 @@ pub fn expand_tokens_with(
|
||||
let mut out = String::new();
|
||||
let mut rest = template;
|
||||
while let Some(i) = rest.find('{') {
|
||||
out.push_str(&rest[..i]);
|
||||
if out.len() >= MAX_EXPANDED_BYTES {
|
||||
return out;
|
||||
}
|
||||
push_capped(&mut out, &rest[..i]);
|
||||
let Some(j) = rest[i..].find('}') else {
|
||||
out.push_str(&rest[i..]);
|
||||
push_capped(&mut out, &rest[i..]);
|
||||
rest = "";
|
||||
break;
|
||||
};
|
||||
@@ -263,9 +280,9 @@ pub fn expand_tokens_with(
|
||||
_ => format!("{{{tok}}}"),
|
||||
},
|
||||
};
|
||||
out.push_str(&v);
|
||||
push_capped(&mut out, &v);
|
||||
rest = &rest[i + j + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
push_capped(&mut out, rest);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -743,7 +743,7 @@ fn backup(path: &Path, stamp: &str) -> std::io::Result<PathBuf> {
|
||||
if !std::fs::symlink_metadata(path)?.is_file() {
|
||||
return Err(std::io::Error::other(format!("{} is not a regular file", path.display())));
|
||||
}
|
||||
let bytes = std::fs::read(path)?;
|
||||
let bytes = crate::read_file::read_regular(path, SIDECAR_READ_MAX)?;
|
||||
let stamp: String = stamp.chars().filter(char::is_ascii_alphanumeric).collect();
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
for k in 0..1000 {
|
||||
@@ -774,7 +774,7 @@ pub struct SidecarSaved {
|
||||
/// The new contents for the sidecar at `path`: `fresh` merged into the existing file, if any.
|
||||
/// Returns (contents, merged, backup).
|
||||
fn sidecar_contents(path: &Path, fresh: String, stamp: &str) -> std::io::Result<(String, bool, Option<PathBuf>)> {
|
||||
let bytes = match std::fs::read(path) {
|
||||
let bytes = match crate::read_file::read_regular(path, SIDECAR_READ_MAX) {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((fresh, false, None)),
|
||||
// can't see what is there: never overwrite it blindly
|
||||
@@ -840,10 +840,10 @@ fn file_path(p: &Photo) -> Option<&str> {
|
||||
pub fn read_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Option<(String, PathBuf)> {
|
||||
if let Some(sc) = lookup.find(original) {
|
||||
// A discovered sidecar keeps precedence even when reading it fails.
|
||||
return std::fs::read_to_string(&sc).ok().map(|s| (s, sc));
|
||||
return crate::read_file::read_regular(&sc, SIDECAR_READ_MAX).ok().and_then(|b| String::from_utf8(b).ok()).map(|s| (s, sc));
|
||||
}
|
||||
if kind == MediaKind::Raw {
|
||||
let bytes = std::fs::read(original).ok()?;
|
||||
let bytes = crate::read_file::read_regular(original, crate::read_file::MAX_MEDIA_BYTES).ok()?;
|
||||
let x = lightcraft_meta::embedded(&bytes).xmp?;
|
||||
return Some((x, PathBuf::from(original)));
|
||||
}
|
||||
@@ -855,6 +855,9 @@ pub fn read_packet(original: &str, kind: MediaKind, lookup: SidecarLookup) -> Op
|
||||
None
|
||||
}
|
||||
|
||||
/// Most bytes of a sidecar read whole (the opened file must be a regular file).
|
||||
const SIDECAR_READ_MAX: u64 = 256 << 20;
|
||||
|
||||
const JPEG_XMP_HEADER_SPAN: u64 = 16 * 1024 * 1024;
|
||||
const JPEG_XMP_HEADER_STEPS: usize = 4096;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user