Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
f54145c
Upstream #2834: Clamp negative signals to zero in hlg_decode
emmertex Oct 25, 2026
aa58f28
Upstream #2833: Strip trailing NULs from non-UTF-8 IPTC text
emmertex Oct 25, 2026
2003264
Upstream #2776: Reject signed numeric character references in XML ent…
emmertex Oct 25, 2026
624bd7e
Upstream #2750: Never crash: tiles far larger than the image are refu…
emmertex Oct 25, 2026
8ad002b
Upstream #2740: Never crash: ARW and SRW strips shorter than declared…
emmertex Oct 25, 2026
480c741
Upstream #2738: Never crash: Refuse an ORF whose 12-bit strip runs pa…
emmertex Oct 25, 2026
18dc3ad
Upstream #2714: Never crash: History is bounded on load and by every …
emmertex Oct 25, 2026
b91d241
Upstream #2648: Never crash: the work gate's byte count saturates ins…
emmertex Oct 25, 2026
d4c74d2
Upstream #2485: catalog.query / library.filter: an unknown filter key…
emmertex Oct 25, 2026
26020df
Upstream #2634: LR-MASK-EFFECTS: mask.exportEffects refuses originals…
emmertex Oct 25, 2026
017eab4
Upstream #2637: Catalog: library files are never read, cut or appende…
emmertex Oct 25, 2026
000b5ca
Upstream #2627: #1952: the idle-close MCP test reads blocking and wai…
emmertex Oct 25, 2026
6c7b700
Upstream #2631: LR-EDIT-DETAIL-DENOISE: GPU denoise doesn't hang when…
emmertex Oct 25, 2026
2bc3b33
Upstream #2724: fix(codecs): validate JPEG ICC APP2 chunk sequences
emmertex Oct 25, 2026
16e5ddd
Upstream #2844: GPU: black pixels take the colour tools and a light v…
emmertex Oct 25, 2026
db802ae
Upstream #2465: TIFF: Read every plane of a planar TIFF (#2462)
emmertex Oct 25, 2026
3fc441e
Upstream #2605: Write capture time UTC offset and sub-seconds in writ…
emmertex Oct 25, 2026
11cd2cf
Upstream #2771: Read Canon maker-note lens when LensModel is missing
emmertex Oct 25, 2026
bd8787d
Upstream #2753 + #2530: refuse truncated times and impossible calenda…
emmertex Oct 25, 2026
bd2ab9b
Upstream #2717: rational tag lists show 16 values like every other list
emmertex Oct 25, 2026
a799406
Upstream #2712 (part): an i16::MIN UTC offset never panics
emmertex Oct 25, 2026
775a0e2
Upstream #2628: CR3 preview box scan checks 32-bit lengths for overflow
emmertex Oct 25, 2026
89895c6
Upstream #2635 (learned): lossy-JPEG tiles are refused from their JPE…
emmertex Oct 25, 2026
9797aea
Upstream #2540: Reject non-finite values when parsing .cube LUTs
emmertex Oct 25, 2026
6e9efda
Upstream #2770: security: bound heic-rs 0.1.4 work around hostile HEI…
emmertex Oct 25, 2026
f79bcd1
Upstream #2607: LR-IMP-FORMATS: GIF and BMP sizes from the header; a …
emmertex Oct 25, 2026
d27fb41
Upstream #2632: MCP: render and screenshot PNGs go through a private …
emmertex Oct 25, 2026
290daa6
Upstream #2600: LR-EXP-LOCATION: an export subfolder never leaves the…
emmertex Oct 25, 2026
77b6ad5
Upstream ports: brand names out of the ported strings and tests
emmertex Oct 25, 2026
8716be7
Upstream ports: resolve merge leftovers (heif, lut and mcp tests)
emmertex Oct 25, 2026
91eae2e
Upstream #2753: normalize_iso refuses a truncated time; reading for s…
emmertex Oct 25, 2026
57fdc54
Revert upstream #2600: the fork already refuses hostile export subfol…
emmertex Oct 25, 2026
d769466
What's New: hostile-file hardening ported from upstream
emmertex Oct 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion crates/catalog/src/dates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@ pub fn weekday(iso: &str) -> Option<&'static str> {
pub fn shift_iso(iso: &str, secs: i64) -> Option<String> {
let iso = iso.trim();
let tail = iso.get(tail_start(iso)?..)?;
let t = iso_seconds(iso)?.checked_add(secs)?;
let base = iso_seconds(iso)?;
// reject impossible dates that the arithmetic silently rolls over (2026-02-30)
if civil(base).get(..10) != iso.get(..10) {
return None;
}
let t = base.checked_add(secs)?;
let (first, last) = (iso_seconds("0000-01-01T00:00:00")?, iso_seconds("9999-12-31T23:59:59")?);
if !(first..=last).contains(&t) {
return None;
Expand Down Expand Up @@ -103,6 +108,10 @@ fn tail_start(iso: &str) -> Option<usize> {
/// Normalize user input to `YYYY-MM-DDTHH:MM:SS` (accepts a space instead of `T`, missing
/// seconds or time). `None` if it isn't a valid date.
pub fn normalize_iso(s: &str) -> Option<String> {
// longer than the bare date means a full `HH:MM`: a truncated time is not a date (iso_seconds stays lenient)
if (11..16).contains(&s.trim().len()) {
return None;
}
let t = iso_seconds(s)?;
let out = civil(t);
// reject impossible dates that the arithmetic silently rolls over (2026-02-30)
Expand Down Expand Up @@ -354,6 +363,23 @@ mod tests {
assert_eq!(normalize_iso("2026-02-30"), None);
}

#[test]
fn normalize_iso_rejects_a_truncated_time() {
for s in ["2026-04-01 9:30", "2026-04-01T10", "2026-04-01 10:5"] {
assert_eq!(normalize_iso(s), None, "{s}");
}
assert_eq!(normalize_iso("2026-04-01 09:30").as_deref(), Some("2026-04-01T09:30:00"));
assert_eq!(normalize_iso("2026-04-01").as_deref(), Some("2026-04-01T00:00:00"));
}

#[test]
fn shift_refuses_impossible_dates() {
assert_eq!(shift_iso("2026-02-30T10:00:00", 60), None);
assert_eq!(shift_iso("2026-02-29T10:00:00", 0), None);
assert_eq!(shift_iso("2026-04-31T10:00:00", 0), None);
assert_eq!(shift_iso("2024-02-29T10:00:00", 0).as_deref(), Some("2024-02-29T10:00:00"));
}

#[test]
fn shift_keeps_the_zone_of_a_time_without_seconds() {
assert_eq!(shift_iso("2026-01-01T10:00+02:00", 3600).as_deref(), Some("2026-01-01T11:00:00+02:00"));
Expand Down
21 changes: 17 additions & 4 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -877,10 +877,11 @@ impl Catalog {
_ => {}
}
Ok(match op {
Op::AddPhoto { photo } => {
Op::AddPhoto { mut photo } => {
if self.photos.contains_key(&photo.id) {
return Err(CatalogError::Invalid(format!("photo {:?} exists", photo.id)));
}
photo.trim_history();
let id = photo.id;
// the largest id would leave no next one (a damaged log or a hostile op)
let next = id.0.checked_add(1).ok_or_else(|| CatalogError::Invalid(format!("photo id {} is out of range", id.0)))?;
Expand Down Expand Up @@ -938,7 +939,14 @@ impl Catalog {
}
Op::SetHistory { id, history } => {
let p = self.photo_mut(id)?;
Op::SetHistory { id, history: std::mem::replace(&mut p.history, history) }
let old = std::mem::replace(&mut p.history, history);
let old_cursor = p.history_cursor;
p.trim_history();
if p.history_cursor == old_cursor {
Op::SetHistory { id, history: old }
} else {
Op::Batch { ops: vec![Op::SetHistory { id, history: old }, Op::SetHistoryCursor { id, cursor: old_cursor }] }
}
}
Op::PushHistory { id, step } => {
let p = self.photo_mut(id)?;
Expand Down Expand Up @@ -1376,15 +1384,20 @@ impl Catalog {
/// finds in them, and walks folders up to the top): every photo, album and stack carries the
/// id it is filed under; the id counters lie past every id in use; a stack keeps only photos
/// in the catalog, once each, and goes when fewer than two are left; an album whose parent is
/// missing, not a folder or inside itself moves to the top level. Returns what was changed
/// (nothing, for a catalog this build wrote).
/// missing, not a folder or inside itself moves to the top level; a photo keeps its newest
/// [`HISTORY_LIMIT`] History steps. Returns what was changed (nothing, for a catalog this build
/// wrote).
pub fn repair(&mut self) -> Vec<String> {
let mut changed = Vec::new();
for (id, p) in self.photos.iter_mut() {
if p.id != *id {
changed.push(format!("photo {} was filed as {}", p.id.0, id.0));
Arc::make_mut(p).id = *id;
}
if p.history.len() > HISTORY_LIMIT {
let n = Arc::make_mut(p).trim_history();
changed.push(format!("photo {}: {n} History step(s) beyond the newest {HISTORY_LIMIT} dropped", id.0));
}
}
for (id, a) in self.albums.iter_mut() {
if a.id != *id {
Expand Down
7 changes: 5 additions & 2 deletions crates/catalog/src/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
//! - File systems without lock support (some network shares): the library opens unlocked, with a
//! warning — refusing it would lock the user out of their own library. Locks over SMB/NFS are
//! advisory and depend on the server; the owner file is then the only hint.
//! - A `catalog.lock` that is a link, or anything else that isn't a regular file, is never created
//! or locked through (issue #2552): the library opens unlocked, with a warning, as above.
//! - Browser storage (OPFS) has no file locks: see the web host for its own guard.

use std::fs::{File, OpenOptions, TryLockError};
Expand Down Expand Up @@ -104,8 +106,9 @@ impl LibraryLock {
log::warn!("library {}: can't lock {LOCK} ({why}); opening it without protection against a second program", dir.display());
LibraryLock { dir: dir.to_path_buf(), file: None, held: false }
};
let file = match OpenOptions::new().read(true).write(true).create(true).truncate(false).open(dir.join(LOCK)) {
Ok(f) => f,
// never through a link at the name, which would create or lock a file elsewhere (issue #2552)
let file = match crate::safe_file::open_or_create_regular(&dir.join(LOCK), OpenOptions::new().read(true).write(true)) {
Ok((f, _)) => f,
Err(e) => return Ok(unlocked(e)),
};
match file.try_lock() {
Expand Down
11 changes: 11 additions & 0 deletions crates/catalog/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,17 @@ pub fn preview_stamp(preview_only: &Option<String>) -> String {
}

impl Photo {
/// Keep the newest [`HISTORY_LIMIT`](crate::HISTORY_LIMIT) History steps; the cursor moves with
/// its step, or to the oldest step kept when its own is dropped. Returns how many were dropped.
pub fn trim_history(&mut self) -> usize {
let n = self.history.len().saturating_sub(crate::HISTORY_LIMIT);
if n > 0 {
self.history.drain(..n);
self.history_cursor = self.history_cursor.map(|c| c.saturating_sub(n));
}
n
}

/// The History step the settings are at (the cursor, clamped to the list; `None` = no history).
pub fn history_index(&self) -> Option<usize> {
let last = self.history.len().checked_sub(1)?;
Expand Down
2 changes: 1 addition & 1 deletion crates/catalog/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub enum RatingOp {

/// What the grid shows. Empty/None fields don't filter.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
#[serde(default, rename_all = "camelCase", deny_unknown_fields)]
pub struct Filter {
/// Free-text search (plug-in metadata fields too; `key:value` for one): every token must match filename, title, caption, keywords, camera, lens,
/// location or format. Tokens like `rating:3`, `flag:pick`, `iso:>800`, `camera:x2` are fielded.
Expand Down
82 changes: 82 additions & 0 deletions crates/catalog/src/safe_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
//! links, an exclusive create that claims the name, then a rename over that placeholder).
//! - [`same_file`] tells whether two paths name the same file on disk (device + inode on Unix,
//! resolved paths elsewhere), for "is this target an original?" checks.
//! - [`open_regular`] / [`open_or_create_regular`] open a library file in place (to read, append
//! or cut it), never through a link planted at its name, nor a FIFO or a device (issue #2552).
//! The replacing writes above are safe already: a rename replaces a link, it doesn't follow it.

use std::cell::Cell;
use std::fs::{self, File, OpenOptions};
Expand Down Expand Up @@ -321,6 +324,61 @@ pub fn same_file(a: &Path, b: &Path) -> bool {
}
}

/// Open the regular file `path` in place with `opts`, never through a link at that name: a library
/// folder may come from a share, a sync or an archive, and a link planted there would have a write
/// land in, or a read take, a file elsewhere (issue #2552). A link, a FIFO (whose open would block),
/// a device or a folder at the name is refused with a message saying what to do; nothing there is
/// `None`. `opts` must not create or truncate: [`open_or_create_regular`] makes a missing file.
///
/// On Unix the opened file is checked to be the one looked at (same device and inode) before
/// anything is read or written through it, so a link swapped in meanwhile is refused too.
pub fn open_regular(path: &Path, opts: &OpenOptions) -> io::Result<Option<File>> {
let before = match fs::symlink_metadata(path) {
Ok(m) => m,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
if !before.file_type().is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"{} is a link or not a regular file; the app won't read or write a library file through one. Remove it or put the real file there.",
path.display()
),
));
}
let f = match opts.open(path) {
Ok(f) => f,
// removed since it was looked at
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
let after = f.metadata()?;
if (after.dev(), after.ino()) != (before.dev(), before.ino()) {
return Err(io::Error::other(format!("{} changed while it was being opened; try again", path.display())));
}
}
Ok(Some(f))
}

/// [`open_regular`], or, when nothing is at `path`, a new file made exclusively (`create_new`),
/// which neither follows a link planted there meanwhile nor creates its target. `true` when this
/// call made the file.
pub fn open_or_create_regular(path: &Path, opts: &OpenOptions) -> io::Result<(File, bool)> {
if let Some(f) = open_regular(path, opts)? {
return Ok((f, false));
}
match opts.clone().create_new(true).open(path) {
Ok(f) => Ok((f, true)),
// made by another program since: opened by the same rules
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => open_regular(path, opts)?.map(|f| (f, false)).ok_or(e),
Err(e) => Err(e),
}
}

#[cfg(test)]
mod tests {
/// On an SMB share macOS refuses the full flush: sidecars and other durable writes still land.
Expand Down Expand Up @@ -490,4 +548,28 @@ mod tests {
assert!(!same_file(&p, &d.join("missing.jpg")));
let _ = fs::remove_dir_all(&d);
}

/// Issue #2552: only a regular file is opened in place. A link (even to a regular file), a
/// folder, a FIFO or a device at the name is refused without being opened, and a missing file
/// is `None` until `open_or_create_regular` makes it.
#[cfg(unix)]
#[test]
fn only_regular_files_are_opened_in_place() {
let d = temp("regular");
let p = d.join("catalog.log");
assert!(open_regular(&p, OpenOptions::new().read(true)).unwrap().is_none());
assert!(open_or_create_regular(&p, OpenOptions::new().append(true)).unwrap().1, "a missing file is made");
assert!(!open_or_create_regular(&p, OpenOptions::new().append(true)).unwrap().1, "an existing one is opened");
assert!(open_regular(&p, OpenOptions::new().read(true)).unwrap().is_some());
std::os::unix::fs::symlink(&p, d.join("link.log")).unwrap();
fs::create_dir_all(d.join("folder.log")).unwrap();
let fifo = d.join("fifo.log");
assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success());
for refused in [d.join("link.log"), d.join("folder.log"), fifo, PathBuf::from("/dev/null")] {
let e = open_regular(&refused, OpenOptions::new().read(true)).unwrap_err();
assert!(e.to_string().contains("is a link or not a regular file"), "{}: {e}", refused.display());
assert!(open_or_create_regular(&refused, OpenOptions::new().append(true)).is_err(), "{}", refused.display());
}
let _ = fs::remove_dir_all(&d);
}
}
77 changes: 51 additions & 26 deletions crates/catalog/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,6 @@ pub trait Store: Send {
}
}

/// Appends and truncates open the name's own file, so anything else at the name is the library's
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
/// hangs the open. Refused with an error the open can show, before anything is written through.
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(md) if md.is_file() => Ok(()),
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}

/// Files in a directory.
pub struct FsStore {
dir: PathBuf,
Expand Down Expand Up @@ -108,12 +96,14 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result<std::fs::File>
}

impl Store for FsStore {
/// Never through a link at the name, nor from a FIFO or a device (issue #2552): a `prefs.json`
/// linked to a private file would be read as damaged and copied into the library.
fn read(&mut self, name: &str) -> io::Result<Option<Vec<u8>>> {
match std::fs::read(self.path(name)) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
use std::io::Read;
let Some(mut f) = crate::safe_file::open_regular(&self.path(name), std::fs::OpenOptions::new().read(true))? else { return Ok(None) };
let mut b = Vec::new();
f.read_to_end(&mut b)?;
Ok(Some(b))
}

fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
Expand Down Expand Up @@ -167,10 +157,10 @@ impl Store for FsStore {
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
check_regular_directory_entry(&self.path(name))?;
let existed = self.path(name).exists();
let f = std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
if !existed {
// never through a link at the name: the records would land in the file it points to, and
// a dangling link would create that file (issue #2552)
let (f, created) = crate::safe_file::open_or_create_regular(&self.path(name), std::fs::OpenOptions::new().append(true))?;
if created {
self.sync_dir();
}
self.appender = Some((name.to_string(), f));
Expand All @@ -190,12 +180,10 @@ impl Store for FsStore {
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
check_regular_directory_entry(&self.path(name))?;
let f = match std::fs::OpenOptions::new().write(true).open(self.path(name)) {
Ok(f) => f,
// a link at the name is refused, not cut: a log linked elsewhere would empty that file (issue #2552)
let Some(f) = crate::safe_file::open_regular(&self.path(name), std::fs::OpenOptions::new().write(true))? else {
// nothing to cut (an append that failed before creating the file)
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e),
return Ok(());
};
f.set_len(len)?;
sync_file(&f, false)
Expand Down Expand Up @@ -372,6 +360,43 @@ mod tests_staging {
let _ = std::fs::remove_dir_all(&dir);
}

/// A link planted at a catalog name is refused, never read, cut back or appended through: the file it points to
/// keeps its bytes, a dangling link makes nothing at its target, and the library is refused with a message
/// instead of having its log's target emptied (issue #2552).
#[cfg(unix)]
#[test]
fn links_at_catalog_names_are_never_read_cut_or_appended_through() {
use crate::journal::{Journal, LOG};
use std::os::unix::fs::symlink;
let dir = std::env::temp_dir().join(format!("lc-store-links-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut store = FsStore::open(&dir).unwrap();
let victim = dir.join("victim.txt");
std::fs::write(&victim, b"keep").unwrap();
// not a record: the journal would cut the log back to its last good record, here 0 bytes
symlink(&victim, dir.join(LOG)).unwrap();
let opened = Journal::open(Box::new(FsStore::open(&dir).unwrap()));
assert_eq!(std::fs::read(&victim).unwrap(), b"keep", "the log's target was cut back");
let Err(e) = opened else { panic!("a library with a linked {LOG} was opened") };
assert!(e.to_string().contains("is a link or not a regular file"), "{e}");

symlink(&victim, dir.join("x.log")).unwrap();
assert!(store.read("x.log").is_err());
assert!(store.append("x.log", b"z").is_err());
assert!(store.truncate("x.log", 0).is_err());
assert_eq!(std::fs::read(&victim).unwrap(), b"keep");
let target = dir.join("made-through-link");
symlink(&target, dir.join("y.log")).unwrap();
assert!(store.append("y.log", b"z").is_err());
assert!(!target.exists(), "a dangling link's target was created");
// real files as before (the append handle kept between appends included)
store.append("z.log", b"ab").unwrap();
store.append("z.log", b"cd").unwrap();
store.truncate("z.log", 2).unwrap();
assert_eq!(store.read("z.log").unwrap().unwrap(), b"ab");
let _ = std::fs::remove_dir_all(&dir);
}

/// The journal's append and truncate (which recovery uses) refuse a non-regular file at the
/// name instead of following it, so a link planted at `catalog.log` never receives library
/// bytes (CWE-59, Audit row 107); the snapshot write already removes such a link (#1502).
Expand Down
21 changes: 21 additions & 0 deletions crates/catalog/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::sync::Arc;

use lcc_develop::DevelopSettings;
use serde_json::json;

use super::*;

Expand All @@ -12,6 +13,26 @@ fn photo(c: &mut Catalog, name: &str, date: &str) -> PhotoId {
id
}

#[cfg(test)]
mod filter_deserialize_tests {
use super::*;

/// #2241: a filter key that is not one of `Filter`'s fields (a typo or a guessed name such as
/// `cameraModel` instead of `camera`) is rejected, not silently dropped: an agent or script that
/// filters by `cameraModel` must not be handed the whole library and told the filter worked.
#[test]
fn unknown_filter_key_is_rejected_not_ignored() {
let e = serde_json::from_value::<Filter>(json!({ "cameraModel": "X2" })).unwrap_err().to_string();
assert!(e.contains("cameraModel"), "the unknown key is named: {e}");

let e = serde_json::from_value::<Filter>(json!({ "foo": 1 })).unwrap_err().to_string();
assert!(e.contains("foo"), "the unknown key is named: {e}");

// the valid key is still accepted; `camera` is the field `cameraModel` was close to.
serde_json::from_value::<Filter>(json!({ "camera": "X2" })).unwrap();
}
}

#[test]
fn apply_and_inverse_roundtrip() {
let mut c = Catalog::new();
Expand Down
Loading