From 318190c6e2f5dfe3e364b0ed5d573b346a80a89a Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:08:36 -0700 Subject: [PATCH 1/8] Refuse a destination that reaches the source under another name Destinations were compared with the source by resolved path only. POSIX realpath keeps the typed case, so on a case-insensitive volume a destination naming the source in another case passed, and a destination folder that was a junction or symlink into the source passed too. Each staging file was then written beside its clip and promoted over it, and the job read Verified with nothing off the card. assert_safe_destinations now also compares by identity along each destination's existing ancestors, a per-directory guard refuses staging into any folder that is or is inside the source (the file fails, nothing is created), and the copy's last check covers the final name as well as the staging path, by resolved path and identity. --- CHANGELOG.md | 8 ++ docs/data-safety.md | 22 +++++ src/offloader/engine.py | 173 ++++++++++++++++++++++++++++++++++++- tests/test_data_safety.py | 175 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 374 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21ed0d7..794d58b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,14 @@ project uses [semantic versioning][semver]. ### Fixed +- **The source could become its own "verified" copy.** A destination that + named the source in another case on a case-insensitive volume + (`/Volumes/a001` for `/Volumes/A001`), or a destination folder that was a + junction or symlink into the source, put each staging file beside its clip + and then replaced the clip with its own copy, and the job read Verified. + Destinations are now compared with the source and with each other by + identity as well as by resolved path, and every folder a copy is staged in + is checked before anything is written there; a file refused this way fails. - **A timeline offload could call a partial cut complete.** With nothing to copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/docs/data-safety.md b/docs/data-safety.md index d294748..363b1d5 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -39,6 +39,28 @@ own source. The check lives in the engine, not the interface, so the CLI, the GUI and library callers all get it — previously only the GUI checked, and the CLI had nothing. +Comparing resolved paths is not enough on its own. POSIX `realpath` keeps the +case a path was typed in, so on APFS or exFAT `--source /Volumes/A001 --dest +/Volumes/a001` passed both checks; each staging file was written beside its +clip, and promotion replaced the clip with its own copy. Everything read +Verified and nothing existed off the card. A bind mount or a substituted drive +hides an alias from `realpath` on any platform. So destinations are also +compared with the source, and with each other, by identity (device and file +id): a destination that is the source, a destination with the source among its +existing ancestors, and two destinations that are one folder are all refused. +A destination that does not exist yet is judged by its nearest existing +ancestors. + +A safe destination root can still hold a folder that leads back into the +source: `dst/Clips` as a junction or symlink to `src/Clips`. Before anything is +staged or created in a folder, the copy checks that folder, by resolved path +and by identity along its existing ancestors, and refuses one that is or is +inside the source. A refused file fails at every destination with the reason, +so the job reads Failed, and nothing is created for it. `_copy_fanout`'s own +check now compares the staging path *and* the final name it will be promoted +to, by resolved path and by identity. Filesystems that report a file id of 0 +are judged by resolved path alone. + ### 2. A failed copy destroyed the good copy it was replacing Re-running an offload over an existing archive, with the card failing partway: diff --git a/src/offloader/engine.py b/src/offloader/engine.py index 4bbdaa9..4b734bf 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -91,9 +91,20 @@ def assert_safe_destinations(source_root: Path, destinations: Sequence[Path]) -> Enforced here rather than in the interface so the CLI, the GUI and any library caller are all covered. + + Resolved paths are compared first, and then the directories themselves. + `resolve` keeps the case the path was typed in on POSIX, so on a + case-insensitive volume (APFS, exFAT) `/Volumes/a001` resolves to a + different path from `/Volumes/A001` while naming the same folder, and a + junction or mount can alias a folder in ways a path never shows. A + destination that does not exist yet is judged by the ancestors that do. """ source = Path(source_root).resolve() + source_id = _identity(source_root) seen: dict[Path, Path] = {} + #: Destination -> (identity of its nearest existing directory, the part + #: of it below that directory), for comparing destinations by identity. + placed: list[tuple[Path, tuple[int, int], str]] = [] for destination in destinations: resolved = Path(destination).resolve() @@ -115,6 +126,120 @@ def assert_safe_destinations(source_root: Path, destinations: Sequence[Path]) -> ) seen[resolved] = Path(destination) + chain = _existing_chain(Path(destination)) + if source_id is not None: + for position, (_, identity) in enumerate(chain): + if identity != source_id: + continue + if position == 0 and chain[0][0] == Path(destination).absolute(): + raise UnsafeDestination( + f"destination {destination} is the source {source_root} " + "itself under another name; copying a card onto " + "itself would destroy it" + ) + raise UnsafeDestination( + f"destination {destination} is inside the source " + f"{source_root}, reached under another name; choose a " + "destination outside it" + ) + if chain: + nearest, identity = chain[0] + below = Path(destination).absolute().relative_to(nearest) + # Casefolded: a part that does not exist yet will be created on + # the same volume as `nearest`, which may not tell case apart. + # Refusing two names that differ only in case is the safe side. + tail = _collision_key(below) + for other, other_id, other_tail in placed: + if other_id == identity and other_tail == tail: + raise UnsafeDestination( + f"destinations {other} and {destination} are the same " + "directory" + ) + placed.append((Path(destination), identity, tail)) + + +def _identity(path: Path) -> tuple[int, int] | None: + """(device, file id) of what is at `path`, or None when unknown. + + None when nothing is there, and also when the filesystem reports a file + id of 0: some network filesystems do that for everything, and treating + every folder on them as the same folder would refuse every offload. + """ + try: + info = os.stat(longpath.extended(path)) + except (OSError, ValueError): + return None + if not info.st_ino: + return None + return (info.st_dev, info.st_ino) + + +def _existing_chain(path: Path) -> list[tuple[Path, tuple[int, int]]]: + """`path` and each of its ancestors that exists, nearest first, with + their identities. + + Lexical ancestors of the absolute path, `..` and all, so a link part-way + up is examined as itself and as whatever it points at, via `stat`. + """ + absolute = Path(path).absolute() + chain: list[tuple[Path, tuple[int, int]]] = [] + for candidate in (absolute, *absolute.parents): + identity = _identity(candidate) + if identity is not None: + chain.append((candidate, identity)) + return chain + + +def _real_path(path: Path) -> Path: + """`path` with every link resolved, compared in its ordinary form. + + Resolved through the extended form so a name Win32 would rewrite is + resolved as itself, then shortened again so that two paths are compared + in the same form whichever of them needed the prefix. + """ + return Path(longpath.shorten_for_display( + os.path.realpath(longpath.extended(path)))) + + +class _SourceGuard: + """Refuses, per target directory, any write into the source tree. + + `assert_safe_destinations` judges each destination *root*. A folder + beneath an otherwise safe root can still lead back into the source: a + `dst/Clips` that is a junction or symlink to `src/Clips` puts every + staging file beside the clip it is a copy of, and promotion then replaces + the clip with its own copy. Everything reads Verified and nothing exists + off the card. So each directory a copy is about to be staged in is + checked, by resolved path and by identity along its existing ancestors, + before anything is created in it. Verdicts are cached per directory, + since a card's files share a handful of folders. + """ + + def __init__(self, source_root: Path) -> None: + self._root = Path(source_root) + self._real = _real_path(source_root) + self._identity = _identity(source_root) + self._verdicts: dict[Path, str | None] = {} + + def refusal(self, directory: Path) -> str | None: + """Why nothing may be written in `directory`, or None.""" + directory = Path(directory) + if directory in self._verdicts: + return self._verdicts[directory] + verdict: str | None = None + real = _real_path(directory) + if real == self._real or self._real in real.parents: + verdict = (f"refusing to write in {directory}: it leads into the " + f"source {self._root} (it resolves to {real})") + elif self._identity is not None: + for candidate, identity in _existing_chain(directory): + if identity == self._identity: + verdict = (f"refusing to write in {directory}: {candidate} " + f"is the source {self._root} under another name") + break + self._verdicts[directory] = verdict + return verdict + def _collision_key(path: Path) -> str: """A name as a case-insensitive, normalization-insensitive volume sees it.""" @@ -824,6 +949,8 @@ def _copy_fanout(source: Path, targets: Sequence[Path], algorithm: str, src_hasher = new_hasher(algorithm) dst_hashers = [new_hasher(algorithm) for _ in targets] + real_source = Path(longpath.extended(source)).resolve() + source_id = _identity(source) for target in targets: # Last line of defence: opening a target with "wb" truncates it, so a # target that *is* the source would destroy the original before a byte @@ -831,10 +958,20 @@ def _copy_fanout(source: Path, targets: Sequence[Path], algorithm: str, # before now; refuse anyway rather than trust that it did. # Resolved in extended form, so a name Win32 would rewrite is compared # as itself and not as whatever its trimmed namesake resolves to. - if (Path(longpath.extended(target)).resolve() - == Path(longpath.extended(source)).resolve()): - raise UnsafeDestination( - f"refusing to write {target}: it is the source file") + # The final name the staging file will be promoted to is checked as + # well: promoting over the source replaces it as surely as truncating + # it does. Identity is compared too, because a resolved path keeps the + # typed case on POSIX and so misses a case-insensitive alias. + candidates = [target] + if target.name.endswith(PARTIAL_SUFFIX): + candidates.append( + target.with_name(target.name[:-len(PARTIAL_SUFFIX)])) + for candidate in candidates: + if (Path(longpath.extended(candidate)).resolve() == real_source + or (source_id is not None + and _identity(candidate) == source_id)): + raise UnsafeDestination( + f"refusing to write {target}: it is the source file") longpath.makedirs(target.parent) chunks: queue.Queue = queue.Queue(maxsize=READ_AHEAD) @@ -1251,6 +1388,12 @@ def emit(event: ProgressEvent) -> None: # pays the failed extraction, the remaining clips skip it. thumb_memo = thumbs.DecoderMemo() + # A card is one tree, and nothing may be written anywhere in it. A + # selection's source is a label (often a timeline file), and its search + # roots may legitimately hold the destination, so it relies on + # `assert_selection_is_safe` and on `_copy_fanout`'s own check instead. + guard = _SourceGuard(source_root) if options.selection is None else None + for index, source in enumerate(transfer): # Between files is the cheapest place to honour a pause or cancel. if control is not None: @@ -1307,6 +1450,28 @@ def emit(event: ProgressEvent) -> None: 0, stat.st_size, counters.job_bytes_done, counters.job_bytes_total)) + # Before the skip check as well as the copy: a destination file that + # is really the source matches it on size, and would be reported as + # present at the destination. + refusals = ([guard.refusal(target.parent) for target in targets] + if guard is not None else []) + if any(refusals): + # The whole file, not just the refused destination: the fan-out + # writes every destination in one pass, and the job is a + # misconfiguration that reads Failed either way. Nothing has been + # created, so there is nothing to clean up. + refused = next(reason for reason in refusals if reason) + counters.errors.append(f"{source}: {refused}") + for root, target, reason in zip(dest_roots, targets, refusals, + strict=True): + entry.destinations.append(Destination( + root=root, path=target, status=FileStatus.FAILED, + error=reason or ("not copied, because another destination " + f"for this file was refused: {refused}"))) + counters.job_bytes_done += stat.st_size + job.files.append(entry) + continue + if options.skip_existing and all( _size_or_none(t) == stat.st_size for t in targets ): diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index 92f1af4..2965415 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -12,6 +12,9 @@ from __future__ import annotations import builtins +import os +import platform +import subprocess from pathlib import Path import pytest @@ -20,6 +23,7 @@ from offloader.models import FileStatus, VerificationMode PAYLOAD = b"IRREPLACEABLE FOOTAGE " * 5000 +WINDOWS = platform.system() == "Windows" def _options(tmp_path: Path, **overrides) -> engine.OffloadOptions: @@ -87,6 +91,177 @@ def test_copy_fanout_refuses_to_write_over_its_own_source(tmp_path: Path): assert source.read_bytes() == PAYLOAD +def _link_directory(link: Path, target: Path) -> None: + """A directory junction on Windows, which needs no admin rights, and a + symlink elsewhere. Skips the test when neither can be made.""" + if WINDOWS: + made = subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], + capture_output=True, text=True) + if made.returncode != 0: + pytest.skip(f"could not create a junction: {made.stderr.strip()}") + return + try: + link.symlink_to(target, target_is_directory=True) + except OSError as exc: + pytest.skip(f"could not create a symlink: {exc}") + + +def _case_insensitive(directory: Path) -> bool: + probe = directory / "case-probe" + probe.write_bytes(b"") + try: + return (directory / "CASE-PROBE").exists() + finally: + probe.unlink() + + +def _resolve_as_typed(monkeypatch) -> None: + """Make path resolution keep the typed case and see through nothing. + + That is what POSIX `realpath` does on a case-insensitive volume + (`/Volumes/a001` stays `/Volumes/a001` though the folder is `A001`), and + what every platform's does across a bind mount or a substituted drive. + It lets the identity checks be proven on a machine whose own resolve + happens to normalize case. + """ + monkeypatch.setattr(os.path, "realpath", + lambda path, *args, **kwargs: os.path.abspath(path)) + + +def _identity(path: Path) -> tuple[int, int]: + info = os.stat(path) + return info.st_dev, info.st_ino + + +def _partials_under(root: Path) -> list[Path]: + return [p for p in root.rglob("*") if p.name.endswith(engine.PARTIAL_SUFFIX)] + + +@pytest.mark.parametrize("relative", ["CARD", "CARD/backup"]) +def test_a_case_variant_of_the_source_is_refused_as_a_destination( + tmp_path: Path, relative): + """`--source /Volumes/A001 --dest /Volumes/a001` on APFS: resolve kept + the typed case, so the equality checks passed, each staging file was + written beside its clip and the existing-file check, finding identical + content, replaced the clip with its own copy. Everything read Verified + and nothing existed off the card. + + Runs wherever the temporary filesystem is case-insensitive. On Windows it + passed before the identity checks too, since `resolve` there returns the + on-disk case and `WindowsPath` compares case-insensitively; the test + below proves the identity check itself on any platform.""" + card = _card(tmp_path) + if not _case_insensitive(tmp_path): + pytest.skip("the temporary filesystem is case-sensitive") + clip = card / "A001_C001.mov" + before = _identity(clip) + + with pytest.raises(engine.UnsafeDestination, match="source"): + engine.run(card, _options(tmp_path, destinations=[tmp_path / relative])) + + assert clip.read_bytes() == PAYLOAD + assert _identity(clip) == before + assert _partials_under(card) == [] + + +@pytest.mark.parametrize("below", ["", "backup"]) +def test_an_alias_of_the_source_that_resolve_cannot_see_is_refused( + tmp_path: Path, monkeypatch, below): + """The same failure as the case-variant destination, by the same route: + a path to the source that `resolve` does not map back to it. Here it is + a link with resolution made blind to it, as it is to a bind mount or a + substituted drive, which reproduces the bug on a case-insensitive Windows + machine too.""" + card = _card(tmp_path) + clip = card / "A001_C001.mov" + before = _identity(clip) + _link_directory(tmp_path / "alias", card) + destination = tmp_path / "alias" / below if below else tmp_path / "alias" + _resolve_as_typed(monkeypatch) + + with pytest.raises(engine.UnsafeDestination, match="source"): + engine.run(card, _options(tmp_path, destinations=[destination])) + + monkeypatch.undo() + assert clip.read_bytes() == PAYLOAD + assert _identity(clip) == before + assert _partials_under(card) == [] + + +def test_two_destinations_that_are_one_folder_by_identity_are_refused( + tmp_path: Path, monkeypatch): + """A bind mount or a substituted drive is one folder under two paths that + no resolve can see through. Both copies would be one file.""" + card = _card(tmp_path) + dest = tmp_path / "dest" + dest.mkdir() + _link_directory(tmp_path / "alias", dest) + _resolve_as_typed(monkeypatch) + with pytest.raises(engine.UnsafeDestination, match="same directory"): + engine.assert_safe_destinations(card, [dest, tmp_path / "alias"]) + # Not yet existing below a shared folder: judged by that folder. + with pytest.raises(engine.UnsafeDestination, match="same directory"): + engine.assert_safe_destinations( + card, [dest / "A001", tmp_path / "alias" / "A001"]) + + +def test_two_destinations_that_are_one_folder_through_a_link_are_refused( + tmp_path: Path): + card = _card(tmp_path) + dest = tmp_path / "dest" + dest.mkdir() + _link_directory(tmp_path / "alias", dest) + with pytest.raises(engine.UnsafeDestination, match="same directory"): + engine.run(card, _options(tmp_path, destinations=[dest, tmp_path / "alias"])) + assert list(dest.iterdir()) == [] + + +@pytest.mark.parametrize("verification", list(VerificationMode)) +@pytest.mark.parametrize("skip_existing", [False, True]) +def test_a_destination_folder_linked_into_the_source_is_never_written( + tmp_path: Path, verification, skip_existing): + """The destination root is fine, but `dst/Clips` is a junction (or + symlink) to `src/Clips`. The staging file was written inside the source + folder and then replaced the clip it was a copy of.""" + card = tmp_path / "card" + (card / "Clips").mkdir(parents=True) + clip = card / "Clips" / "A001_C001.mov" + clip.write_bytes(PAYLOAD) + before = _identity(clip) + dest = tmp_path / "dest" + dest.mkdir() + _link_directory(dest / "Clips", card / "Clips") + + job = engine.run(card, _options(tmp_path, verification=verification, + skip_existing=skip_existing)) + + assert clip.read_bytes() == PAYLOAD + assert _identity(clip) == before + assert _partials_under(card) == [] + assert job.final_status == "Failed" + (entry,) = job.files + assert entry.status is FileStatus.FAILED + assert "source" in entry.destinations[0].error + + +def test_copy_fanout_refuses_a_staging_file_promoted_over_its_source( + tmp_path: Path, monkeypatch): + """The last line of defence compared only the staging path with the + source, by resolved path. The final name is what promotion replaces, and + a resolve that keeps the typed case misses the alias altogether.""" + card = _card(tmp_path) + if not _case_insensitive(tmp_path): + pytest.skip("the temporary filesystem is case-sensitive") + source = card / "A001_C001.mov" + staging = tmp_path / "CARD" / ("A001_C001.mov" + engine.PARTIAL_SUFFIX) + _resolve_as_typed(monkeypatch) + with pytest.raises(engine.UnsafeDestination, match="it is the source"): + engine._copy_fanout(source, [staging], "xxh3-64", lambda n: None) + monkeypatch.undo() + assert not staging.exists() + assert source.read_bytes() == PAYLOAD + + def test_the_source_is_never_opened_for_writing(tmp_path: Path, monkeypatch): """Nothing in the pipeline may open a file under the source root in any mode that can modify it.""" From dcd1aaf369f7846cbac0847e719b03ff0e6e237d Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:11:48 -0700 Subject: [PATCH 2/8] Never copy a leftover staging file or open an existing one A source file named *.offloader-partial was copied like any other, under a final name that a later file's staging name could equal, so it could be truncated or deleted after being reported Verified. The scan now leaves such files out (casefolded) and reports each one as a job warning, without failing the job or adding a manifest entry; selections apply the same rule to source and final names. A file already at a staging name is never opened with wb or deleted: the copy is staged under the next free staging name and a warning names the file left alone. --- CHANGELOG.md | 7 +++ README.md | 4 +- docs/data-safety.md | 20 ++++++ src/offloader/engine.py | 106 +++++++++++++++++++++++++++++--- tests/test_data_safety.py | 126 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 253 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 794d58b..d3c64f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,13 @@ project uses [semantic versioning][semver]. Destinations are now compared with the source and with each other by identity as well as by resolved path, and every folder a copy is staged in is checked before anything is written there; a file refused this way fails. +- **A leftover staging file could be certified and then destroyed.** A + source file named `*.offloader-partial` (a leftover on a re-offloaded + shuttle drive) was copied under that name, where a later file's staging + copy could truncate or delete it after it was reported Verified. Such files + are no longer copied; each is named in a job warning. An existing file at a + staging name is never opened: the copy is staged under the next free + staging name and the file is left alone, with a warning. - **A timeline offload could call a partial cut complete.** With nothing to copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/README.md b/README.md index aeabcdf..ee5f271 100644 --- a/README.md +++ b/README.md @@ -542,7 +542,9 @@ The short version: by the engine, so the CLI, GUI and library callers cannot disagree about it. - Files are written under a `.offloader-partial` name and only moved into place once complete and verified. A failed or interrupted copy never damages what - was already there and never leaves a plausible-looking filename. + was already there and never leaves a plausible-looking filename. A source + file already named like that is a leftover, and is reported rather than + copied. - `--verify full` evicts each file from the page cache before reading it back, because a read straight after a write is otherwise served from memory and proves nothing about the device. diff --git a/docs/data-safety.md b/docs/data-safety.md index 363b1d5..8072fae 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -85,6 +85,26 @@ the *right name* and the wrong length. That is the most dangerous artefact an offload tool can produce — it survives a visual check, and it survives a size-only comparison on the next run. +Cleanup deletes staging files and promotion replaces them, which is only safe +while no real final file carries the suffix. So a source file whose name ends +in `.offloader-partial` (compared case-insensitively) is never copied. It is a +leftover from an interrupted offload, typically on a shuttle drive being +offloaded again. It used to be copied like any other file, under a final name +that a later file's staging name could equal; that file was then truncated or +deleted after being reported Verified. Each one is named in a job warning +saying it was not copied. It does not fail the job and has no manifest entry: +it is not card content, and an unhashed entry could never be answered by a +rerun. The rule is applied in the scan, so the copy, `report` and the app's +duplicate-card check all see the same file list, and to a timeline selection, +by source name and by final name. + +A file already sitting at a staging name is never opened or deleted either. It +may be a partial left by an interrupted run, but it may also be a file an +earlier version copied under that name and reported Verified, and nothing +distinguishes the two. The copy is staged as `.2.offloader-partial` (or +the next free number) instead, and a warning names the file that was left +alone, which can be deleted once nothing needs it. + ## What "verified" actually means Three modes, and it is worth being precise about what each proves. diff --git a/src/offloader/engine.py b/src/offloader/engine.py index 4b734bf..4ec4e9b 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -61,6 +61,25 @@ PARTIAL_SUFFIX = ".offloader-partial" +def is_staging_name(name: str) -> bool: + """Whether `name` is a staging file's, as a case-insensitive volume sees it. + + Cleanup deletes staging files and promotion replaces them, which is only + safe while no real final file can carry the suffix. So a source file named + like one is never copied: it is a leftover from an interrupted offload, + and copying it would give it a final name that a later file's staging + name can equal, to be truncated or deleted after it was reported Verified. + Casefolded, like `_collision_key`, because the destination volume may not + tell `X.MOV.OFFLOADER-PARTIAL` from the staging name of `x.mov`. + """ + return unicodedata.normalize("NFC", name.casefold()).endswith(PARTIAL_SUFFIX) + + +def _staging_warning(path: Path, consequence: str = "was not copied") -> str: + return (f"{path} is a leftover staging file from an interrupted offload " + f"(its name ends in {PARTIAL_SUFFIX}) and {consequence}") + + class _ReaderStopped(Exception): """Raised inside the read-ahead thread when the copy stopped under it.""" @@ -766,7 +785,8 @@ def _is_directory_link(path: str) -> bool: def scan(root: Path, excludes: Iterable[str] = DEFAULT_EXCLUDES, *, errors: list[ScanProblem] | None = None, - links: list[Path] | None = None) -> list[Path]: + links: list[Path] | None = None, + staging: list[Path] | None = None) -> list[Path]: """Every file under `root`, sorted, with junk filtered out. A directory that cannot be listed is appended to `errors` rather than @@ -783,6 +803,12 @@ def scan(root: Path, excludes: Iterable[str] = DEFAULT_EXCLUDES, *, directory is always scanned under its real name. The root is entered even when it is itself a link: that is the folder the operator chose. + A file whose name is a staging file's (`is_staging_name`) is never + returned, whatever `excludes` says, and each one is appended to `staging` + so the caller can say so. It is left out here rather than in `run()` so + every caller (the copy, `rescan`, the app's duplicate-card fingerprint) + sees the same file list. + The walk runs on the extended-length form of the root (see `longpath`), so a directory whose name Win32 would trim, or one past MAX_PATH, is listed as itself. The paths returned are in the form `root` was given in. @@ -836,8 +862,13 @@ def onerror(exc: OSError) -> None: dirnames[:] = keep for filename in sorted(filenames): candidate = here / filename - if not is_excluded(candidate, patterns): - found.append(candidate) + if is_excluded(candidate, patterns): + continue + if is_staging_name(filename): + if staging is not None: + staging.append(candidate) + continue + found.append(candidate) return found @@ -1214,6 +1245,33 @@ def _warn_on_split_companions(job: Job) -> None: ) +def _staging_path(target: Path) -> tuple[Path, Path | None]: + """Where to stage `target`, and the existing file that was in the way. + + Normally `.offloader-partial`. Opening that with "wb" truncates + whatever is there, and cleanup deletes it, so an existing file at that + name is never used: it may be a partial an interrupted run left behind, + but it may also be a file an earlier version copied under that name and + reported Verified (a leftover partial on a re-offloaded shuttle drive). + Nothing here can tell which, so it is left alone and the copy is staged + as `.2.offloader-partial` or the next free number instead. Every + candidate still ends in the suffix, so it is still recognisably a staging + file. Judged by `lstat`, so a dangling link at the name is not followed. + """ + first = target.with_name(target.name + PARTIAL_SUFFIX) + candidate, number = first, 1 + while True: + try: + longpath.lstat(candidate) + except (OSError, ValueError): + # Free, or under a folder that is not there yet. Anything else + # that stops `lstat` (no permission, no such volume) stops the + # open too, which then fails the file with the real error. + return candidate, (None if candidate == first else first) + number += 1 + candidate = target.with_name(f"{target.name}.{number}{PARTIAL_SUFFIX}") + + def _discard(targets: Iterable[Path]) -> None: """Delete half-written destinations. A partial file that looks complete is worse than no file at all.""" @@ -1282,18 +1340,32 @@ def run(source_root: Path, options: OffloadOptions, #: A selection is not scanned, so both stay empty for one. scan_errors: list[ScanProblem] = [] links: list[Path] = [] + #: Files named like a staging file, which are never copied (see + #: `is_staging_name`). Reported as warnings; not card content, so they + #: neither fail the job nor get a manifest entry. + staging: list[Path] = [] if options.selection is not None: assert_selection_is_safe(options.selection, dest_roots) - files = [Path(entry.source) for entry in options.selection] + selection = [] + for entry in options.selection: + # The final name too: a selector chooses it, and it is the name + # that must never carry the suffix. + if (is_staging_name(Path(entry.source).name) + or is_staging_name(Path(entry.relative).name)): + staging.append(Path(entry.source)) + else: + selection.append(entry) + files = [Path(entry.source) for entry in selection] seen = {os.path.normcase(str(p)) for p in files} if len(seen) != len(files): raise ValueError("selection lists the same source file twice") - relatives = {Path(e.source): Path(e.relative) for e in options.selection} - roots = {Path(e.source): Path(e.root) for e in options.selection} + relatives = {Path(e.source): Path(e.relative) for e in selection} + roots = {Path(e.source): Path(e.root) for e in selection} else: assert_safe_destinations(source_root, dest_roots) - files = scan(source_root, options.excludes, errors=scan_errors, links=links) + files = scan(source_root, options.excludes, errors=scan_errors, + links=links, staging=staging) roots = {} assert_no_destination_collisions(files, source_root, dest_roots, @@ -1354,6 +1426,8 @@ def run(source_root: Path, options: OffloadOptions, f"{link} is a symbolic link or junction and was not followed, so " "nothing under it was copied; offload its target directly if it " "is needed") + for path in staging: + job.warnings.append(_staging_warning(path)) job.report_dir_name = choose_report_folder( job.name, files, source_root, dest_roots, options.preserve_structure, @@ -1492,7 +1566,17 @@ def emit(event: ProgressEvent) -> None: # Write under a temporary name and only rename once the copy is proven. # An existing good file at the destination is never opened, so a failed # or interrupted attempt cannot take it down with it. - partials = [t.with_name(t.name + PARTIAL_SUFFIX) for t in targets] + partials = [] + for target in targets: + partial, in_the_way = _staging_path(target) + partials.append(partial) + if in_the_way is not None: + job.warnings.append( + f"{in_the_way} was already at the destination and was left " + f"alone; this copy was staged as {partial.name} instead. It " + "is a leftover from an interrupted offload, or a file an " + "earlier version copied under that name, and can be " + "deleted once nothing needs it") bytes_at_start = counters.job_bytes_done @@ -1931,7 +2015,9 @@ def rescan(source_root: Path, destination_roots: Sequence[Path], source_root = Path(source_root) scan_errors: list[ScanProblem] = [] links: list[Path] = [] - files = scan(source_root, options.excludes, errors=scan_errors, links=links) + staging: list[Path] = [] + files = scan(source_root, options.excludes, errors=scan_errors, links=links, + staging=staging) algorithm = get_algorithm(options.algorithm) host = sysinfo.collect() @@ -1956,6 +2042,8 @@ def rescan(source_root: Path, destination_roots: Sequence[Path], scan_errors.append(ScanProblem(link, "not followed", link=True)) job.warnings.append( f"{link} is a symbolic link or junction and was not followed") + for path in staging: + job.warnings.append(_staging_warning(path, "was left out of this report")) thumb_dir = options.thumbnail_dir or (source_root / f"{job.name}_Reports" / "thumbs") thumb_memo = thumbs.DecoderMemo() total = sum(_size_or_zero(p) for p in files) diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index 2965415..0d18ac3 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -622,3 +622,129 @@ def test_paranoid_says_so_when_it_could_not_drop_the_cache(tmp_path: Path, assert any("second read" in w and "memory" in w for w in job.warnings), \ job.warnings + + +# ------------------------------------------------------------ staging names + + +def _tree(root: Path, files: dict[str, bytes]) -> Path: + for relative, data in files.items(): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return root + + +@pytest.mark.parametrize("preserve_structure", [True, False], + ids=["structure", "flat"]) +@pytest.mark.parametrize("leftover", [ + "B/x.mov.offloader-partial", + "B/x.mov.OFFLOADER-Partial", + # Scanned before the clip, so the old code promoted it first and the + # clip's staging file, when flattened, then truncated it. + "0/x.mov.offloader-partial", +]) +def test_a_leftover_staging_file_on_the_card_is_reported_not_copied( + tmp_path: Path, capsys, preserve_structure, leftover): + """A shuttle drive re-offloaded after an interrupted run holds a staging + file. It used to be copied like any other file and given a final name + that a later file's staging name could equal, to be truncated or deleted + after it had been reported Verified.""" + from offloader import cli + + card = _tree(tmp_path / "card", {"A/x.mov": PAYLOAD, + leftover: b"half of somebody's clip"}) + dest = tmp_path / "dest" + job = engine.run(card, _options(tmp_path, + preserve_structure=preserve_structure)) + + assert job.final_status == "Verified" + assert [entry.relative.as_posix() for entry in job.files] == ["A/x.mov"] + assert _partials_under(dest) == [] + target = dest / ("A/x.mov" if preserve_structure else "x.mov") + assert target.read_bytes() == PAYLOAD + named = Path(leftover).name + assert any(named in w and "not copied" in w for w in job.warnings), job.warnings + rows = [Path(row.path).name for row in job.manifest_rows(0)] + assert rows == ["x.mov"] + # Every caller of scan sees the same list, the app's duplicate-card + # fingerprint among them. + assert engine.scan(card) == [entry.source for entry in job.files] + assert (card / leftover).read_bytes() == b"half of somebody's clip" + + # And the CLI says so. + assert cli.main(["offload", "--source", str(card), "--dest", + str(tmp_path / "dest2"), "--no-probe", "--quiet", + "--retries", "1"]) == 0 + assert named in capsys.readouterr().err + + +def test_scan_reports_staging_files_it_leaves_out(tmp_path: Path): + card = _tree(tmp_path / "card", {"x.mov": b"1", "y.MOV.Offloader-Partial": b"2"}) + staging: list[Path] = [] + # Excludes do not bring them back: the rule is not a preference. + assert engine.scan(card, (), staging=staging) == [card / "x.mov"] + assert staging == [card / "y.MOV.Offloader-Partial"] + + +def test_a_selection_never_copies_a_staging_file(tmp_path: Path): + card = _tree(tmp_path / "lib", {"x.mov": PAYLOAD, + "y.mov.offloader-partial": b"leftover", + "z.mov": b"zed"}) + dest = tmp_path / "dest" + selection = [ + engine.SelectedFile(card / "x.mov", Path("x.mov"), card), + engine.SelectedFile(card / "y.mov.offloader-partial", + Path("y.mov.offloader-partial"), card), + # A final name the selector chose that carries the suffix. + engine.SelectedFile(card / "z.mov", Path("z.mov.offloader-partial"), card), + ] + job = engine.run(card, _options(tmp_path, selection=selection)) + assert job.final_status == "Verified" + assert [entry.source.name for entry in job.files] == ["x.mov"] + assert _partials_under(dest) == [] + assert sum("not copied" in w for w in job.warnings) == 2, job.warnings + + +def test_a_rerun_never_truncates_a_file_already_at_a_staging_name(tmp_path: Path): + """Before staging names were refused on the card, a leftover partial was + copied and promoted under its own name, `Clips/x.mov.offloader-partial`, + and an earlier manifest lists it as verified. That is exactly where a + rerun stages `Clips/x.mov`: opening it with "wb" truncated it, and + promotion then renamed it away. Nothing can tell that file from a partial + an interrupted run left, so it is never opened, and the copy is staged + under the next free staging name instead.""" + card = _tree(tmp_path / "card", {"Clips/x.mov": PAYLOAD}) + dest = tmp_path / "dest" + earlier = _tree(dest, {"Clips/x.mov.offloader-partial": b"verified last time"}) + stale = earlier / "Clips" / "x.mov.offloader-partial" + before = _identity(stale) + + job = engine.run(card, _options(tmp_path)) + + assert job.final_status == "Verified" + assert (dest / "Clips" / "x.mov").read_bytes() == PAYLOAD + assert stale.read_bytes() == b"verified last time" + assert _identity(stale) == before + assert _partials_under(dest) == [stale] + assert any("x.mov.offloader-partial" in w and "left alone" in w + for w in job.warnings), job.warnings + + +def test_a_failed_copy_staged_under_another_name_leaves_the_staging_name_alone( + tmp_path: Path, monkeypatch): + """Cleanup after a failure deletes only the staging file this run made.""" + card = _tree(tmp_path / "card", {"x.mov": PAYLOAD}) + dest = _tree(tmp_path / "dest", {"x.mov.offloader-partial": b"not ours"}) + real = engine.longpath.open_binary + + def failing(path, mode="rb"): + if "r" in mode and str(path).endswith("card" + os.sep + "x.mov"): + raise PermissionError(13, "Access is denied", str(path)) + return real(path, mode) + + monkeypatch.setattr(engine.longpath, "open_binary", failing) + job = engine.run(card, _options(tmp_path, retry=_fast())) + assert job.final_status == "Failed" + assert (dest / "x.mov.offloader-partial").read_bytes() == b"not ours" + assert _partials_under(dest) == [dest / "x.mov.offloader-partial"] \ No newline at end of file From 37e172e9c7dcfa5783e1f7c8b5c6265b34bafd58 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:13:39 -0700 Subject: [PATCH 3/8] Sanitize every job name before it becomes a folder name The job name, from --name, the app's job name, the source folder's name or the volume label, was joined onto each destination as _Reports unsanitized. A traversal or separator in it wrote reports outside the destination, and a colon or trailing dot failed on Windows. Both places a Job is built now pass the final name through naming.sanitize, and a typed name that changed gets a warning naming the one used. --- CHANGELOG.md | 5 +++ docs/data-safety.md | 1 + src/offloader/engine.py | 55 ++++++++++++++++++----- tests/test_data_safety.py | 94 ++++++++++++++++++++++++++++++++++++++- 4 files changed, 142 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3c64f3..01af32c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,11 @@ project uses [semantic versioning][semver]. are no longer copied; each is named in a job warning. An existing file at a staging name is never opened: the copy is staged under the next free staging name and the file is left alone, with a warning. +- **A job name could put reports outside the destination.** `--name`, the + app's job name and the volume label were joined onto each destination as + `_Reports` unsanitized, so `..\..\X` or `a/b` wrote reports elsewhere + and `a:b` failed on Windows. Every job name is now sanitized by the engine, + with a warning when a typed name had to change. - **A timeline offload could call a partial cut complete.** With nothing to copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/docs/data-safety.md b/docs/data-safety.md index 8072fae..220b378 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -324,6 +324,7 @@ folder used. | A source folder that cannot be listed | The job fails, naming the folder, and the CLI exits `1`. Its manifests carry an unhashed entry for the folder, so `verify` fails too. It used to be dropped silently and the job read Verified. | | A file deleted after the scan | That file fails with "source vanished after scan"; the rest of the job carries on and its paperwork is written. | | A different card with the same folder layout | A finished copy never replaces an existing destination file whose content differs. The existing file is hashed and compared; identical content is replaced (that changes nothing), different content fails that file with the reason and keeps the existing copy. `--replace-existing` (in the app, *Replace existing files whose content differs*, off by default) overrides this. | +| A job name that is not one plain folder name | `--name`, the app's job name, the source folder's name and the volume label (removable-media metadata) all become `_Reports` inside each destination. Every one goes through `naming.sanitize`, so `..\..\X` or `a/b` cannot put reports outside the destination and `a:b` or a trailing dot cannot fail on Windows. A typed name that had to change is named in a warning with the name used. | | A source that already holds `_Reports` | Reports go to `_Reports-2` (or the next free number) with a warning; the copied folder is left as copied. | | Same-named clips in different folders | Thumbnail files are named by a hash of each clip's relative path, so one clip's frames never replace another's in the report. | | Corrupt config file | Treated as empty. Config must never stand between someone and their card. | diff --git a/src/offloader/engine.py b/src/offloader/engine.py index 4ec4e9b..5a1527a 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -20,7 +20,7 @@ from pathlib import Path from . import braw as braw_mod -from . import companions, integrity, longpath, sysinfo, thumbs, volumes +from . import companions, integrity, longpath, naming, sysinfo, thumbs, volumes from . import probe as probe_mod from . import retry as retry_mod from .hashers import get_algorithm, hash_file, new_hasher @@ -1392,14 +1392,11 @@ def run(source_root: Path, options: OffloadOptions, options.proxies_first and options.profile.probes_media) host = sysinfo.collect() + # A selection names its job after the timeline it came from, and a + # timeline is a file: ".xml" in a report header helps nobody. + name, renamed = _job_name(options.job_name, source_root, use_stem=True) job = Job( - # A selection names its job after the timeline it came from, and a - # timeline is a file: ".xml" in a report header helps nobody. A card - # offloaded from its root has no folder name; its volume label is what - # the operator calls it. - name=(options.job_name - or (source_root.stem if source_root.is_file() else source_root.name) - or volumes.volume_label(source_root) or "Offload"), + name=name, source_root=source_root, destination_roots=dest_roots, verification=options.verification, @@ -1414,6 +1411,8 @@ def run(source_root: Path, options: OffloadOptions, preserve_structure=options.preserve_structure, selection_relatives=dict(relatives or {}), ) + if renamed: + job.warnings.append(renamed) for problem in scan_errors: counters.errors.append(problem.describe()) @@ -1891,6 +1890,38 @@ def _size_or_zero(path: Path) -> int: return _size_or_none(path) or 0 +def _job_name(given: str | None, source_root: Path, *, + use_stem: bool) -> tuple[str, str | None]: + """The job's name, safe to use as a folder name, and a warning when an + explicitly given name had to change. + + The name becomes `_Reports`, joined onto every destination root, so + it has to be one plain folder name whatever its origin. `--name` and the + app's job name are typed; the fallbacks are the source folder's name and + the volume label, which is untrusted removable-media metadata. Unsanitized, + `..\\..\\X` or `a/b` put the reports outside the destination, and `a:b` + or a trailing dot fails on Windows. Only the app's naming templates used + to go through `naming.sanitize`; every name does now. + + `use_stem` names a job after a file source (a timeline) without its + extension. A card offloaded from its root has no folder name; its volume + label is what the operator calls it. + """ + if given: + name = naming.sanitize(given) + if name == given: + return name, None + return name, ( + f"the job name {given!r} cannot be used as a folder name as typed " + "(it holds a path separator or a character, or a leading or " + "trailing space or dot, that a destination may reject), so this " + f"job is named {name!r} and its reports are under that name") + fallback = ((source_root.stem if use_stem and source_root.is_file() + else source_root.name) + or volumes.volume_label(source_root) or "Offload") + return naming.sanitize(fallback), None + + def choose_report_folder(name: str, files: Sequence[Path], source_root: Path, dest_roots: Sequence[Path], preserve_structure: bool, relatives: dict[Path, Path] | None = None) -> str: @@ -2021,11 +2052,9 @@ def rescan(source_root: Path, destination_roots: Sequence[Path], algorithm = get_algorithm(options.algorithm) host = sysinfo.collect() + name, renamed = _job_name(options.job_name, source_root, use_stem=False) job = Job( - # A card offloaded from its root has no folder name; its volume - # label is what the operator calls it. - name=(options.job_name or source_root.name - or volumes.volume_label(source_root) or "Offload"), + name=name, source_root=source_root, destination_roots=[Path(d) for d in destination_roots] or [source_root], verification=options.verification, @@ -2038,6 +2067,8 @@ def rescan(source_root: Path, destination_roots: Sequence[Path], scan_errors=scan_errors, preserve_structure=options.preserve_structure, ) + if renamed: + job.warnings.append(renamed) for link in links: scan_errors.append(ScanProblem(link, "not followed", link=True)) job.warnings.append( diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index 0d18ac3..1f48de4 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -747,4 +747,96 @@ def failing(path, mode="rb"): job = engine.run(card, _options(tmp_path, retry=_fast())) assert job.final_status == "Failed" assert (dest / "x.mov.offloader-partial").read_bytes() == b"not ours" - assert _partials_under(dest) == [dest / "x.mov.offloader-partial"] \ No newline at end of file + assert _partials_under(dest) == [dest / "x.mov.offloader-partial"] + + +# ---------------------------------------------------------------- job names + + +HOSTILE_NAMES = ["../../X", "..\\..\\X", "a/b", "a:b", "X.", " X ", "..", "a\\b"] + + +def _files_under(root: Path) -> set[Path]: + return {path for path in root.rglob("*") if path.is_file()} + + +def _assert_reports_only_inside(tmp_path: Path, card: Path, dest: Path, + before: set[Path]) -> list[Path]: + """Every file written lands in `dest`; returns the manifests there.""" + written = _files_under(tmp_path) - before + outside = [p for p in written if not p.is_relative_to(dest)] + assert outside == [] + assert not any(p.is_relative_to(card) for p in written) + manifests = sorted(dest.glob("*_Reports*/JobReport.mhl")) + assert len(manifests) == 1, sorted(written) + return manifests + + +@pytest.mark.parametrize("name", HOSTILE_NAMES) +def test_a_job_name_never_writes_reports_outside_the_destination( + tmp_path: Path, name): + """`--name "..\\..\\X"` became `..\\..\\X_Reports`, joined onto each + destination, and the reports went two folders above it; `a:b` failed on + Windows. The engine now makes every job name one plain folder name.""" + from offloader.reports import paperwork + + base = tmp_path / "deep" / "er" + card = base / "card" + card.mkdir(parents=True) + (card / "A001_C001.mov").write_bytes(PAYLOAD) + dest = base / "dest" + before = _files_under(tmp_path) + + job = engine.run(card, _options(tmp_path, destinations=[dest], job_name=name)) + paperwork.write_reports(job, ["mhl", "csv", "html"]) + + assert job.report_failures == [] + assert job.final_status == "Verified" + manifests = _assert_reports_only_inside(tmp_path, card, dest, before) + assert manifests[0].parent.parent == dest + assert manifests[0].parent.name == f"{job.name}_Reports" + assert any(repr(name) in w and repr(job.name) in w for w in job.warnings), \ + job.warnings + + +@pytest.mark.parametrize("name", HOSTILE_NAMES) +def test_the_cli_name_never_writes_reports_outside_the_destination( + tmp_path: Path, capsys, name): + from offloader import cli + + base = tmp_path / "deep" / "er" + card = base / "card" + card.mkdir(parents=True) + (card / "A001_C001.mov").write_bytes(PAYLOAD) + dest = base / "dest" + before = _files_under(tmp_path) + + code = cli.main(["offload", "--source", str(card), "--dest", str(dest), + "--name", name, "--report", "mhl,csv,html", "--no-probe", + "--quiet", "--retries", "1"]) + + assert code == 0, capsys.readouterr().err + (manifest,) = _assert_reports_only_inside(tmp_path, card, dest, before) + assert cli.main(["verify", str(manifest), "--quiet"]) == 0 + + +def test_a_plain_job_name_is_used_as_given_without_a_warning(tmp_path: Path): + card = _card(tmp_path) + job = engine.run(card, _options(tmp_path, job_name="Shoot [Day 1]")) + assert job.name == "Shoot [Day 1]" + assert job.warnings == [] + + +def test_a_hostile_volume_label_becomes_one_folder_name(monkeypatch): + """A card offloaded from its root is named by its volume label, which is + metadata off a removable device and nobody typed.""" + monkeypatch.setattr(engine.volumes, "volume_label", + lambda path: "..\\..\\EVIL:label/x.") + root = Path(Path.cwd().anchor) + assert root.name == "" + for use_stem in (True, False): + name, warning = engine._job_name(None, root, use_stem=use_stem) + assert warning is None + assert not any(c in name for c in '\\/:'), name + assert name not in (".", "..") and not name.endswith((".", " ")) + assert Path(name).name == name \ No newline at end of file From 5255c60abca95120d58d9d3681fca0bfd02b5577 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:14:35 -0700 Subject: [PATCH 4/8] Choose the reports folder with the collision check's key choose_report_folder compared copied folder names with os.path.normcase, a no-op on POSIX and blind to Unicode composition everywhere, so a copied a001_Reports/ and a job named A001 shared one folder on APFS. It now uses _collision_key, which casefolds and NFC-normalizes on every platform. --- CHANGELOG.md | 5 +++++ docs/data-safety.md | 5 ++++- src/offloader/engine.py | 7 +++++-- tests/test_data_safety.py | 33 ++++++++++++++++++++++++++++++++- 4 files changed, 46 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01af32c..0a9b34a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,11 @@ project uses [semantic versioning][semver]. `_Reports` unsanitized, so `..\..\X` or `a/b` wrote reports elsewhere and `a:b` failed on Windows. Every job name is now sanitized by the engine, with a warning when a typed name had to change. +- **New reports could land in a copied reports folder on macOS.** The check + that keeps a job's reports out of a `_Reports` folder being copied + compared names with `normcase`, which folds case on Windows only, so a + copied `a001_Reports/` and a job named `A001` shared one folder on APFS. It + now uses the flatten collision check's casefolded, NFC-normalized key. - **A timeline offload could call a partial cut complete.** With nothing to copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/docs/data-safety.md b/docs/data-safety.md index 220b378..569878d 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -306,7 +306,10 @@ Re-offloading a previous destination (a shuttle drive holding `A001/A001_Reports/`) used to write the new reports over the copied folder, replacing files the job had just certified, the shuttle's own manifest among them. The folder choice above covers that case too, with a warning naming the -folder used. +folder used. Copied folder names are compared casefolded and NFC-normalized on +every platform, as the flatten collision check compares paths, because the +destination may be case- or normalization-insensitive: a copied `a001_Reports/` +and a job named `A001` are one folder on APFS. ## Other things that are guarded diff --git a/src/offloader/engine.py b/src/offloader/engine.py index 5a1527a..948d458 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -1949,11 +1949,14 @@ def choose_report_folder(name: str, files: Sequence[Path], source_root: Path, first = source.name else: first = source.name - claimed.add(os.path.normcase(first)) + # The collision check's key, not `normcase`, which is a no-op on + # POSIX: a copied `a001_Reports/` and a job named `A001` are one + # folder on APFS or exFAT, whatever the source volume thought. + claimed.add(_collision_key(Path(first))) base = f"{name}_Reports" candidate, number = base, 1 - while (os.path.normcase(candidate) in claimed + while (_collision_key(Path(candidate)) in claimed or any(longpath.exists(Path(root) / candidate) for root in dest_roots)): number += 1 candidate = f"{base}-{number}" diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index 1f48de4..c03616e 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -839,4 +839,35 @@ def test_a_hostile_volume_label_becomes_one_folder_name(monkeypatch): assert warning is None assert not any(c in name for c in '\\/:'), name assert name not in (".", "..") and not name.endswith((".", " ")) - assert Path(name).name == name \ No newline at end of file + assert Path(name).name == name + + +# ------------------------------------------------------- the reports folder + + +def test_the_reports_folder_skips_a_copied_folder_differing_in_composition( + tmp_path: Path): + """Chosen by `os.path.normcase`, which folds case on Windows only and + composition nowhere. `Cafe\u0301_Reports` copied off a card and a job + named `Caf\u00e9` are one folder on APFS, which normalizes, so the new + reports would land in the copied folder.""" + card = _tree(tmp_path / "card", { + "Clips/C001.mov": PAYLOAD, + "Cafe\u0301_Reports/JobReport.mhl": b"the shuttle's", + }) + job = engine.run(card, _options(tmp_path, job_name="Caf\u00e9")) + assert job.report_dir_name == "Caf\u00e9_Reports-2" + assert any("Caf\u00e9_Reports-2" in w for w in job.warnings), job.warnings + + +def test_the_reports_folder_skips_a_copied_folder_differing_in_case_on_posix( + tmp_path: Path, monkeypatch): + """On POSIX `normcase` is a no-op, so a copied `a001_Reports/` and a job + named `A001` shared one folder on APFS. Simulated here by giving + `normcase` its POSIX behaviour.""" + card = tmp_path / "card" + files = [card / "a001_Reports" / "JobReport.mhl", card / "Clips" / "C001.mov"] + monkeypatch.setattr(os.path, "normcase", lambda path: os.fspath(path)) + chosen = engine.choose_report_folder("A001", files, card, [tmp_path / "dest"], + preserve_structure=True) + assert chosen == "A001_Reports-2" \ No newline at end of file From b4236792153da64f6bd6132d300e4fc1b8810a54 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:22:40 -0700 Subject: [PATCH 5/8] Keep staging over a leftover a killed run left behind The previous commit staged a copy under the next free staging name whenever a file was already at .offloader-partial, and left that file alone. After a crash that strands a clip-sized leftover on the destination on every rerun, with nothing to clear it. No source file with the staging suffix is copied any more, so a file at a staging name is this tool's own leftover and the next copy of that file stages over it, as it always has. The one case that differs, a file an earlier version promoted under a staging name, is documented as a limit. --- CHANGELOG.md | 4 +--- docs/data-safety.md | 14 ++++++------ src/offloader/engine.py | 45 ++++++--------------------------------- tests/test_data_safety.py | 44 +++++++------------------------------- 4 files changed, 24 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a9b34a..3b206a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,9 +39,7 @@ project uses [semantic versioning][semver]. source file named `*.offloader-partial` (a leftover on a re-offloaded shuttle drive) was copied under that name, where a later file's staging copy could truncate or delete it after it was reported Verified. Such files - are no longer copied; each is named in a job warning. An existing file at a - staging name is never opened: the copy is staged under the next free - staging name and the file is left alone, with a warning. + are no longer copied; each is named in a job warning. - **A job name could put reports outside the destination.** `--name`, the app's job name and the volume label were joined onto each destination as `_Reports` unsanitized, so `..\..\X` or `a/b` wrote reports elsewhere diff --git a/docs/data-safety.md b/docs/data-safety.md index 569878d..94a76c2 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -98,12 +98,14 @@ rerun. The rule is applied in the scan, so the copy, `report` and the app's duplicate-card check all see the same file list, and to a timeline selection, by source name and by final name. -A file already sitting at a staging name is never opened or deleted either. It -may be a partial left by an interrupted run, but it may also be a file an -earlier version copied under that name and reported Verified, and nothing -distinguishes the two. The copy is staged as `.2.offloader-partial` (or -the next free number) instead, and a warning names the file that was left -alone, which can be deleted once nothing needs it. +A file already sitting at a staging name at a destination is treated as this +tool's own leftover from a run that was killed mid-copy, and the next copy of +that file stages over it, as it always has. That is what keeps a crash from +stranding dead bytes on the destination. **Limit:** a version before this rule +could copy a leftover from a source and promote it under its staging name. If +such a file is still at a destination, a later copy of the file it shadows +(`x.mov` for `x.mov.offloader-partial`, in the same folder) overwrites it, and +the earlier manifest that listed it then fails `verify` as missing. ## What "verified" actually means diff --git a/src/offloader/engine.py b/src/offloader/engine.py index 948d458..df0b163 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -1245,33 +1245,6 @@ def _warn_on_split_companions(job: Job) -> None: ) -def _staging_path(target: Path) -> tuple[Path, Path | None]: - """Where to stage `target`, and the existing file that was in the way. - - Normally `.offloader-partial`. Opening that with "wb" truncates - whatever is there, and cleanup deletes it, so an existing file at that - name is never used: it may be a partial an interrupted run left behind, - but it may also be a file an earlier version copied under that name and - reported Verified (a leftover partial on a re-offloaded shuttle drive). - Nothing here can tell which, so it is left alone and the copy is staged - as `.2.offloader-partial` or the next free number instead. Every - candidate still ends in the suffix, so it is still recognisably a staging - file. Judged by `lstat`, so a dangling link at the name is not followed. - """ - first = target.with_name(target.name + PARTIAL_SUFFIX) - candidate, number = first, 1 - while True: - try: - longpath.lstat(candidate) - except (OSError, ValueError): - # Free, or under a folder that is not there yet. Anything else - # that stops `lstat` (no permission, no such volume) stops the - # open too, which then fails the file with the real error. - return candidate, (None if candidate == first else first) - number += 1 - candidate = target.with_name(f"{target.name}.{number}{PARTIAL_SUFFIX}") - - def _discard(targets: Iterable[Path]) -> None: """Delete half-written destinations. A partial file that looks complete is worse than no file at all.""" @@ -1565,17 +1538,13 @@ def emit(event: ProgressEvent) -> None: # Write under a temporary name and only rename once the copy is proven. # An existing good file at the destination is never opened, so a failed # or interrupted attempt cannot take it down with it. - partials = [] - for target in targets: - partial, in_the_way = _staging_path(target) - partials.append(partial) - if in_the_way is not None: - job.warnings.append( - f"{in_the_way} was already at the destination and was left " - f"alone; this copy was staged as {partial.name} instead. It " - "is a leftover from an interrupted offload, or a file an " - "earlier version copied under that name, and can be " - "deleted once nothing needs it") + # A file already at the staging name is this tool's own leftover from + # a run that was killed mid-copy, and is overwritten: nothing with + # the suffix is ever copied from a source (`is_staging_name`), so no + # real file can be sitting there, and leaving leftovers in place + # would strand a card's worth of dead bytes on the destination after + # every crash. + partials = [t.with_name(t.name + PARTIAL_SUFFIX) for t in targets] bytes_at_start = counters.job_bytes_done diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index c03616e..33be2e4 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -706,48 +706,20 @@ def test_a_selection_never_copies_a_staging_file(tmp_path: Path): assert sum("not copied" in w for w in job.warnings) == 2, job.warnings -def test_a_rerun_never_truncates_a_file_already_at_a_staging_name(tmp_path: Path): - """Before staging names were refused on the card, a leftover partial was - copied and promoted under its own name, `Clips/x.mov.offloader-partial`, - and an earlier manifest lists it as verified. That is exactly where a - rerun stages `Clips/x.mov`: opening it with "wb" truncated it, and - promotion then renamed it away. Nothing can tell that file from a partial - an interrupted run left, so it is never opened, and the copy is staged - under the next free staging name instead.""" +def test_a_rerun_clears_the_staging_file_a_killed_run_left(tmp_path: Path): + """A run killed mid-copy leaves `.offloader-partial` behind. The + rerun stages over it and promotes, so the leftover is gone and nothing + with the suffix stays at the destination. This is safe only because no + source file with the suffix is ever copied, so nothing real can be there.""" card = _tree(tmp_path / "card", {"Clips/x.mov": PAYLOAD}) - dest = tmp_path / "dest" - earlier = _tree(dest, {"Clips/x.mov.offloader-partial": b"verified last time"}) - stale = earlier / "Clips" / "x.mov.offloader-partial" - before = _identity(stale) + dest = _tree(tmp_path / "dest", + {"Clips/x.mov.offloader-partial": b"half a clip"}) job = engine.run(card, _options(tmp_path)) assert job.final_status == "Verified" assert (dest / "Clips" / "x.mov").read_bytes() == PAYLOAD - assert stale.read_bytes() == b"verified last time" - assert _identity(stale) == before - assert _partials_under(dest) == [stale] - assert any("x.mov.offloader-partial" in w and "left alone" in w - for w in job.warnings), job.warnings - - -def test_a_failed_copy_staged_under_another_name_leaves_the_staging_name_alone( - tmp_path: Path, monkeypatch): - """Cleanup after a failure deletes only the staging file this run made.""" - card = _tree(tmp_path / "card", {"x.mov": PAYLOAD}) - dest = _tree(tmp_path / "dest", {"x.mov.offloader-partial": b"not ours"}) - real = engine.longpath.open_binary - - def failing(path, mode="rb"): - if "r" in mode and str(path).endswith("card" + os.sep + "x.mov"): - raise PermissionError(13, "Access is denied", str(path)) - return real(path, mode) - - monkeypatch.setattr(engine.longpath, "open_binary", failing) - job = engine.run(card, _options(tmp_path, retry=_fast())) - assert job.final_status == "Failed" - assert (dest / "x.mov.offloader-partial").read_bytes() == b"not ours" - assert _partials_under(dest) == [dest / "x.mov.offloader-partial"] + assert _partials_under(dest) == [] # ---------------------------------------------------------------- job names From 2b4852b0ca6681b23476274a5aff476c8ef9fcc7 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:26:00 -0700 Subject: [PATCH 6/8] Do not expect an empty warning list where macOS adds its own A fully verified job on a platform that cannot evict the page cache carries that warning, so the plain-job-name test checks for the absence of a job name warning instead of an empty list. --- tests/test_data_safety.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index 33be2e4..8c255cb 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -796,7 +796,10 @@ def test_a_plain_job_name_is_used_as_given_without_a_warning(tmp_path: Path): card = _card(tmp_path) job = engine.run(card, _options(tmp_path, job_name="Shoot [Day 1]")) assert job.name == "Shoot [Day 1]" - assert job.warnings == [] + # Not `== []`: a platform that cannot evict the page cache (macOS) adds + # its own warning to every fully verified job. + assert not any("job name" in warning for warning in job.warnings), \ + job.warnings def test_a_hostile_volume_label_becomes_one_folder_name(monkeypatch): From 6998aab0d9ac1cfd5a86f0ff0d122fb23fea42c7 Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:21:44 -0700 Subject: [PATCH 7/8] Fail a selected file whose name is reserved for staging instead of skipping it --- src/offloader/engine.py | 22 ++++++++++++------ tests/test_data_safety.py | 49 +++++++++++++++++++++++++++------------ 2 files changed, 49 insertions(+), 22 deletions(-) diff --git a/src/offloader/engine.py b/src/offloader/engine.py index df0b163..ed58052 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -1317,18 +1317,24 @@ def run(source_root: Path, options: OffloadOptions, #: `is_staging_name`). Reported as warnings; not card content, so they #: neither fail the job nor get a manifest entry. staging: list[Path] = [] + #: Selected files refused before any write because a name they would + #: carry is reserved for staging files. Source -> reason. + reserved: dict[Path, str] = {} if options.selection is not None: assert_selection_is_safe(options.selection, dest_roots) - selection = [] - for entry in options.selection: - # The final name too: a selector chooses it, and it is the name - # that must never carry the suffix. + selection = list(options.selection) + for entry in selection: + # The final name too: a selector chose it, and it is the name that + # must never carry the suffix. An explicit choice is never dropped + # silently: the entry stays in the job and fails at every + # destination, through the same path as a refused folder. if (is_staging_name(Path(entry.source).name) or is_staging_name(Path(entry.relative).name)): - staging.append(Path(entry.source)) - else: - selection.append(entry) + reserved[Path(entry.source)] = ( + "not copied: the name is reserved for this tool's own " + f"staging files ({PARTIAL_SUFFIX}), so nothing was written" + ) files = [Path(entry.source) for entry in selection] seen = {os.path.normcase(str(p)) for p in files} if len(seen) != len(files): @@ -1501,6 +1507,8 @@ def emit(event: ProgressEvent) -> None: # present at the destination. refusals = ([guard.refusal(target.parent) for target in targets] if guard is not None else []) + if source in reserved: + refusals = [reserved[source]] * len(targets) if any(refusals): # The whole file, not just the refused destination: the fan-out # writes every destination in one pass, and the job is a diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index 8c255cb..e8acf89 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -687,23 +687,42 @@ def test_scan_reports_staging_files_it_leaves_out(tmp_path: Path): assert staging == [card / "y.MOV.Offloader-Partial"] -def test_a_selection_never_copies_a_staging_file(tmp_path: Path): - card = _tree(tmp_path / "lib", {"x.mov": PAYLOAD, - "y.mov.offloader-partial": b"leftover", - "z.mov": b"zed"}) - dest = tmp_path / "dest" +@pytest.mark.parametrize("source_name, relative", [ + ("z.mov", "z.mov.offloader-partial"), + ("y.mov.offloader-partial", "y.mov"), + ("y.mov.offloader-partial", "y.mov.offloader-partial"), +]) +def test_a_selected_file_with_a_reserved_name_fails_instead_of_vanishing( + tmp_path: Path, source_name, relative): + """An explicitly selected file is never dropped silently. One whose source + or requested output name is a staging name fails at every destination, the + rest of the selection is copied, and the job cannot read Verified.""" + from offloader import cli + + lib = _tree(tmp_path / "lib", {"x.mov": PAYLOAD, source_name: b"zed"}) + dests = [tmp_path / "dest", tmp_path / "dest2"] selection = [ - engine.SelectedFile(card / "x.mov", Path("x.mov"), card), - engine.SelectedFile(card / "y.mov.offloader-partial", - Path("y.mov.offloader-partial"), card), - # A final name the selector chose that carries the suffix. - engine.SelectedFile(card / "z.mov", Path("z.mov.offloader-partial"), card), + engine.SelectedFile(lib / "x.mov", Path("x.mov"), lib), + engine.SelectedFile(lib / source_name, Path(relative), lib), ] - job = engine.run(card, _options(tmp_path, selection=selection)) - assert job.final_status == "Verified" - assert [entry.source.name for entry in job.files] == ["x.mov"] - assert _partials_under(dest) == [] - assert sum("not copied" in w for w in job.warnings) == 2, job.warnings + job = engine.run(lib, _options(tmp_path, selection=selection, + destinations=dests)) + + assert job.final_status not in ("Verified", "Copied") + good, refused = job.files + assert good.status is FileStatus.VERIFIED + for dest in dests: + assert (dest / "x.mov").read_bytes() == PAYLOAD + assert refused.status is FileStatus.FAILED + assert [d.status for d in refused.destinations] == [FileStatus.FAILED] * 2 + assert all("reserved" in d.error for d in refused.destinations) + for dest in dests: + assert sorted(p.name for p in dest.rglob("*") if p.is_file()) == ["x.mov"] + # Listed in the manifest like any other failed file. + rows = job.manifest_rows(0) + assert [Path(r.path).name for r in rows + if Path(r.path).name == Path(relative).name] + assert cli.exit_code(job) == cli.EXIT_FAILED def test_a_rerun_clears_the_staging_file_a_killed_run_left(tmp_path: Path): From f38f7a3c9280a7e5f1b178ad03193dbb1dbe825c Mon Sep 17 00:00:00 2001 From: owenpkent <20529132+owenpkent@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:21:44 -0700 Subject: [PATCH 8/8] Judge destination ancestors by the effective path so a dotdot sibling is accepted --- CHANGELOG.md | 8 +++++++- docs/data-safety.md | 22 ++++++++++++++------- src/offloader/engine.py | 22 ++++++++++++--------- tests/test_data_safety.py | 41 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b206a3..6e5a103 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,11 +35,17 @@ project uses [semantic versioning][semver]. Destinations are now compared with the source and with each other by identity as well as by resolved path, and every folder a copy is staged in is checked before anything is written there; a file refused this way fails. + The ancestors are taken from the effective path, so a sibling destination + spelled `card/../backup` is still accepted while the source spelled with + `..` is still refused. - **A leftover staging file could be certified and then destroyed.** A source file named `*.offloader-partial` (a leftover on a re-offloaded shuttle drive) was copied under that name, where a later file's staging copy could truncate or delete it after it was reported Verified. Such files - are no longer copied; each is named in a job warning. + are no longer copied; each one found by a scan is named in a job warning. + A timeline selection entry whose source or requested name carries the + suffix fails at every destination with a reason instead of being skipped, + so the job cannot read Verified with a chosen file missing. - **A job name could put reports outside the destination.** `--name`, the app's job name and the volume label were joined onto each destination as `_Reports` unsanitized, so `..\..\X` or `a/b` wrote reports elsewhere diff --git a/docs/data-safety.md b/docs/data-safety.md index 94a76c2..6096250 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -49,7 +49,10 @@ compared with the source, and with each other, by identity (device and file id): a destination that is the source, a destination with the source among its existing ancestors, and two destinations that are one folder are all refused. A destination that does not exist yet is judged by its nearest existing -ancestors. +ancestors. Those ancestors are taken from the effective path, with links and +`..` parts resolved, not from the spelling: `card/../backup` is the sibling +folder `backup` and is copied to, while `card/../card` and +`backup/../card/inner` still resolve into the source and are refused. A safe destination root can still hold a folder that leads back into the source: `dst/Clips` as a junction or symlink to `src/Clips`. Before anything is @@ -91,12 +94,17 @@ in `.offloader-partial` (compared case-insensitively) is never copied. It is a leftover from an interrupted offload, typically on a shuttle drive being offloaded again. It used to be copied like any other file, under a final name that a later file's staging name could equal; that file was then truncated or -deleted after being reported Verified. Each one is named in a job warning -saying it was not copied. It does not fail the job and has no manifest entry: -it is not card content, and an unhashed entry could never be answered by a -rerun. The rule is applied in the scan, so the copy, `report` and the app's -duplicate-card check all see the same file list, and to a timeline selection, -by source name and by final name. +deleted after being reported Verified. Each one found by the scan is named in +a job warning saying it was not copied. It does not fail the job and has no +manifest entry: it is not card content, and an unhashed entry could never be +answered by a rerun. The scan applies the rule, so the copy, `report` and the +app's duplicate-card check all see the same file list. + +A timeline selection is different, because every entry in it was chosen. One +whose source name or requested final name carries the suffix is never copied +and never skipped silently: it stays in the job as a file that failed at every +destination, with the reason, so the job reads Failed, the CLI exits 1, and +the manifest lists it. The rest of the selection is still copied and verified. A file already sitting at a staging name at a destination is treated as this tool's own leftover from a run that was killed mid-copy, and the next copy of diff --git a/src/offloader/engine.py b/src/offloader/engine.py index ed58052..d4a96ff 100644 --- a/src/offloader/engine.py +++ b/src/offloader/engine.py @@ -145,12 +145,13 @@ def assert_safe_destinations(source_root: Path, destinations: Sequence[Path]) -> ) seen[resolved] = Path(destination) + effective = _real_path(Path(destination)) chain = _existing_chain(Path(destination)) if source_id is not None: for position, (_, identity) in enumerate(chain): if identity != source_id: continue - if position == 0 and chain[0][0] == Path(destination).absolute(): + if position == 0 and chain[0][0] == effective: raise UnsafeDestination( f"destination {destination} is the source {source_root} " "itself under another name; copying a card onto " @@ -163,7 +164,7 @@ def assert_safe_destinations(source_root: Path, destinations: Sequence[Path]) -> ) if chain: nearest, identity = chain[0] - below = Path(destination).absolute().relative_to(nearest) + below = effective.relative_to(nearest) # Casefolded: a part that does not exist yet will be created on # the same volume as `nearest`, which may not tell case apart. # Refusing two names that differ only in case is the safe side. @@ -194,15 +195,18 @@ def _identity(path: Path) -> tuple[int, int] | None: def _existing_chain(path: Path) -> list[tuple[Path, tuple[int, int]]]: - """`path` and each of its ancestors that exists, nearest first, with - their identities. - - Lexical ancestors of the absolute path, `..` and all, so a link part-way - up is examined as itself and as whatever it points at, via `stat`. + """The effective `path` and each of its ancestors that exists, nearest + first, with their identities. + + The chain is built from `_real_path`, so links and `..` parts are already + resolved, including in a tail that does not exist yet. Walking the + lexical ancestors instead would take `card/../backup` for a path inside + `card`. Identity is compared with `stat`, so a folder reached under + another case or an alias is still recognised as itself. """ - absolute = Path(path).absolute() + effective = _real_path(path) chain: list[tuple[Path, tuple[int, int]]] = [] - for candidate in (absolute, *absolute.parents): + for candidate in (effective, *effective.parents): identity = _identity(candidate) if identity is not None: chain.append((candidate, identity)) diff --git a/tests/test_data_safety.py b/tests/test_data_safety.py index e8acf89..0d91996 100644 --- a/tests/test_data_safety.py +++ b/tests/test_data_safety.py @@ -81,6 +81,47 @@ def test_refuses_two_destinations_that_are_the_same_directory(tmp_path: Path): tmp_path, destinations=[tmp_path / "dest", tmp_path / "sub" / ".." / "dest"])) +def test_a_sibling_destination_spelled_with_dotdot_is_copied(tmp_path: Path): + """`card/../backup` is the folder `backup` beside the card, not a folder + inside it.""" + card = _card(tmp_path) + destination = card / ".." / "backup" + job = engine.run(card, _options(tmp_path, destinations=[destination])) + assert job.final_status == "Verified" + assert (tmp_path / "backup" / "A001_C001.mov").read_bytes() == PAYLOAD + assert (card / "A001_C001.mov").read_bytes() == PAYLOAD + assert not (card / "backup").exists() + + +def test_a_sibling_destination_spelled_with_dotdot_passes_the_cli( + tmp_path: Path): + from offloader import cli + + card = _card(tmp_path) + assert cli.main(["offload", "--source", str(card), "--dest", + str(card / ".." / "backup"), "--no-probe", "--quiet", + "--retries", "1"]) == 0 + assert (tmp_path / "backup" / "A001_C001.mov").read_bytes() == PAYLOAD + + +@pytest.mark.parametrize("spelling, message", [ + (("card", "..", "card"), "source"), + (("card", "sub", ".."), "source"), + (("backup", "..", "card", "inner"), "inside the source"), +]) +def test_the_source_spelled_with_dotdot_is_still_refused( + tmp_path: Path, spelling, message): + card = _card(tmp_path) + (card / "sub").mkdir() + (tmp_path / "backup").mkdir() + destination = tmp_path.joinpath(*spelling) + with pytest.raises(engine.UnsafeDestination, match=message): + engine.run(card, _options(tmp_path, destinations=[destination])) + assert (card / "A001_C001.mov").read_bytes() == PAYLOAD + assert _partials_under(card) == [] + assert not (card / "inner").exists() + + def test_copy_fanout_refuses_to_write_over_its_own_source(tmp_path: Path): """Belt and braces beneath the destination check, since this is the exact operation that loses the data."""