From ddd2b617f07a2c14549b7c4cba9667e5f317d9ee Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sat, 28 Nov 2026 22:19:19 -0700
Subject: [PATCH 01/14] Make the ASC MHL chain file append-only and warn when
it disagrees with disk
---
CHANGELOG.md | 6 +++
docs/ascmhl.md | 21 +++++++++
src/offloader/ascmhl.py | 99 ++++++++++++++++++++++++++++++++++++-----
tests/test_ascmhl.py | 97 ++++++++++++++++++++++++++++++++++++++++
4 files changed, 212 insertions(+), 11 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 21ed0d7..cb9cb32 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,12 @@ project uses [semantic versioning][semver].
### Fixed
+- **The ASC MHL chain file was rebuilt from scratch on every write.** It
+ rehashed whatever generations were on disk, so a generation that had been
+ edited or bit-rotted got a fresh, matching C4 and a deleted one silently left
+ the chain. The chain is now append-only: recorded entries are kept as they
+ were, and a generation that is missing or no longer matches, an unreadable
+ chain (left untouched) and a missing chain (rebuilt) each add a job 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/docs/ascmhl.md b/docs/ascmhl.md
index 677b570..da5cb7c 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -105,6 +105,27 @@ The chain file identifies each manifest by its C4 ID (SMPTE ST 2114): a SHA-512
digest in base58, prefixed `c4`, always 90 characters. It is also available as a
file checksum in its own right — `--hash c4`.
+The chain is **append-only**. Each generation's entry is written once, when the
+generation is, and pins that manifest's C4 ID as it stood then. Writing the next
+generation keeps every recorded entry exactly as it is and appends only the
+generations that have none. It does not rehash what is on disk and rewrite the
+record, which would hand a manifest that was edited or bit-rotted a fresh,
+matching C4 and let a deleted one vanish from the chain.
+
+Where the chain and the disk disagree, the entry is kept and the job gets a
+warning, which reaches the terminal and the reports:
+
+- a recorded generation's file is missing, or hashes to something other than
+ its recorded C4: the chain no longer matches it;
+- the chain file exists but cannot be read: it is left byte for byte as it was,
+ and the new generation is not recorded in it;
+- the chain file is missing while earlier generations exist: a new chain is
+ written for the generations present, and those earlier ones are attested only
+ from now.
+
+`offloader verify` does not read the chain file yet, so a tampered or missing
+generation is reported at write time only; verification does not check it.
+
## Verification
`offloader verify` reads ASC MHL histories as well as classic MHL:
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 12b4011..d3d7805 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -301,20 +301,95 @@ def _indent_and_write(element: ET.Element, path: Path) -> None:
path.write_bytes((declaration + body + "\n").encode("utf-8"))
-def write_chain(root: Path) -> Path:
- """Rewrite the chain file from the manifests present, C4-identifying each."""
+def _read_chain(path: Path) -> list[tuple[str, str, str]] | None:
+ """The chain's recorded (sequencenr, path, c4) entries, in file order.
+
+ None when the file does not parse into that shape. Values are kept as the
+ strings that were written, so they can be written back unchanged.
+ """
+ try:
+ root = ET.parse(path).getroot()
+ except (ET.ParseError, OSError):
+ return None
+ if root.tag != f"{{{DIRECTORY_NAMESPACE}}}ascmhldirectory":
+ return None
+ recorded: list[tuple[str, str, str]] = []
+ for node in root:
+ sequence = node.get("sequencenr")
+ name = node.find(f"{{{DIRECTORY_NAMESPACE}}}path")
+ c4 = node.find(f"{{{DIRECTORY_NAMESPACE}}}c4")
+ if (node.tag != f"{{{DIRECTORY_NAMESPACE}}}hashlist" or sequence is None
+ or name is None or not name.text or c4 is None or not c4.text):
+ return None
+ recorded.append((sequence, name.text, c4.text))
+ return recorded
+
+
+def update_chain(root: Path) -> tuple[Path, list[str]]:
+ """Append any generation the chain has not recorded, and say what is off.
+
+ The chain pins each manifest's C4 ID as it stood when it was written, so
+ it is append-only. Rebuilding it from whatever files are present now would
+ hand a manifest that was altered or bit-rotted a fresh, matching C4, and
+ let a deleted one drop out without a trace. Entries already recorded are
+ therefore kept exactly as they are, even when their file is missing or no
+ longer hashes to what was recorded; that is reported instead.
+
+ Returns the chain path and a list of human-readable warnings. A chain
+ file that exists but cannot be read is left untouched.
+ """
directory = ascmhl_dir(root)
+ target = directory / CHAIN_FILENAME
+ manifests = existing_manifests(root)
+ warnings: list[str] = []
+
+ recorded: list[tuple[str, str, str]] = []
+ if target.exists():
+ read = _read_chain(target)
+ if read is None:
+ warnings.append(
+ f"The ASC MHL chain file {target.name} could not be read, so "
+ "it was left as it is and the new generation was not recorded "
+ "in it.")
+ return target, warnings
+ recorded = read
+ elif len(manifests) > 1:
+ warnings.append(
+ f"The ASC MHL chain file {target.name} was missing and has been "
+ "rebuilt; earlier generations are attested only from now.")
+
+ present = {manifest.name: manifest for manifest in manifests}
+ known = {name for _seq, name, _c4 in recorded}
+ for sequence, name, c4 in recorded:
+ manifest = present.get(name)
+ if manifest is None:
+ warnings.append(
+ f"ASC MHL generation {sequence.zfill(4)} ({name}) is missing; "
+ "the chain no longer matches it.")
+ elif c4_of_bytes(manifest.read_bytes()) != c4:
+ warnings.append(
+ f"ASC MHL generation {sequence.zfill(4)} ({name}) has changed "
+ "since it was recorded; the chain no longer matches it.")
+
+ entries = list(recorded)
+ for manifest in manifests:
+ if manifest.name not in known:
+ sequence = int(_MANIFEST_PATTERN.match(manifest.name).group(1))
+ entries.append((str(sequence), manifest.name,
+ c4_of_bytes(manifest.read_bytes())))
+
chain = ET.Element("ascmhldirectory", {"xmlns": DIRECTORY_NAMESPACE})
+ for sequence, name, c4 in entries:
+ node = ET.SubElement(chain, "hashlist", {"sequencenr": sequence})
+ ET.SubElement(node, "path").text = name
+ ET.SubElement(node, "c4").text = c4
+ _indent_and_write(chain, target)
+ return target, warnings
- for manifest in existing_manifests(root):
- sequence = int(_MANIFEST_PATTERN.match(manifest.name).group(1))
- node = ET.SubElement(chain, "hashlist", {"sequencenr": str(sequence)})
- ET.SubElement(node, "path").text = manifest.name
- ET.SubElement(node, "c4").text = c4_of_bytes(manifest.read_bytes())
- target = directory / CHAIN_FILENAME
- _indent_and_write(chain, target)
- return target
+def write_chain(root: Path) -> Path:
+ """Update the chain file (see `update_chain`), discarding its warnings."""
+ return update_chain(root)[0]
def write_manifest(job: Job, root: Path, *, destination_index: int = 0,
@@ -411,7 +486,9 @@ def write_manifest(job: Job, root: Path, *, destination_index: int = 0,
target = ascmhl_dir(root) / manifest_filename(
next_sequence(root), root.name or "root", moment)
_indent_and_write(manifest, target)
- write_chain(root)
+ # Surfaced on the job: the chain is evidence, and a generation it no longer
+ # matches must not pass in silence.
+ job.warnings.extend(update_chain(root)[1])
return target
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 9c4d158..7cdceff 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -293,6 +293,103 @@ def test_every_chain_entry_matches_its_manifest(tmp_path: Path):
c4_of_bytes((directory / name).read_bytes())
+# ------------------------------------------- the chain is append-only
+
+
+def _chain_entries(destination: Path) -> dict[str, str]:
+ namespace = "{urn:ASC:MHL:DIRECTORY:v2.0}"
+ chain = ET.parse(destination / "ascmhl" / "ascmhl_chain.xml").getroot()
+ return {node.get("sequencenr"): node.find(f"{namespace}c4").text
+ for node in chain}
+
+
+def _write_generations(tmp_path: Path, count: int):
+ jobs = []
+ for _ in range(count):
+ job, destination = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+ jobs.append(job)
+ return jobs, destination
+
+
+def test_appending_a_generation_leaves_earlier_chain_bytes_alone(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ first = chain.read_text(encoding="utf-8")
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+
+ second = chain.read_text(encoding="utf-8")
+ entry = first.split("")[0].split("",
+ encoding="utf-8")
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+
+ entries = _chain_entries(destination)
+ assert entries["1"] == original
+ assert set(entries) == {"1", "2"}
+ assert any("0001" in w and "changed" in w for w in job.warnings)
+
+
+def test_a_deleted_generation_keeps_its_entry_and_warns(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 2)
+ original = _chain_entries(destination)["1"]
+ first = ascmhl.existing_manifests(destination)[0]
+ first.unlink()
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+
+ entries = _chain_entries(destination)
+ assert entries["1"] == original
+ assert set(entries) == {"1", "2", "3"}
+ assert any("0001" in w and "missing" in w for w in job.warnings)
+
+
+def test_an_unreadable_chain_is_left_alone_and_warns(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ chain.write_bytes(b"
Date: Sat, 28 Nov 2026 22:20:45 -0700
Subject: [PATCH 02/14] Neutralise spreadsheet formulas in CSV report cells
---
CHANGELOG.md | 5 +++
README.md | 6 ++-
docs/data-safety.md | 1 +
src/offloader/reports/csv_report.py | 25 ++++++++++++-
tests/test_reports.py | 58 +++++++++++++++++++++++++++++
5 files changed, 93 insertions(+), 2 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb9cb32..14fa25f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,11 @@ project uses [semantic versioning][semver].
### Fixed
+- **A filename could run as a formula in the CSV report.** A cell starting
+ with `=`, `+`, `-`, `@`, a tab or a carriage return (a file called
+ `=HYPERLINK(...)`, or media metadata) was evaluated when the CSV was opened
+ in a spreadsheet. Such text cells now carry a leading apostrophe; numbers and
+ the header are unchanged. The `resolve --csv` table gets the same treatment.
- **The ASC MHL chain file was rebuilt from scratch on every write.** It
rehashed whatever generations were on disk, so a generation that had been
edited or bit-rotted got a fresh, matching C4 and a deleted one silently left
diff --git a/README.md b/README.md
index aeabcdf..f325d1e 100644
--- a/README.md
+++ b/README.md
@@ -292,7 +292,11 @@ which is why it is opt-in. See
with per-file verdicts.
- **CSV**: one row per source/destination pair, with checksums, media
metadata, the slate from whichever department wrote it (camera or sound), and
- status. For spreadsheets and ingest scripts.
+ status. For spreadsheets and ingest scripts. A text cell that begins with
+ `=`, `+`, `-`, `@`, a tab or a carriage return (a filename off a card can)
+ is written with a leading apostrophe so a spreadsheet shows it as text
+ instead of running it as a formula; a script reading the CSV will see that
+ apostrophe. Numbers and the header row are unchanged.
- **MHL** — Media Hash List 1.1, paths relative to the file's own directory so
it travels with the media. Written per destination.
- **ASC MHL** — the format the ASC publishes and ARRI recommends. A numbered
diff --git a/docs/data-safety.md b/docs/data-safety.md
index d294748..bc2877e 100644
--- a/docs/data-safety.md
+++ b/docs/data-safety.md
@@ -289,6 +289,7 @@ folder used.
| Metadata that will not parse | The file still copies and verifies; only its metadata is lost, and the job carries a warning. |
| A directory symlink or junction in the source | Never entered, and each one skipped is named in a warning. Nothing under it was copied, so it fails the job like a folder that could not be listed: the CLI exits `1` and each manifest gets an unhashed entry for it. A junction pointing at its own parent cannot loop, and an alias listed before its target (`A_alias -> Z_real`) can no longer claim the real folder: the real folder is always scanned under its real name. Cloud-storage placeholder folders are reparse points too but are real folders, so only links (name-surrogate reparse points) are skipped. |
| A manifest whose digests are uppercase | Compared case-insensitively for hex formats, exactly for C4. Another tool's casing is not corruption. |
+| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab or a carriage return is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
| A filename XML or UTF-8 cannot carry | Filtered to U+FFFD in manifests and CSV, so one bad name cannot strand a delivery's paperwork. |
| A malformed chunk in a broadcast WAV | The walk advances on every step and is bounded, so a truncated file cannot hang it; the payload is capped, so a corrupt size field is not an allocation. The file still copies and verifies. |
| An `iXML` chunk carrying a doctype | Refused outright, closing billion-laughs entity expansion and XXE. No recorder writes one. See [`ixml.md`](ixml.md). |
diff --git a/src/offloader/reports/csv_report.py b/src/offloader/reports/csv_report.py
index 556fa50..619e64d 100644
--- a/src/offloader/reports/csv_report.py
+++ b/src/offloader/reports/csv_report.py
@@ -8,6 +8,25 @@
from ..models import Job
from ..util import format_file_datetime, format_size, xml_safe
+#: First characters a spreadsheet reads as the start of a formula. Tab and
+#: carriage return are here because Excel strips them before deciding.
+_FORMULA_TRIGGERS = ("=", "+", "-", "@", "\t", "\r")
+
+
+def _neutralise(value: str) -> str:
+ """Stop a spreadsheet evaluating a cell that came off a card.
+
+ A filename, path, job name or metadata value is untrusted, and a file
+ called `=HYPERLINK(...)` becomes a live formula when the CSV is opened.
+ The standard mitigation is a leading apostrophe, which spreadsheets show
+ as text. A script reading the CSV sees the apostrophe.
+
+ Only strings reach here: every column that holds a number is written as
+ an int, or as an unsigned formatted string (fps, duration, size), so no
+ legitimate value starts with a trigger character.
+ """
+ return "'" + value if value.startswith(_FORMULA_TRIGGERS) else value
+
class SafeWriter:
"""A csv.writer that cannot be killed by a filename.
@@ -16,6 +35,9 @@ class SafeWriter:
a name carrying a lone surrogate raises UnicodeEncodeError mid-row and
takes the whole report with it. Filtering here covers every column at
once, and matches what the MHL writer has always done.
+
+ It also neutralises spreadsheet formulas (see `_neutralise`), here rather
+ than per column so no row, present or future, can forget.
"""
def __init__(self, writer) -> None:
@@ -23,7 +45,8 @@ def __init__(self, writer) -> None:
def writerow(self, values) -> None:
self._writer.writerow(
- [xml_safe(v) if isinstance(v, str) else v for v in values])
+ [_neutralise(xml_safe(v)) if isinstance(v, str) else v
+ for v in values])
COLUMNS = [
"File Name",
diff --git a/tests/test_reports.py b/tests/test_reports.py
index ff88c36..49fffb8 100644
--- a/tests/test_reports.py
+++ b/tests/test_reports.py
@@ -196,6 +196,64 @@ def test_csv_has_a_row_per_destination(sample_job: Job, tmp_path: Path):
assert record["Size (bytes)"] == "258758961"
+@pytest.mark.parametrize("trigger", ["=", "+", "-", "@", chr(9), chr(13)])
+def test_csv_neutralises_formula_triggers_in_every_column(
+ trigger: str, sample_job: Job, tmp_path: Path):
+ """A card's names and metadata are untrusted; a spreadsheet would run a
+ cell that opens with a trigger character as a formula."""
+ evil = trigger + "HYPERLINK(1)"
+ entry = sample_job.files[0]
+ sample_job.name = evil
+ entry.source = entry.source.with_name(evil)
+ entry.media.camera.model = evil
+ entry.media.sound.note = evil
+ entry.destinations[0].error = evil
+ entry.destinations[0].path = entry.destinations[0].path.with_name(evil)
+
+ path = write_csv(sample_job, tmp_path / "JobReport.csv")
+ with path.open(newline="", encoding="utf-8") as handle:
+ rows = list(csv.reader(handle))
+ header = next(r for r in rows if r and r[0] == "File Name")
+ record = dict(zip(header, rows[rows.index(header) + 1], strict=True))
+
+ for column in ("File Name", "Camera", "Note", "Error"):
+ assert record[column] == "'" + evil, column
+ # A path opens with a drive or a slash, so it is not a trigger itself.
+ assert record["Destination Path"].endswith(evil)
+ # The preamble starts with "#", so it was never at risk.
+ assert rows[0] == ["# " + evil]
+
+
+def test_csv_leaves_ordinary_cells_and_numbers_alone(
+ sample_job: Job, tmp_path: Path):
+ path = write_csv(sample_job, tmp_path / "JobReport.csv")
+ rows = list(csv.reader(path.read_text(encoding="utf-8").splitlines()))
+ header = next(r for r in rows if r and r[0] == "File Name")
+ record = dict(zip(header, rows[rows.index(header) + 1], strict=True))
+
+ assert record["File Name"] == "A001_C001.mov"
+ assert record["Size (bytes)"] == "258758961"
+ assert record["FPS"] == "24.000"
+ assert record["Frames"] == "6022"
+ assert record["Timecode"] == "12:54:38:12 NDF"
+ assert not any(cell.startswith("'") for row in rows for cell in row)
+ assert rows[rows.index(header)] == header
+
+
+def test_csv_header_row_is_unchanged_and_round_trips(
+ sample_job: Job, tmp_path: Path):
+ from offloader.reports.csv_report import COLUMNS
+
+ sample_job.files[0].media.camera.lens = "=1+1"
+ path = write_csv(sample_job, tmp_path / "JobReport.csv")
+ with path.open(newline="", encoding="utf-8") as handle:
+ rows = list(csv.reader(handle))
+ assert COLUMNS in rows
+ body = rows[rows.index(COLUMNS) + 1]
+ assert len(body) == len(COLUMNS)
+ assert body[COLUMNS.index("Lens")] == "'=1+1"
+
+
# ------------------------------------------------------------------ MHL
From 006f32737616ba0171f29e953da3a581b0dc71ca Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sat, 28 Nov 2026 22:25:08 -0700
Subject: [PATCH 03/14] Say where a chain warning is shown
Job warnings reach the terminal and the app's completion dialog. The PDF,
HTML and CSV reports do not print them, so the chain section no longer says
they do.
---
docs/ascmhl.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/docs/ascmhl.md b/docs/ascmhl.md
index da5cb7c..e4a7978 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -113,7 +113,8 @@ record, which would hand a manifest that was edited or bit-rotted a fresh,
matching C4 and let a deleted one vanish from the chain.
Where the chain and the disk disagree, the entry is kept and the job gets a
-warning, which reaches the terminal and the reports:
+warning, which the terminal prints and the app shows when the job ends (the
+PDF, HTML and CSV reports do not print job warnings):
- a recorded generation's file is missing, or hashes to something other than
its recorded C4: the chain no longer matches it;
From 87aa4f7cc2d3d06587395e60875bd849a382f605 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sat, 28 Nov 2026 22:28:52 -0700
Subject: [PATCH 04/14] Check for chain warnings, not an empty warning list
macOS cannot evict the page cache and adds a warning to every fully
verified job, so two chain tests that expected no warnings at all failed
there. They now look only at warnings about the chain.
---
tests/test_ascmhl.py | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 7cdceff..5f3b787 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -312,6 +312,13 @@ def _write_generations(tmp_path: Path, count: int):
return jobs, destination
+def _chain_warnings(job) -> list[str]:
+ """The job's warnings about the chain. Not all of `job.warnings`: a
+ platform that cannot evict the page cache (macOS) adds its own warning to
+ every fully verified job."""
+ return [w for w in job.warnings if "chain" in w]
+
+
def test_appending_a_generation_leaves_earlier_chain_bytes_alone(tmp_path: Path):
_jobs, destination = _write_generations(tmp_path, 1)
chain = destination / "ascmhl" / "ascmhl_chain.xml"
@@ -324,7 +331,7 @@ def test_appending_a_generation_leaves_earlier_chain_bytes_alone(tmp_path: Path)
entry = first.split("")[0].split("
Date: Sun, 29 Nov 2026 12:14:58 -0700
Subject: [PATCH 05/14] Harden the ASC MHL chain update and extend CSV formula
neutralising
The chain is replaced atomically, sequence numbers never reuse a number the
chain records, and a generation that cannot be recorded in the chain is a
report failure (exit 5) instead of a warning. CSV cells starting with a line
feed or a full-width = + - @ are now neutralised too.
---
CHANGELOG.md | 11 ++-
docs/ascmhl.md | 18 +++-
docs/data-safety.md | 3 +-
src/offloader/ascmhl.py | 115 +++++++++++++++++++++----
src/offloader/reports/csv_report.py | 10 ++-
tests/test_ascmhl.py | 127 +++++++++++++++++++++++++++-
tests/test_reports.py | 4 +-
7 files changed, 256 insertions(+), 32 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14fa25f..cd89773 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,7 +28,8 @@ project uses [semantic versioning][semver].
### Fixed
- **A filename could run as a formula in the CSV report.** A cell starting
- with `=`, `+`, `-`, `@`, a tab or a carriage return (a file called
+ with `=`, `+`, `-`, `@`, a tab, a carriage return, a line feed or a
+ full-width `=`, `+`, `-` or `@` (a file called
`=HYPERLINK(...)`, or media metadata) was evaluated when the CSV was opened
in a spreadsheet. Such text cells now carry a leading apostrophe; numbers and
the header are unchanged. The `resolve --csv` table gets the same treatment.
@@ -36,8 +37,12 @@ project uses [semantic versioning][semver].
rehashed whatever generations were on disk, so a generation that had been
edited or bit-rotted got a fresh, matching C4 and a deleted one silently left
the chain. The chain is now append-only: recorded entries are kept as they
- were, and a generation that is missing or no longer matches, an unreadable
- chain (left untouched) and a missing chain (rebuilt) each add a job warning.
+ were, and a generation that is missing or no longer matches, or a missing
+ chain (rebuilt), adds a job warning. The chain is replaced atomically, so a
+ failed write keeps the old one. Sequence numbers never reuse a number the
+ chain records. A chain that cannot be read (left untouched) or written
+ leaves the new generation unrecorded, which is a report failure: the job
+ reads `Verified, reports failed` and the CLI exits 5.
- **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/ascmhl.md b/docs/ascmhl.md
index e4a7978..450ba5f 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -112,18 +112,32 @@ generations that have none. It does not rehash what is on disk and rewrite the
record, which would hand a manifest that was edited or bit-rotted a fresh,
matching C4 and let a deleted one vanish from the chain.
+The file is replaced atomically: the new chain is written to a temporary file
+in the `ascmhl/` folder and renamed over the old one, so a failed write (a full
+disk) leaves the existing chain exactly as it was. A new generation's sequence
+number is above both the highest manifest on disk and the highest number the
+chain records, so a number is never reused, even after a generation file is
+deleted.
+
Where the chain and the disk disagree, the entry is kept and the job gets a
warning, which the terminal prints and the app shows when the job ends (the
PDF, HTML and CSV reports do not print job warnings):
- a recorded generation's file is missing, or hashes to something other than
its recorded C4: the chain no longer matches it;
-- the chain file exists but cannot be read: it is left byte for byte as it was,
- and the new generation is not recorded in it;
+- a manifest on disk is not in the chain by name, but its number is already
+ recorded for a different file: the chain is kept as recorded and the file is
+ not added;
- the chain file is missing while earlier generations exist: a new chain is
written for the generations present, and those earlier ones are attested only
from now.
+When the new generation cannot be recorded at all, because the chain file
+exists but cannot be read (it is left byte for byte as it was) or the
+replacement could not be written, that is a report failure, not a warning: the
+generation file is still listed as written, the job reads
+`Verified, reports failed` and the CLI exits `5`.
+
`offloader verify` does not read the chain file yet, so a tampered or missing
generation is reported at write time only; verification does not check it.
diff --git a/docs/data-safety.md b/docs/data-safety.md
index bc2877e..750fbd3 100644
--- a/docs/data-safety.md
+++ b/docs/data-safety.md
@@ -289,7 +289,8 @@ folder used.
| Metadata that will not parse | The file still copies and verifies; only its metadata is lost, and the job carries a warning. |
| A directory symlink or junction in the source | Never entered, and each one skipped is named in a warning. Nothing under it was copied, so it fails the job like a folder that could not be listed: the CLI exits `1` and each manifest gets an unhashed entry for it. A junction pointing at its own parent cannot loop, and an alias listed before its target (`A_alias -> Z_real`) can no longer claim the real folder: the real folder is always scanned under its real name. Cloud-storage placeholder folders are reparse points too but are real folders, so only links (name-surrogate reparse points) are skipped. |
| A manifest whose digests are uppercase | Compared case-insensitively for hex formats, exactly for C4. Another tool's casing is not corruption. |
-| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab or a carriage return is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
+| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab, a carriage return, a line feed, or the full-width forms of `=`, `+`, `-` and `@` (U+FF1D, U+FF0B, U+FF0D, U+FF20) is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
+| An ASC MHL chain that cannot be read or written | The chain is replaced atomically, so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records. |
| A filename XML or UTF-8 cannot carry | Filtered to U+FFFD in manifests and CSV, so one bad name cannot strand a delivery's paperwork. |
| A malformed chunk in a broadcast WAV | The walk advances on every step and is bounded, so a truncated file cannot hang it; the payload is capped, so a corrupt size field is not an allocation. The file still copies and verifies. |
| An `iXML` chunk carrying a doctype | Refused outright, closing billion-laughs entity expansion and XXE. No recorder writes one. See [`ixml.md`](ixml.md). |
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index d3d7805..f5caac2 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -16,8 +16,10 @@
import datetime as _dt
import glob
+import os
import platform
import re
+import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from xml.etree import ElementTree as ET
@@ -222,12 +224,31 @@ def existing_manifests(root: Path) -> list[Path]:
return [path for _, path in sorted(found)]
+def _recorded_numbers(root: Path) -> list[int]:
+ """Every sequence number the chain records, whether or not its file is
+ still on disk. Empty when the chain is absent or cannot be read."""
+ target = ascmhl_dir(root) / CHAIN_FILENAME
+ recorded = _read_chain(target) if target.is_file() else None
+ numbers: list[int] = []
+ for sequence, _name, _c4 in recorded or []:
+ try:
+ numbers.append(int(sequence))
+ except ValueError:
+ continue
+ return numbers
+
+
def next_sequence(root: Path) -> int:
- manifests = existing_manifests(root)
- if not manifests:
- return 1
- last = _MANIFEST_PATTERN.match(manifests[-1].name)
- return int(last.group(1)) + 1
+ """One above every number in use: on disk, and recorded in the chain.
+
+ The chain outlives a deleted generation file, so counting files alone
+ would hand the number of a removed generation to the next one and leave
+ two chain entries with the same sequence.
+ """
+ used = [int(_MANIFEST_PATTERN.match(path.name).group(1))
+ for path in existing_manifests(root)]
+ used.extend(_recorded_numbers(root))
+ return max(used, default=0) + 1
def read_manifest_hashes(manifest: Path) -> dict[str, dict[str, str]]:
@@ -289,7 +310,15 @@ def _sanitise_tree(element: ET.Element) -> None:
node.attrib[key] = xml_safe(value)
-def _indent_and_write(element: ET.Element, path: Path) -> None:
+class ChainUpdateError(Exception):
+ """The new generation could not be recorded in the ASC MHL chain.
+
+ Raised when the chain file cannot be read (it is then left untouched) or
+ the replacement could not be written (the existing chain is then kept).
+ """
+
+
+def _serialise(element: ET.Element) -> bytes:
# ElementTree writes the declaration with single quotes; the reference
# implementation and the spec's examples use double. Match them, so a
# manifest can be diffed against another tool's output directly.
@@ -297,8 +326,43 @@ def _indent_and_write(element: ET.Element, path: Path) -> None:
ET.indent(element, space=" ")
declaration = '\n'
body = ET.tostring(element, encoding="unicode")
+ return (declaration + body + "\n").encode("utf-8")
+
+
+def _indent_and_write(element: ET.Element, path: Path) -> None:
+ payload = _serialise(element)
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes((declaration + body + "\n").encode("utf-8"))
+ path.write_bytes(payload)
+
+
+def _replace_atomically(element: ET.Element, path: Path) -> None:
+ """Write `element` over `path` so a failure leaves the old file as it was.
+
+ The bytes go to a temporary file in the same folder, which replaces the
+ target in one step. Its name does not match the manifest pattern.
+ """
+ temporary: str | None = None
+ try:
+ payload = _serialise(element)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ handle, temporary = tempfile.mkstemp(
+ prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
+ with os.fdopen(handle, "wb") as stream:
+ stream.write(payload)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ temporary = None
+ except OSError as exc:
+ raise ChainUpdateError(
+ f"could not write {path.name}, so the existing chain was kept "
+ f"and the new generation was not recorded in it: {exc}") from exc
+ finally:
+ if temporary is not None:
+ try:
+ os.unlink(temporary)
+ except OSError:
+ pass
def _read_chain(path: Path) -> list[tuple[str, str, str]] | None:
@@ -335,8 +399,10 @@ def update_chain(root: Path) -> tuple[Path, list[str]]:
therefore kept exactly as they are, even when their file is missing or no
longer hashes to what was recorded; that is reported instead.
- Returns the chain path and a list of human-readable warnings. A chain
- file that exists but cannot be read is left untouched.
+ Returns the chain path and a list of human-readable warnings. Raises
+ `ChainUpdateError` when the new generation could not be recorded: the
+ chain file exists but cannot be read (it is left untouched), or the
+ replacement could not be written (the existing chain is kept).
"""
directory = ascmhl_dir(root)
target = directory / CHAIN_FILENAME
@@ -347,11 +413,9 @@ def update_chain(root: Path) -> tuple[Path, list[str]]:
if target.exists():
read = _read_chain(target)
if read is None:
- warnings.append(
- f"The ASC MHL chain file {target.name} could not be read, so "
- "it was left as it is and the new generation was not recorded "
- "in it.")
- return target, warnings
+ raise ChainUpdateError(
+ f"{target.name} could not be read, so it was left as it is "
+ "and the new generation was not recorded in it")
recorded = read
elif len(manifests) > 1:
warnings.append(
@@ -372,10 +436,20 @@ def update_chain(root: Path) -> tuple[Path, list[str]]:
"since it was recorded; the chain no longer matches it.")
entries = list(recorded)
+ numbers = {sequence for sequence, _name, _c4 in recorded}
for manifest in manifests:
if manifest.name not in known:
- sequence = int(_MANIFEST_PATTERN.match(manifest.name).group(1))
- entries.append((str(sequence), manifest.name,
+ sequence = str(int(_MANIFEST_PATTERN.match(manifest.name).group(1)))
+ if sequence in numbers:
+ # Appending would put two entries under one number. Keep the
+ # chain as recorded and say so.
+ warnings.append(
+ f"ASC MHL generation {sequence.zfill(4)} ({manifest.name}) "
+ "is not in the chain, and that number is already recorded "
+ "for a different file; it was not added.")
+ continue
+ numbers.add(sequence)
+ entries.append((sequence, manifest.name,
c4_of_bytes(manifest.read_bytes())))
chain = ET.Element("ascmhldirectory", {"xmlns": DIRECTORY_NAMESPACE})
@@ -383,7 +457,7 @@ def update_chain(root: Path) -> tuple[Path, list[str]]:
node = ET.SubElement(chain, "hashlist", {"sequencenr": sequence})
ET.SubElement(node, "path").text = name
ET.SubElement(node, "c4").text = c4
- _indent_and_write(chain, target)
+ _replace_atomically(chain, target)
return target, warnings
@@ -488,7 +562,12 @@ def write_manifest(job: Job, root: Path, *, destination_index: int = 0,
_indent_and_write(manifest, target)
# Surfaced on the job: the chain is evidence, and a generation it no longer
# matches must not pass in silence.
- job.warnings.extend(update_chain(root)[1])
+ try:
+ job.warnings.extend(update_chain(root)[1])
+ except ChainUpdateError as exc:
+ # The generation file is already written and is returned as such; the
+ # missing chain entry is a report failure (exit 5), not a warning.
+ job.report_failures.append(f"ASC MHL chain for {root}: {exc}")
return target
diff --git a/src/offloader/reports/csv_report.py b/src/offloader/reports/csv_report.py
index 619e64d..73c9a11 100644
--- a/src/offloader/reports/csv_report.py
+++ b/src/offloader/reports/csv_report.py
@@ -8,9 +8,13 @@
from ..models import Job
from ..util import format_file_datetime, format_size, xml_safe
-#: First characters a spreadsheet reads as the start of a formula. Tab and
-#: carriage return are here because Excel strips them before deciding.
-_FORMULA_TRIGGERS = ("=", "+", "-", "@", "\t", "\r")
+#: First characters a spreadsheet reads as the start of a formula. Tab,
+#: carriage return and line feed are here because Excel strips them before
+#: deciding (OWASP CSV injection guidance). So are the full-width forms of
+#: `=`, `+`, `-` and `@` (U+FF1D, U+FF0B, U+FF0D, U+FF20), which some
+#: spreadsheet locales fold to the ASCII operators.
+_FORMULA_TRIGGERS = ("=", "+", "-", "@", "\t", "\r", "\n",
+ "\uFF1D", "\uFF0B", "\uFF0D", "\uFF20")
def _neutralise(value: str) -> str:
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 5f3b787..46925f6 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -365,19 +365,138 @@ def test_a_deleted_generation_keeps_its_entry_and_warns(tmp_path: Path):
assert any("0001" in w and "missing" in w for w in job.warnings)
-def test_an_unreadable_chain_is_left_alone_and_warns(tmp_path: Path):
+def test_an_unreadable_chain_is_left_alone_and_fails_the_report(tmp_path: Path):
_jobs, destination = _write_generations(tmp_path, 1)
chain = destination / "ascmhl" / "ascmhl_chain.xml"
chain.write_bytes(b" list[str]:
+ chain = ET.parse(destination / "ascmhl" / "ascmhl_chain.xml").getroot()
+ return [node.get("sequencenr") for node in chain]
+
+
+def test_a_removed_generation_file_never_hands_its_number_on(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 2)
+ ascmhl.existing_manifests(destination)[-1].unlink()
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert _sequence_list(destination) == ["1", "2", "3"]
+
+
+def test_an_unrecorded_file_reusing_a_recorded_number_is_not_appended(
+ tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 2)
+ directory = destination / "ascmhl"
+ second = ascmhl.existing_manifests(destination)[-1]
+ # Same number as the recorded second generation, different name.
+ (directory / second.name.replace("0002_", "0002_other_", 1)).write_bytes(
+ second.read_bytes())
+ chain = directory / "ascmhl_chain.xml"
+ before = chain.read_bytes()
+
+ _path, warnings = ascmhl.update_chain(destination)
+
+ assert chain.read_bytes() == before
+ assert _sequence_list(destination) == ["1", "2"]
+ assert any("0002" in w and "already recorded" in w for w in warnings)
+
+
+def _fail_replace(monkeypatch):
+ import errno
+ import os
+
+ def full(*_args, **_kwargs):
+ raise OSError(errno.ENOSPC, "No space left on device")
+
+ monkeypatch.setattr(ascmhl.os, "replace", full)
+ assert ascmhl.os is os
+
+
+def test_a_failed_chain_write_keeps_the_old_chain_and_fails_the_report(
+ tmp_path: Path, monkeypatch):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ before = chain.read_bytes()
+ before_names = sorted(p.name for p in directory.iterdir())
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ _fail_replace(monkeypatch)
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert manifest.is_file()
+ assert chain.read_bytes() == before
+ # Only the new generation was added: no temporary file is left behind.
+ assert sorted(p.name for p in directory.iterdir()) == sorted(
+ before_names + [manifest.name])
+ assert any("ASC MHL chain" in f and "No space left" in f
+ for f in job.report_failures)
+
+
+def test_a_failed_chain_write_raises_from_update_chain(
+ tmp_path: Path, monkeypatch):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ _fail_replace(monkeypatch)
+ with pytest.raises(ascmhl.ChainUpdateError):
+ ascmhl.write_chain(destination)
+
+
+def test_the_chain_is_replaced_through_a_temporary_file(
+ tmp_path: Path, monkeypatch):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ seen = []
+ real = ascmhl.os.replace
+
+ def spy(source, target):
+ seen.append((Path(source), Path(target)))
+ real(source, target)
+
+ monkeypatch.setattr(ascmhl.os, "replace", spy)
+ ascmhl.write_chain(destination)
+ (source, target), = seen
+ assert target.name == "ascmhl_chain.xml"
+ assert source.parent == target.parent
+ assert not ascmhl._MANIFEST_PATTERN.match(source.name)
+ assert not source.exists()
+
+
+def test_an_unwritable_chain_exits_with_reports_failed(tmp_path: Path):
+ card = tmp_path / "card"
+ card.mkdir()
+ (card / "C001.mov").write_bytes(b"clip bytes" * 100)
+ destination = tmp_path / "dst"
+ occupied = destination / "ascmhl" / "ascmhl_chain.xml"
+ occupied.mkdir(parents=True)
+
+ code = cli.main(["offload", "--source", str(card), "--dest",
+ str(destination), "--report", "ascmhl", "--no-probe",
+ "--quiet", "--retries", "1"])
+
+ assert code == 5
+ assert occupied.is_dir()
def test_a_missing_chain_is_rebuilt_and_warns(tmp_path: Path):
diff --git a/tests/test_reports.py b/tests/test_reports.py
index 49fffb8..c671397 100644
--- a/tests/test_reports.py
+++ b/tests/test_reports.py
@@ -196,7 +196,9 @@ def test_csv_has_a_row_per_destination(sample_job: Job, tmp_path: Path):
assert record["Size (bytes)"] == "258758961"
-@pytest.mark.parametrize("trigger", ["=", "+", "-", "@", chr(9), chr(13)])
+@pytest.mark.parametrize("trigger", [
+ "=", "+", "-", "@", chr(9), chr(13), chr(10),
+ "\uFF1D", "\uFF0B", "\uFF0D", "\uFF20"])
def test_csv_neutralises_formula_triggers_in_every_column(
trigger: str, sample_job: Job, tmp_path: Path):
"""A card's names and metadata are untrusted; a spreadsheet would run a
From 80af849d4577f030699236686f1e60a6cd4d26b2 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 12:24:00 -0700
Subject: [PATCH 06/14] Write the chain's temporary file with ordinary
permissions
A mkstemp file is owner-only, so replacing the chain with one would lock
other users of a shared volume out of it. Use a plain temporary file
beside the chain, as config.write_json does.
---
src/offloader/ascmhl.py | 23 ++++++++++-------------
1 file changed, 10 insertions(+), 13 deletions(-)
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index f5caac2..dbeaa18 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -19,7 +19,6 @@
import os
import platform
import re
-import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from xml.etree import ElementTree as ET
@@ -339,30 +338,28 @@ def _replace_atomically(element: ET.Element, path: Path) -> None:
"""Write `element` over `path` so a failure leaves the old file as it was.
The bytes go to a temporary file in the same folder, which replaces the
- target in one step. Its name does not match the manifest pattern.
+ target in one step. Its name does not match the manifest pattern, and it
+ is opened the ordinary way (as `config.write_json` does), so the chain
+ keeps the permissions any other file written here gets: a `mkstemp` file
+ is owner-only, which would lock other users of a shared volume out of it.
"""
- temporary: str | None = None
+ temporary = path.with_name(path.name + ".tmp")
try:
payload = _serialise(element)
path.parent.mkdir(parents=True, exist_ok=True)
- handle, temporary = tempfile.mkstemp(
- prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
- with os.fdopen(handle, "wb") as stream:
+ with open(temporary, "wb") as stream:
stream.write(payload)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
- temporary = None
except OSError as exc:
+ try:
+ os.unlink(temporary)
+ except OSError:
+ pass
raise ChainUpdateError(
f"could not write {path.name}, so the existing chain was kept "
f"and the new generation was not recorded in it: {exc}") from exc
- finally:
- if temporary is not None:
- try:
- os.unlink(temporary)
- except OSError:
- pass
def _read_chain(path: Path) -> list[tuple[str, str, str]] | None:
From 9ca61d535598d015f2108eeb0dacbf8c71c7e59e Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 12:52:09 -0700
Subject: [PATCH 07/14] Harden the ASC MHL chain write: exclusive temp file,
kept permissions, numeric sequence check
---
CHANGELOG.md | 8 +--
docs/ascmhl.md | 18 ++++---
docs/data-safety.md | 2 +-
src/offloader/ascmhl.py | 70 ++++++++++++++++++++------
tests/test_ascmhl.py | 106 +++++++++++++++++++++++++++++++++++++++-
5 files changed, 177 insertions(+), 27 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd89773..8cb2653 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,9 +38,11 @@ project uses [semantic versioning][semver].
edited or bit-rotted got a fresh, matching C4 and a deleted one silently left
the chain. The chain is now append-only: recorded entries are kept as they
were, and a generation that is missing or no longer matches, or a missing
- chain (rebuilt), adds a job warning. The chain is replaced atomically, so a
- failed write keeps the old one. Sequence numbers never reuse a number the
- chain records. A chain that cannot be read (left untouched) or written
+ chain (rebuilt), adds a job warning. The chain is replaced atomically through
+ a uniquely named, exclusively created temporary file (nothing that already
+ exists is opened or removed) that keeps an existing chain's permissions on
+ POSIX, so a failed write keeps the old one. Sequence numbers never reuse a
+ number the chain records, compared by value (`0002` is 2). A chain that cannot be read (left untouched) or written
leaves the new generation unrecorded, which is a report failure: the job
reads `Verified, reports failed` and the CLI exits 5.
- **A timeline offload could call a partial cut complete.** With nothing to
diff --git a/docs/ascmhl.md b/docs/ascmhl.md
index 450ba5f..9384391 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -112,12 +112,18 @@ generations that have none. It does not rehash what is on disk and rewrite the
record, which would hand a manifest that was edited or bit-rotted a fresh,
matching C4 and let a deleted one vanish from the chain.
-The file is replaced atomically: the new chain is written to a temporary file
-in the `ascmhl/` folder and renamed over the old one, so a failed write (a full
-disk) leaves the existing chain exactly as it was. A new generation's sequence
-number is above both the highest manifest on disk and the highest number the
-chain records, so a number is never reused, even after a generation file is
-deleted.
+The file is replaced atomically: the new chain is written to a uniquely named
+temporary file in the `ascmhl/` folder, created exclusively so that nothing
+already there is opened, followed or removed, and renamed over the old one. A
+failed write (a full disk) leaves the existing chain exactly as it was, and
+only a temporary file this write created is cleaned up. On POSIX an existing
+chain keeps its permission bits; a new one gets the ordinary creation mode. A
+new generation's sequence number is above both the highest manifest on disk
+and the highest number the chain records, so a number is never reused, even
+after a generation file is deleted. Numbers are compared by value, so a
+recorded `0002` blocks a file numbered 2; the recorded text is written back
+unchanged. A recorded number that is not an integer is kept as written and
+reported in a warning.
Where the chain and the disk disagree, the entry is kept and the job gets a
warning, which the terminal prints and the app shows when the job ends (the
diff --git a/docs/data-safety.md b/docs/data-safety.md
index 750fbd3..1d6d997 100644
--- a/docs/data-safety.md
+++ b/docs/data-safety.md
@@ -290,7 +290,7 @@ folder used.
| A directory symlink or junction in the source | Never entered, and each one skipped is named in a warning. Nothing under it was copied, so it fails the job like a folder that could not be listed: the CLI exits `1` and each manifest gets an unhashed entry for it. A junction pointing at its own parent cannot loop, and an alias listed before its target (`A_alias -> Z_real`) can no longer claim the real folder: the real folder is always scanned under its real name. Cloud-storage placeholder folders are reparse points too but are real folders, so only links (name-surrogate reparse points) are skipped. |
| A manifest whose digests are uppercase | Compared case-insensitively for hex formats, exactly for C4. Another tool's casing is not corruption. |
| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab, a carriage return, a line feed, or the full-width forms of `=`, `+`, `-` and `@` (U+FF1D, U+FF0B, U+FF0D, U+FF20) is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
-| An ASC MHL chain that cannot be read or written | The chain is replaced atomically, so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records. |
+| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; an existing chain keeps its permissions on POSIX), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
| A filename XML or UTF-8 cannot carry | Filtered to U+FFFD in manifests and CSV, so one bad name cannot strand a delivery's paperwork. |
| A malformed chunk in a broadcast WAV | The walk advances on every step and is bounded, so a truncated file cannot hang it; the payload is capped, so a corrupt size field is not an allocation. The file still copies and verifies. |
| An `iXML` chunk carrying a doctype | Refused outright, closing billion-laughs entity expansion and XXE. No recorder writes one. See [`ixml.md`](ixml.md). |
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index dbeaa18..5b0cb19 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -19,6 +19,8 @@
import os
import platform
import re
+import secrets
+import stat
from dataclasses import dataclass, field
from pathlib import Path
from xml.etree import ElementTree as ET
@@ -337,26 +339,51 @@ def _indent_and_write(element: ET.Element, path: Path) -> None:
def _replace_atomically(element: ET.Element, path: Path) -> None:
"""Write `element` over `path` so a failure leaves the old file as it was.
- The bytes go to a temporary file in the same folder, which replaces the
- target in one step. Its name does not match the manifest pattern, and it
- is opened the ordinary way (as `config.write_json` does), so the chain
- keeps the permissions any other file written here gets: a `mkstemp` file
- is owner-only, which would lock other users of a shared volume out of it.
+ The bytes go to a uniquely named temporary file in the same folder, which
+ replaces the target in one step. The file is created exclusively (and
+ without following a symlink), so nothing that already exists, a clip or a
+ link to one included, is ever opened, truncated or removed; only a
+ temporary file this call created is unlinked. Its name does not match the
+ manifest pattern. It is created with the ordinary mode (`mkstemp` would
+ make it owner-only, locking other users of a shared volume out), and an
+ existing chain's permission bits are carried over on POSIX.
"""
- temporary = path.with_name(path.name + ".tmp")
+ temporary: Path | None = None
try:
payload = _serialise(element)
path.parent.mkdir(parents=True, exist_ok=True)
- with open(temporary, "wb") as stream:
+ flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL
+ | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0))
+ descriptor = -1
+ for attempt in range(5):
+ candidate = path.with_name(
+ f"{path.name}.{secrets.token_hex(8)}.tmp")
+ try:
+ descriptor = os.open(candidate, flags, 0o666)
+ except FileExistsError:
+ if attempt == 4:
+ raise
+ continue
+ temporary = candidate
+ break
+ with os.fdopen(descriptor, "wb") as stream:
stream.write(payload)
stream.flush()
+ if os.name == "posix":
+ try:
+ mode = stat.S_IMODE(os.stat(path).st_mode)
+ except FileNotFoundError:
+ mode = None # new history: keep the creation mode
+ if mode is not None:
+ os.fchmod(stream.fileno(), mode)
os.fsync(stream.fileno())
os.replace(temporary, path)
except OSError as exc:
- try:
- os.unlink(temporary)
- except OSError:
- pass
+ if temporary is not None:
+ try:
+ os.unlink(temporary)
+ except OSError:
+ pass
raise ChainUpdateError(
f"could not write {path.name}, so the existing chain was kept "
f"and the new generation was not recorded in it: {exc}") from exc
@@ -433,11 +460,24 @@ def update_chain(root: Path) -> tuple[Path, list[str]]:
"since it was recorded; the chain no longer matches it.")
entries = list(recorded)
- numbers = {sequence for sequence, _name, _c4 in recorded}
+ # Numbers are compared by value, so a chain that spells 2 as "0002" still
+ # blocks a new file numbered 2. The recorded strings are written back as
+ # they were. A recorded value that is not an integer cannot be compared,
+ # so it is kept as written and reported rather than treated as free.
+ numbers: set[int] = set()
+ for sequence, name, _c4 in recorded:
+ try:
+ numbers.add(int(sequence))
+ except ValueError:
+ warnings.append(
+ f"ASC MHL chain entry for {name} has a sequence number "
+ f"({sequence!r}) that is not an integer; it was kept as "
+ "written.")
for manifest in manifests:
if manifest.name not in known:
- sequence = str(int(_MANIFEST_PATTERN.match(manifest.name).group(1)))
- if sequence in numbers:
+ number = int(_MANIFEST_PATTERN.match(manifest.name).group(1))
+ sequence = str(number)
+ if number in numbers:
# Appending would put two entries under one number. Keep the
# chain as recorded and say so.
warnings.append(
@@ -445,7 +485,7 @@ def update_chain(root: Path) -> tuple[Path, list[str]]:
"is not in the chain, and that number is already recorded "
"for a different file; it was not added.")
continue
- numbers.add(sequence)
+ numbers.add(number)
entries.append((sequence, manifest.name,
c4_of_bytes(manifest.read_bytes())))
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 46925f6..44b66f4 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -9,7 +9,9 @@
from __future__ import annotations
import datetime as _dt
+import os
import re
+import stat
from pathlib import Path
from xml.etree import ElementTree as ET
@@ -406,8 +408,9 @@ def test_a_removed_generation_file_never_hands_its_number_on(tmp_path: Path):
assert _sequence_list(destination) == ["1", "2", "3"]
+@pytest.mark.parametrize("spelling", ["2", "0002"])
def test_an_unrecorded_file_reusing_a_recorded_number_is_not_appended(
- tmp_path: Path):
+ tmp_path: Path, spelling: str):
_jobs, destination = _write_generations(tmp_path, 2)
directory = destination / "ascmhl"
second = ascmhl.existing_manifests(destination)[-1]
@@ -415,15 +418,114 @@ def test_an_unrecorded_file_reusing_a_recorded_number_is_not_appended(
(directory / second.name.replace("0002_", "0002_other_", 1)).write_bytes(
second.read_bytes())
chain = directory / "ascmhl_chain.xml"
+ if spelling != "2":
+ chain.write_bytes(chain.read_bytes().replace(
+ b'sequencenr="2"', f'sequencenr="{spelling}"'.encode()))
before = chain.read_bytes()
_path, warnings = ascmhl.update_chain(destination)
assert chain.read_bytes() == before
- assert _sequence_list(destination) == ["1", "2"]
+ assert _sequence_list(destination) == ["1", spelling]
assert any("0002" in w and "already recorded" in w for w in warnings)
+def test_a_recorded_sequence_that_is_not_an_integer_is_kept_and_reported(
+ tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 2)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ chain.write_text(chain.read_text(encoding="utf-8").replace(
+ 'sequencenr="2"', 'sequencenr="two"'), encoding="utf-8")
+
+ _path, warnings = ascmhl.update_chain(destination)
+
+ assert _sequence_list(destination) == ["1", "two"]
+ assert any("not an integer" in w and "two" in w for w in warnings)
+ assert ascmhl.next_sequence(destination) == 3
+
+
+def test_next_sequence_counts_a_zero_padded_recorded_number(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 2)
+ ascmhl.existing_manifests(destination)[-1].unlink()
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ chain.write_text(chain.read_text(encoding="utf-8").replace(
+ 'sequencenr="2"', 'sequencenr="0002"'), encoding="utf-8")
+
+ assert ascmhl.next_sequence(destination) == 3
+
+
+def _temporary_files(directory: Path) -> list[str]:
+ return sorted(p.name for p in directory.iterdir()
+ if p.name.endswith(".tmp"))
+
+
+def test_a_file_at_the_old_fixed_temporary_name_is_left_alone(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ squatter = directory / "ascmhl_chain.xml.tmp"
+ squatter.write_bytes(b"not ours")
+
+ ascmhl.update_chain(destination)
+
+ assert squatter.read_bytes() == b"not ours"
+ assert _temporary_files(directory) == ["ascmhl_chain.xml.tmp"]
+
+
+def test_a_symlink_at_the_old_temporary_name_does_not_reach_the_clip(
+ tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ clip = destination / "A001.mov"
+ clip.write_bytes(b"precious clip bytes")
+ link = directory / "ascmhl_chain.xml.tmp"
+ try:
+ link.symlink_to(clip)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks are not permitted on this machine")
+
+ ascmhl.update_chain(destination)
+
+ assert clip.read_bytes() == b"precious clip bytes"
+ assert link.is_symlink()
+
+
+def test_a_successful_update_leaves_no_temporary_file(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 2)
+ directory = destination / "ascmhl"
+ before = sorted(p.name for p in directory.iterdir())
+
+ ascmhl.update_chain(destination)
+
+ assert sorted(p.name for p in directory.iterdir()) == before
+ assert _temporary_files(directory) == []
+
+
+@pytest.mark.skipif(os.name != "posix", reason="POSIX permission bits")
+def test_replacing_the_chain_keeps_its_permission_bits(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ chain.chmod(0o640)
+ previous = os.umask(0o077)
+ try:
+ ascmhl.update_chain(destination)
+ finally:
+ os.umask(previous)
+ assert stat.S_IMODE(chain.stat().st_mode) == 0o640
+
+
+@pytest.mark.skipif(os.name != "posix", reason="POSIX permission bits")
+def test_a_new_chain_gets_the_mode_the_umask_gives(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ chain.unlink()
+ previous = os.umask(0o022)
+ try:
+ ascmhl.update_chain(destination)
+ finally:
+ os.umask(previous)
+ assert stat.S_IMODE(chain.stat().st_mode) == 0o644
+
+
def _fail_replace(monkeypatch):
import errno
import os
From 63f98265c1015d576d4a01af18483e2932338a94 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 13:25:24 -0700
Subject: [PATCH 08/14] Keep the chain's access rules and handle long paths
when replacing it
---
CHANGELOG.md | 7 ++-
docs/ascmhl.md | 10 ++++-
docs/data-safety.md | 2 +-
src/offloader/ascmhl.py | 78 ++++++++++++++++++++++++++++++----
tests/test_ascmhl.py | 94 ++++++++++++++++++++++++++++++++++++++---
5 files changed, 171 insertions(+), 20 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8cb2653..c2d4a19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,8 +40,11 @@ project uses [semantic versioning][semver].
were, and a generation that is missing or no longer matches, or a missing
chain (rebuilt), adds a job warning. The chain is replaced atomically through
a uniquely named, exclusively created temporary file (nothing that already
- exists is opened or removed) that keeps an existing chain's permissions on
- POSIX, so a failed write keeps the old one. Sequence numbers never reuse a
+ exists is opened or removed), so a failed write keeps the old one. An
+ existing chain keeps its permission bits on POSIX (applied before any content
+ is written) and its access rules on Windows (when the user may not change
+ permissions the update still goes through without them), and a chain path
+ close to the Windows limit no longer fails on its longer temporary name. Sequence numbers never reuse a
number the chain records, compared by value (`0002` is 2). A chain that cannot be read (left untouched) or written
leaves the new generation unrecorded, which is a report failure: the job
reads `Verified, reports failed` and the CLI exits 5.
diff --git a/docs/ascmhl.md b/docs/ascmhl.md
index 9384391..2c8f2ca 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -114,10 +114,16 @@ matching C4 and let a deleted one vanish from the chain.
The file is replaced atomically: the new chain is written to a uniquely named
temporary file in the `ascmhl/` folder, created exclusively so that nothing
-already there is opened, followed or removed, and renamed over the old one. A
+already there is opened, followed or removed, and moved over the old one. A
failed write (a full disk) leaves the existing chain exactly as it was, and
only a temporary file this write created is cleaned up. On POSIX an existing
-chain keeps its permission bits; a new one gets the ordinary creation mode. A
+chain's permission bits are applied to the temporary file before any content
+is written; a new one gets the ordinary creation mode. On Windows an existing
+chain is replaced with `ReplaceFileW`, which keeps the access rules set on the
+file itself (when the user may write the chain but not change its permissions,
+the update still goes through, without those rules). Long paths are handled:
+the temporary name is longer than the chain's, and it is opened through the
+extended-length form. A
new generation's sequence number is above both the highest manifest on disk
and the highest number the chain records, so a number is never reused, even
after a generation file is deleted. Numbers are compared by value, so a
diff --git a/docs/data-safety.md b/docs/data-safety.md
index 1d6d997..f631836 100644
--- a/docs/data-safety.md
+++ b/docs/data-safety.md
@@ -290,7 +290,7 @@ folder used.
| A directory symlink or junction in the source | Never entered, and each one skipped is named in a warning. Nothing under it was copied, so it fails the job like a folder that could not be listed: the CLI exits `1` and each manifest gets an unhashed entry for it. A junction pointing at its own parent cannot loop, and an alias listed before its target (`A_alias -> Z_real`) can no longer claim the real folder: the real folder is always scanned under its real name. Cloud-storage placeholder folders are reparse points too but are real folders, so only links (name-surrogate reparse points) are skipped. |
| A manifest whose digests are uppercase | Compared case-insensitively for hex formats, exactly for C4. Another tool's casing is not corruption. |
| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab, a carriage return, a line feed, or the full-width forms of `=`, `+`, `-` and `@` (U+FF1D, U+FF0B, U+FF0D, U+FF20) is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
-| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; an existing chain keeps its permissions on POSIX), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
+| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; an existing chain keeps its permission bits on POSIX, applied before any content is written, and its access rules on Windows, where an update by a user who may not change permissions still goes through without them; long paths are handled), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
| A filename XML or UTF-8 cannot carry | Filtered to U+FFFD in manifests and CSV, so one bad name cannot strand a delivery's paperwork. |
| A malformed chunk in a broadcast WAV | The walk advances on every step and is bounded, so a truncated file cannot hang it; the payload is capped, so a corrupt size field is not an allocation. The file still copies and verifies. |
| An `iXML` chunk carrying a doctype | Refused outright, closing billion-laughs entity expansion and XXE. No recorder writes one. See [`ixml.md`](ixml.md). |
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 5b0cb19..0a198e6 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -25,7 +25,7 @@
from pathlib import Path
from xml.etree import ElementTree as ET
-from . import PRODUCT_NAME, __version__
+from . import PRODUCT_NAME, __version__, longpath
from .hashers import ALGORITHMS, c4_of_bytes, get_algorithm, new_hasher
from .models import Job
from .util import xml_safe
@@ -336,6 +336,48 @@ def _indent_and_write(element: ET.Element, path: Path) -> None:
path.write_bytes(payload)
+#: `ReplaceFileW` failures after which the replacement file is the only copy of
+#: the new content (the replaced file was removed or renamed away), so the
+#: temporary file must not be cleaned up.
+_KEEP_TEMPORARY_ERRORS = (1176, 1177)
+_REPLACEFILE_IGNORE_ERRORS = 0x2 | 0x4 # MERGE_ERRORS | ACL_ERRORS
+
+
+def _replace_file_windows(temporary: Path, path: Path) -> None:
+ """Promote `temporary` over the existing `path` with `ReplaceFileW`.
+
+ Unlike a rename it keeps the replaced file's access rules, attributes and
+ creation time, so a reader granted access on the chain file itself keeps
+ it. When the user may write the file but not change its permissions the
+ first call is denied; it is then retried once, ignoring merge and ACL
+ errors, so the update still goes through (without the file's own rules).
+ """
+ import ctypes
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ function = kernel32.ReplaceFileW
+ function.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR,
+ wintypes.DWORD, wintypes.LPVOID, wintypes.LPVOID]
+ function.restype = wintypes.BOOL
+ replaced = longpath.extended(path)
+ replacement = longpath.extended(temporary)
+ for flags in (0, _REPLACEFILE_IGNORE_ERRORS):
+ if function(replaced, replacement, None, flags, None, None):
+ return
+ error = ctypes.get_last_error()
+ if error != 5 or flags: # ERROR_ACCESS_DENIED, first attempt only
+ raise ctypes.WinError(error)
+
+
+def _promote(temporary: Path, path: Path) -> None:
+ """Put the finished temporary file at `path`."""
+ if os.name == "nt" and longpath.exists(path):
+ _replace_file_windows(temporary, path)
+ else:
+ longpath.replace(temporary, path)
+
+
def _replace_atomically(element: ET.Element, path: Path) -> None:
"""Write `element` over `path` so a failure leaves the old file as it was.
@@ -345,10 +387,14 @@ def _replace_atomically(element: ET.Element, path: Path) -> None:
link to one included, is ever opened, truncated or removed; only a
temporary file this call created is unlinked. Its name does not match the
manifest pattern. It is created with the ordinary mode (`mkstemp` would
- make it owner-only, locking other users of a shared volume out), and an
- existing chain's permission bits are carried over on POSIX.
+ make it owner-only, locking other users of a shared volume out). On POSIX
+ an existing chain's permission bits are applied before the first byte is
+ written. On Windows an existing chain is replaced with `ReplaceFileW`,
+ which keeps its access rules. Every operation on the temporary file goes
+ through `longpath`, since its name is longer than the chain's.
"""
temporary: Path | None = None
+ keep_temporary = False
try:
payload = _serialise(element)
path.parent.mkdir(parents=True, exist_ok=True)
@@ -359,7 +405,7 @@ def _replace_atomically(element: ET.Element, path: Path) -> None:
candidate = path.with_name(
f"{path.name}.{secrets.token_hex(8)}.tmp")
try:
- descriptor = os.open(candidate, flags, 0o666)
+ descriptor = os.open(longpath.extended(candidate), flags, 0o666)
except FileExistsError:
if attempt == 4:
raise
@@ -367,23 +413,37 @@ def _replace_atomically(element: ET.Element, path: Path) -> None:
temporary = candidate
break
with os.fdopen(descriptor, "wb") as stream:
- stream.write(payload)
- stream.flush()
if os.name == "posix":
try:
mode = stat.S_IMODE(os.stat(path).st_mode)
except FileNotFoundError:
mode = None # new history: keep the creation mode
if mode is not None:
+ # Before any content, so a 0600 chain never exists as a
+ # copy under the default mode.
os.fchmod(stream.fileno(), mode)
+ stream.write(payload)
+ stream.flush()
os.fsync(stream.fileno())
- os.replace(temporary, path)
+ try:
+ _promote(temporary, path)
+ except OSError as exc:
+ # ReplaceFileW documents two failures (1176, 1177) after which
+ # the replaced file is gone or renamed and the temporary file
+ # holds the only copy of the new chain.
+ keep_temporary = getattr(exc, "winerror", None) in _KEEP_TEMPORARY_ERRORS
+ raise
except OSError as exc:
- if temporary is not None:
+ if temporary is not None and not keep_temporary:
try:
- os.unlink(temporary)
+ longpath.unlink(temporary)
except OSError:
pass
+ if keep_temporary:
+ raise ChainUpdateError(
+ f"could not replace {path.name}; the new chain was left at "
+ f"{temporary} and the new generation was not recorded in "
+ f"the chain: {exc}") from exc
raise ChainUpdateError(
f"could not write {path.name}, so the existing chain was kept "
f"and the new generation was not recorded in it: {exc}") from exc
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 44b66f4..68b4734 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -12,12 +12,13 @@
import os
import re
import stat
+import subprocess
from pathlib import Path
from xml.etree import ElementTree as ET
import pytest
-from offloader import ascmhl, cli, engine, verify
+from offloader import ascmhl, cli, engine, longpath, verify
from offloader.hashers import c4_of_bytes, hash_file
from offloader.models import VerificationMode
@@ -513,6 +514,27 @@ def test_replacing_the_chain_keeps_its_permission_bits(tmp_path: Path):
assert stat.S_IMODE(chain.stat().st_mode) == 0o640
+@pytest.mark.skipif(os.name != "posix", reason="POSIX permission bits")
+def test_the_chain_mode_is_applied_before_any_content_is_written(
+ tmp_path: Path, monkeypatch):
+ """A 0600 chain must never exist as a readable copy under the default
+ mode: the temporary file is still empty when fchmod runs."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ chain.chmod(0o600)
+ sizes = []
+ real = os.fchmod
+
+ def spy(fd, mode):
+ sizes.append(os.fstat(fd).st_size)
+ real(fd, mode)
+
+ monkeypatch.setattr(ascmhl.os, "fchmod", spy)
+ ascmhl.update_chain(destination)
+ assert sizes == [0]
+ assert stat.S_IMODE(chain.stat().st_mode) == 0o600
+
+
@pytest.mark.skipif(os.name != "posix", reason="POSIX permission bits")
def test_a_new_chain_gets_the_mode_the_umask_gives(tmp_path: Path):
_jobs, destination = _write_generations(tmp_path, 1)
@@ -526,15 +548,75 @@ def test_a_new_chain_gets_the_mode_the_umask_gives(tmp_path: Path):
assert stat.S_IMODE(chain.stat().st_mode) == 0o644
+def _explicit_everyone_allow(path: Path, tmp_path: Path) -> bool:
+ """Whether `path` carries a non-inherited allow ACE for Everyone (WD).
+
+ Read from the SDDL that `icacls /save` writes, so it holds in any display
+ language: `(A;;;;;WD)`, with `ID` in the flags if inherited.
+ """
+ saved = tmp_path / "acl.txt"
+ subprocess.run(["icacls", str(path), "/save", str(saved)],
+ check=True, capture_output=True)
+ text = saved.read_bytes().decode("utf-16")
+ return re.search(r"\(A;(?!\w*ID)\w*;\w+;;;WD\)", text) is not None
+
+
+@pytest.mark.skipif(os.name != "nt", reason="NTFS access rules are Windows-only")
+def test_updating_the_chain_keeps_its_file_specific_access_rules(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ granted = subprocess.run(
+ ["icacls", str(chain), "/grant", "*S-1-1-0:(R)"],
+ capture_output=True, text=True)
+ if granted.returncode != 0:
+ pytest.skip(f"icacls failed: {granted.stdout} {granted.stderr}")
+ assert _explicit_everyone_allow(chain, tmp_path)
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert not [f for f in job.report_failures if "ASC MHL chain" in f]
+ assert _explicit_everyone_allow(chain, tmp_path)
+ names = [e.find(f"{{{ascmhl.DIRECTORY_NAMESPACE}}}path").text
+ for e in ET.parse(chain).getroot()]
+ assert len(names) == 2
+
+
+@pytest.mark.skipif(os.name != "nt", reason="the Windows path limit")
+def test_a_chain_whose_temporary_name_passes_the_path_limit_is_updated(
+ tmp_path: Path):
+ """The temporary name adds 21 characters; with the chain at 241 the
+ temporary path is 262, past MAX_PATH even though the chain fits."""
+ chain_tail = len("/ascmhl/ascmhl_chain.xml")
+ wanted = 241 - chain_tail # length of the destination folder
+ deep = tmp_path
+ while wanted - len(str(deep)) > 1:
+ step = min(90, wanted - len(str(deep)) - 1)
+ deep = deep / ("d" * step)
+ destination = deep
+ assert len(str(destination / "ascmhl" / "ascmhl_chain.xml")) == 241
+ source = tmp_path / "card"
+ source.mkdir()
+ (source / "a.mov").write_bytes(b"aaaa")
+ for _ in range(2):
+ job = engine.run(source, engine.OffloadOptions(
+ destinations=[destination], algorithm="xxh64",
+ verification=VerificationMode.FULL, thumbnail_count=0,
+ extra_probe=False, job_name="deep"))
+ ascmhl.write_manifest(job, destination, when=WHEN)
+ assert not [f for f in job.report_failures if "ASC MHL chain" in f]
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ root = ET.parse(longpath.extended(chain)).getroot()
+ assert [e.get("sequencenr") for e in root] == ["1", "2"]
+
+
def _fail_replace(monkeypatch):
import errno
- import os
def full(*_args, **_kwargs):
raise OSError(errno.ENOSPC, "No space left on device")
- monkeypatch.setattr(ascmhl.os, "replace", full)
- assert ascmhl.os is os
+ monkeypatch.setattr(ascmhl, "_promote", full)
def test_a_failed_chain_write_keeps_the_old_chain_and_fails_the_report(
@@ -570,13 +652,13 @@ def test_the_chain_is_replaced_through_a_temporary_file(
tmp_path: Path, monkeypatch):
_jobs, destination = _write_generations(tmp_path, 1)
seen = []
- real = ascmhl.os.replace
+ real = ascmhl._promote
def spy(source, target):
seen.append((Path(source), Path(target)))
real(source, target)
- monkeypatch.setattr(ascmhl.os, "replace", spy)
+ monkeypatch.setattr(ascmhl, "_promote", spy)
ascmhl.write_chain(destination)
(source, target), = seen
assert target.name == "ascmhl_chain.xml"
From cfc589480fcaf2fff45962da2188df55f69ecfb6 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 13:33:09 -0700
Subject: [PATCH 09/14] Give the chain replace a backup name, and warn when its
rules are lost
ReplaceFileW without a backup name can fail part-way with no chain left at
all. With one, every failure it documents leaves the old chain under its
own name or under the backup name, from where it is put back, so the old
chain is always what is in place when the update fails.
When the rule-keeping replace is refused because the user may not change
the file's permissions, the update still goes through without them; that
is now a job warning instead of silent.
---
CHANGELOG.md | 2 +-
docs/ascmhl.md | 4 +-
docs/data-safety.md | 2 +-
src/offloader/ascmhl.py | 114 ++++++++++++++++++++++++----------------
tests/test_ascmhl.py | 80 +++++++++++++++++++++++++++-
5 files changed, 154 insertions(+), 48 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c2d4a19..7e53929 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,7 +43,7 @@ project uses [semantic versioning][semver].
exists is opened or removed), so a failed write keeps the old one. An
existing chain keeps its permission bits on POSIX (applied before any content
is written) and its access rules on Windows (when the user may not change
- permissions the update still goes through without them), and a chain path
+ permissions the update still goes through without them, with a warning), and a chain path
close to the Windows limit no longer fails on its longer temporary name. Sequence numbers never reuse a
number the chain records, compared by value (`0002` is 2). A chain that cannot be read (left untouched) or written
leaves the new generation unrecorded, which is a report failure: the job
diff --git a/docs/ascmhl.md b/docs/ascmhl.md
index 2c8f2ca..ed313de 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -121,7 +121,9 @@ chain's permission bits are applied to the temporary file before any content
is written; a new one gets the ordinary creation mode. On Windows an existing
chain is replaced with `ReplaceFileW`, which keeps the access rules set on the
file itself (when the user may write the chain but not change its permissions,
-the update still goes through, without those rules). Long paths are handled:
+the update still goes through, without those rules, and a job warning says
+so). The replace is always given a backup name, so each failure it documents
+leaves the old chain in place or puts it back. Long paths are handled:
the temporary name is longer than the chain's, and it is opened through the
extended-length form. A
new generation's sequence number is above both the highest manifest on disk
diff --git a/docs/data-safety.md b/docs/data-safety.md
index f631836..6861f8b 100644
--- a/docs/data-safety.md
+++ b/docs/data-safety.md
@@ -290,7 +290,7 @@ folder used.
| A directory symlink or junction in the source | Never entered, and each one skipped is named in a warning. Nothing under it was copied, so it fails the job like a folder that could not be listed: the CLI exits `1` and each manifest gets an unhashed entry for it. A junction pointing at its own parent cannot loop, and an alias listed before its target (`A_alias -> Z_real`) can no longer claim the real folder: the real folder is always scanned under its real name. Cloud-storage placeholder folders are reparse points too but are real folders, so only links (name-surrogate reparse points) are skipped. |
| A manifest whose digests are uppercase | Compared case-insensitively for hex formats, exactly for C4. Another tool's casing is not corruption. |
| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab, a carriage return, a line feed, or the full-width forms of `=`, `+`, `-` and `@` (U+FF1D, U+FF0B, U+FF0D, U+FF20) is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
-| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; an existing chain keeps its permission bits on POSIX, applied before any content is written, and its access rules on Windows, where an update by a user who may not change permissions still goes through without them; long paths are handled), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
+| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; an existing chain keeps its permission bits on POSIX, applied before any content is written, and its access rules on Windows, where an update by a user who may not change permissions still goes through without them and adds a job warning; long paths are handled), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
| A filename XML or UTF-8 cannot carry | Filtered to U+FFFD in manifests and CSV, so one bad name cannot strand a delivery's paperwork. |
| A malformed chunk in a broadcast WAV | The walk advances on every step and is bounded, so a truncated file cannot hang it; the payload is capped, so a corrupt size field is not an allocation. The file still copies and verifies. |
| An `iXML` chunk carrying a doctype | Refused outright, closing billion-laughs entity expansion and XXE. No recorder writes one. See [`ixml.md`](ixml.md). |
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 0a198e6..05d0721 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -336,49 +336,84 @@ def _indent_and_write(element: ET.Element, path: Path) -> None:
path.write_bytes(payload)
-#: `ReplaceFileW` failures after which the replacement file is the only copy of
-#: the new content (the replaced file was removed or renamed away), so the
-#: temporary file must not be cleaned up.
-_KEEP_TEMPORARY_ERRORS = (1176, 1177)
+_ERROR_ACCESS_DENIED = 5
+#: `ReplaceFileW` could not move the replacement into place, and the file
+#: being replaced now sits at the backup name.
+_ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177
_REPLACEFILE_IGNORE_ERRORS = 0x2 | 0x4 # MERGE_ERRORS | ACL_ERRORS
-def _replace_file_windows(temporary: Path, path: Path) -> None:
+def _replace_file_w(replaced: str, replacement: str, backup: str, flags: int) -> int:
+ """`ReplaceFileW`, returning 0 or the Win32 error code. Windows only."""
+ import ctypes
+ from ctypes import wintypes
+
+ function = ctypes.WinDLL("kernel32", use_last_error=True).ReplaceFileW
+ function.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR,
+ wintypes.DWORD, wintypes.LPVOID, wintypes.LPVOID]
+ function.restype = wintypes.BOOL
+ if function(replaced, replacement, backup, flags, None, None):
+ return 0
+ return ctypes.get_last_error() or -1
+
+
+def _replace_file_windows(temporary: Path, path: Path) -> str | None:
"""Promote `temporary` over the existing `path` with `ReplaceFileW`.
Unlike a rename it keeps the replaced file's access rules, attributes and
creation time, so a reader granted access on the chain file itself keeps
it. When the user may write the file but not change its permissions the
first call is denied; it is then retried once, ignoring merge and ACL
- errors, so the update still goes through (without the file's own rules).
+ errors, so the update still goes through, and the returned warning says
+ the file's own rules were not carried over.
+
+ A backup name is always given. Without one, a failure part-way
+ (`ERROR_UNABLE_TO_MOVE_REPLACEMENT`) leaves no chain at all; with one,
+ every documented failure leaves the old chain either under its own name
+ or under the backup name, from where it is put back here. Either way the
+ old chain is what is at `path` when this raises.
"""
import ctypes
- from ctypes import wintypes
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- function = kernel32.ReplaceFileW
- function.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR,
- wintypes.DWORD, wintypes.LPVOID, wintypes.LPVOID]
- function.restype = wintypes.BOOL
- replaced = longpath.extended(path)
- replacement = longpath.extended(temporary)
- for flags in (0, _REPLACEFILE_IGNORE_ERRORS):
- if function(replaced, replacement, None, flags, None, None):
- return
- error = ctypes.get_last_error()
- if error != 5 or flags: # ERROR_ACCESS_DENIED, first attempt only
- raise ctypes.WinError(error)
-
-
-def _promote(temporary: Path, path: Path) -> None:
- """Put the finished temporary file at `path`."""
+ backup = path.with_name(f"{path.name}.{secrets.token_hex(8)}.old")
+ names = (longpath.extended(path), longpath.extended(temporary),
+ longpath.extended(backup))
+ warning = None
+ error = _replace_file_w(*names, 0)
+ if error == _ERROR_ACCESS_DENIED:
+ error = _replace_file_w(*names, _REPLACEFILE_IGNORE_ERRORS)
+ warning = (
+ f"The access rules set on {path.name} itself could not be carried "
+ "over when it was updated (changing its permissions was denied); "
+ "it now has the rules its folder gives it.")
+ if error == _ERROR_UNABLE_TO_MOVE_REPLACEMENT_2:
+ try:
+ longpath.replace(backup, path)
+ except OSError as exc:
+ raise ChainUpdateError(
+ f"could not replace {path.name}, and the existing chain was "
+ f"left at {backup}: rename it back to {path.name}. The new "
+ f"generation was not recorded in it: {exc}") from exc
+ if error:
+ raise ctypes.WinError(error)
+ # The old chain, now that the new one is in place.
+ try:
+ longpath.unlink(backup)
+ except OSError:
+ pass
+ return warning
+
+
+def _promote(temporary: Path, path: Path) -> str | None:
+ """Put the finished temporary file at `path`. Returns a warning to pass
+ on, or None."""
if os.name == "nt" and longpath.exists(path):
- _replace_file_windows(temporary, path)
- else:
- longpath.replace(temporary, path)
+ return _replace_file_windows(temporary, path)
+ longpath.replace(temporary, path)
+ return None
-def _replace_atomically(element: ET.Element, path: Path) -> None:
+def _replace_atomically(element: ET.Element, path: Path) -> str | None:
"""Write `element` over `path` so a failure leaves the old file as it was.
The bytes go to a uniquely named temporary file in the same folder, which
@@ -392,9 +427,10 @@ def _replace_atomically(element: ET.Element, path: Path) -> None:
written. On Windows an existing chain is replaced with `ReplaceFileW`,
which keeps its access rules. Every operation on the temporary file goes
through `longpath`, since its name is longer than the chain's.
+
+ Returns a warning for the caller to pass on, or None.
"""
temporary: Path | None = None
- keep_temporary = False
try:
payload = _serialise(element)
path.parent.mkdir(parents=True, exist_ok=True)
@@ -425,25 +461,13 @@ def _replace_atomically(element: ET.Element, path: Path) -> None:
stream.write(payload)
stream.flush()
os.fsync(stream.fileno())
- try:
- _promote(temporary, path)
- except OSError as exc:
- # ReplaceFileW documents two failures (1176, 1177) after which
- # the replaced file is gone or renamed and the temporary file
- # holds the only copy of the new chain.
- keep_temporary = getattr(exc, "winerror", None) in _KEEP_TEMPORARY_ERRORS
- raise
+ return _promote(temporary, path)
except OSError as exc:
- if temporary is not None and not keep_temporary:
+ if temporary is not None:
try:
longpath.unlink(temporary)
except OSError:
pass
- if keep_temporary:
- raise ChainUpdateError(
- f"could not replace {path.name}; the new chain was left at "
- f"{temporary} and the new generation was not recorded in "
- f"the chain: {exc}") from exc
raise ChainUpdateError(
f"could not write {path.name}, so the existing chain was kept "
f"and the new generation was not recorded in it: {exc}") from exc
@@ -554,7 +578,9 @@ def update_chain(root: Path) -> tuple[Path, list[str]]:
node = ET.SubElement(chain, "hashlist", {"sequencenr": sequence})
ET.SubElement(node, "path").text = name
ET.SubElement(node, "c4").text = c4
- _replace_atomically(chain, target)
+ warning = _replace_atomically(chain, target)
+ if warning:
+ warnings.append(warning)
return target, warnings
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 68b4734..44baf7c 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -656,7 +656,7 @@ def test_the_chain_is_replaced_through_a_temporary_file(
def spy(source, target):
seen.append((Path(source), Path(target)))
- real(source, target)
+ return real(source, target)
monkeypatch.setattr(ascmhl, "_promote", spy)
ascmhl.write_chain(destination)
@@ -1111,3 +1111,81 @@ def normalise(text: str) -> str:
assert mine.name == theirs.name
assert normalise(mine.read_text(encoding="utf-8")) == \
normalise(theirs.read_text(encoding="utf-8"))
+
+
+
+# ----------------------------------------- ReplaceFileW failure handling
+
+
+def _stand_in_for_replace_file(monkeypatch, behave):
+ """Run `behave(replaced, replacement, backup, flags, real)` in place of
+ the Win32 call, so a failure it documents can be staged."""
+ real = ascmhl._replace_file_w
+ calls = []
+
+ def fake(replaced, replacement, backup, flags):
+ calls.append(flags)
+ return behave(replaced, replacement, backup, flags, real)
+
+ monkeypatch.setattr(ascmhl, "_replace_file_w", fake)
+ return calls
+
+
+@pytest.mark.skipif(os.name != "nt", reason="ReplaceFileW is Windows only")
+def test_a_chain_whose_permissions_may_not_be_changed_is_still_updated(
+ tmp_path: Path, monkeypatch):
+ """An operator who may write the chain but not change its permissions is
+ refused the rule-keeping replace. The update goes through without the
+ file's own rules, and says so."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ calls = _stand_in_for_replace_file(
+ monkeypatch,
+ lambda replaced, replacement, backup, flags, real:
+ 5 if flags == 0 else real(replaced, replacement, backup, flags))
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert calls == [0, 0x2 | 0x4]
+ directory = destination / "ascmhl"
+ assert manifest.name in (directory / "ascmhl_chain.xml").read_text("utf-8")
+ assert not job.report_failures
+ assert any("access rules" in warning for warning in job.warnings)
+ assert not [p.name for p in directory.iterdir()
+ if p.name.endswith((".tmp", ".old"))]
+
+
+@pytest.mark.skipif(os.name != "nt", reason="ReplaceFileW is Windows only")
+@pytest.mark.parametrize("error", [1175, 1176, 1177])
+def test_a_replace_that_fails_part_way_leaves_the_old_chain_in_place(
+ tmp_path: Path, monkeypatch, error):
+ """The three failures `ReplaceFileW` documents. A backup name is always
+ given, so for 1175 and 1176 both files keep their names; for 1177 the old
+ chain has been moved to the backup name and is put back."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ before = chain.read_bytes()
+ before_names = sorted(p.name for p in directory.iterdir())
+
+ def behave(replaced, replacement, backup, flags, real):
+ if error == 1177:
+ os.replace(replaced, backup)
+ return error
+
+ _stand_in_for_replace_file(monkeypatch, behave)
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert chain.read_bytes() == before
+ assert sorted(p.name for p in directory.iterdir()) == sorted(
+ before_names + [manifest.name])
+ assert any("ASC MHL chain" in failure for failure in job.report_failures)
+
+
+@pytest.mark.skipif(os.name != "nt", reason="ReplaceFileW is Windows only")
+def test_a_successful_replace_leaves_no_backup_of_the_old_chain(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 3)
+ names = sorted(p.name for p in (destination / "ascmhl").iterdir())
+ assert len(names) == 4
+ assert not [name for name in names if name.endswith((".tmp", ".old"))]
From a95695c0092f6837d86dd51379e58cde2a523091 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 13:58:33 -0700
Subject: [PATCH 10/14] Create the chain's staging file with the chain's own
permissions, and clean it up when a restore fails
---
CHANGELOG.md | 7 +-
docs/ascmhl.md | 15 ++--
docs/data-safety.md | 2 +-
src/offloader/ascmhl.py | 153 ++++++++++++++++++++++++++++------
tests/test_ascmhl.py | 177 ++++++++++++++++++++++++++++++++++++++--
5 files changed, 309 insertions(+), 45 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e53929..f87012d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,9 +40,10 @@ project uses [semantic versioning][semver].
were, and a generation that is missing or no longer matches, or a missing
chain (rebuilt), adds a job warning. The chain is replaced atomically through
a uniquely named, exclusively created temporary file (nothing that already
- exists is opened or removed), so a failed write keeps the old one. An
- existing chain keeps its permission bits on POSIX (applied before any content
- is written) and its access rules on Windows (when the user may not change
+ exists is opened or removed), so a failed write keeps the old one. The
+ temporary file is created with an existing chain's permission bits on POSIX
+ or access rules on Windows from the first open, never wider, and the chain
+ keeps them (on Windows, when the user may not change
permissions the update still goes through without them, with a warning), and a chain path
close to the Windows limit no longer fails on its longer temporary name. Sequence numbers never reuse a
number the chain records, compared by value (`0002` is 2). A chain that cannot be read (left untouched) or written
diff --git a/docs/ascmhl.md b/docs/ascmhl.md
index ed313de..32b8f4a 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -116,13 +116,14 @@ The file is replaced atomically: the new chain is written to a uniquely named
temporary file in the `ascmhl/` folder, created exclusively so that nothing
already there is opened, followed or removed, and moved over the old one. A
failed write (a full disk) leaves the existing chain exactly as it was, and
-only a temporary file this write created is cleaned up. On POSIX an existing
-chain's permission bits are applied to the temporary file before any content
-is written; a new one gets the ordinary creation mode. On Windows an existing
-chain is replaced with `ReplaceFileW`, which keeps the access rules set on the
-file itself (when the user may write the chain but not change its permissions,
-the update still goes through, without those rules, and a job warning says
-so). The replace is always given a backup name, so each failure it documents
+only a temporary file this write created is cleaned up. Over an existing
+chain the temporary file is created with that chain's permission bits (POSIX)
+or access rules (Windows) from the first open, so it is never more accessible
+than the chain it replaces; a new history's file gets the ordinary creation
+mode. On Windows the chain is then replaced with `ReplaceFileW`, which keeps
+the access rules set on the file itself (when the user may write the chain but
+not change its permissions, the update still goes through with the copy of
+the rules made when it began, and a job warning says so). The replace is always given a backup name, so each failure it documents
leaves the old chain in place or puts it back. Long paths are handled:
the temporary name is longer than the chain's, and it is opened through the
extended-length form. A
diff --git a/docs/data-safety.md b/docs/data-safety.md
index 6861f8b..fee509b 100644
--- a/docs/data-safety.md
+++ b/docs/data-safety.md
@@ -290,7 +290,7 @@ folder used.
| A directory symlink or junction in the source | Never entered, and each one skipped is named in a warning. Nothing under it was copied, so it fails the job like a folder that could not be listed: the CLI exits `1` and each manifest gets an unhashed entry for it. A junction pointing at its own parent cannot loop, and an alias listed before its target (`A_alias -> Z_real`) can no longer claim the real folder: the real folder is always scanned under its real name. Cloud-storage placeholder folders are reparse points too but are real folders, so only links (name-surrogate reparse points) are skipped. |
| A manifest whose digests are uppercase | Compared case-insensitively for hex formats, exactly for C4. Another tool's casing is not corruption. |
| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab, a carriage return, a line feed, or the full-width forms of `=`, `+`, `-` and `@` (U+FF1D, U+FF0B, U+FF0D, U+FF20) is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
-| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; an existing chain keeps its permission bits on POSIX, applied before any content is written, and its access rules on Windows, where an update by a user who may not change permissions still goes through without them and adds a job warning; long paths are handled), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
+| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; the temporary file is created with an existing chain's permission bits on POSIX or access rules on Windows from the first open, never wider, and the chain keeps its rules on Windows, where an update by a user who may not change permissions still goes through without them and adds a job warning; long paths are handled), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
| A filename XML or UTF-8 cannot carry | Filtered to U+FFFD in manifests and CSV, so one bad name cannot strand a delivery's paperwork. |
| A malformed chunk in a broadcast WAV | The walk advances on every step and is bounded, so a truncated file cannot hang it; the payload is capped, so a corrupt size field is not an allocation. The file still copies and verifies. |
| An `iXML` chunk carrying a doctype | Refused outright, closing billion-laughs entity expansion and XXE. No recorder writes one. See [`ixml.md`](ixml.md). |
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 05d0721..9fabd36 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -336,6 +336,11 @@ def _indent_and_write(element: ET.Element, path: Path) -> None:
path.write_bytes(payload)
+_SE_FILE_OBJECT = 1
+_DACL_SECURITY_INFORMATION = 4
+_GENERIC_WRITE = 0x40000000
+_CREATE_NEW = 1
+_FILE_ATTRIBUTE_NORMAL = 0x80
_ERROR_ACCESS_DENIED = 5
#: `ReplaceFileW` could not move the replacement into place, and the file
#: being replaced now sits at the backup name.
@@ -365,7 +370,8 @@ def _replace_file_windows(temporary: Path, path: Path) -> str | None:
it. When the user may write the file but not change its permissions the
first call is denied; it is then retried once, ignoring merge and ACL
errors, so the update still goes through, and the returned warning says
- the file's own rules were not carried over.
+ the replace could not merge the rules (the file still carries the copy
+ made when `_create_staging` created it).
A backup name is always given. Without one, a failure part-way
(`ERROR_UNABLE_TO_MOVE_REPLACEMENT`) leaves no chain at all; with one,
@@ -383,9 +389,10 @@ def _replace_file_windows(temporary: Path, path: Path) -> str | None:
if error == _ERROR_ACCESS_DENIED:
error = _replace_file_w(*names, _REPLACEFILE_IGNORE_ERRORS)
warning = (
- f"The access rules set on {path.name} itself could not be carried "
- "over when it was updated (changing its permissions was denied); "
- "it now has the rules its folder gives it.")
+ f"The access rules set on {path.name} itself could not be merged "
+ "by the replace when it was updated (changing its permissions was "
+ "denied); it carries the copy of those rules that was made when "
+ "the update began.")
if error == _ERROR_UNABLE_TO_MOVE_REPLACEMENT_2:
try:
longpath.replace(backup, path)
@@ -413,6 +420,107 @@ def _promote(temporary: Path, path: Path) -> str | None:
return None
+def _create_staging_windows(candidate: Path, chain: Path) -> int:
+ """Create `candidate` exclusively, holding the DACL of the existing `chain`
+ from the first open. Windows only.
+
+ The file's rules are those of the chain it will replace, not the ones its
+ folder would hand down, so it is never readable more widely than the
+ chain while it holds the chain's content. If the chain's rules cannot be
+ read this raises rather than creating an ordinary file, which is the
+ exposure this exists to close.
+ """
+ import ctypes
+ import msvcrt
+ from ctypes import wintypes
+
+ class SecurityAttributes(ctypes.Structure):
+ _fields_ = [("nLength", wintypes.DWORD),
+ ("lpSecurityDescriptor", wintypes.LPVOID),
+ ("bInheritHandle", wintypes.BOOL)]
+
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ get_security = advapi32.GetNamedSecurityInfoW
+ get_security.argtypes = [wintypes.LPCWSTR, ctypes.c_int, wintypes.DWORD,
+ wintypes.LPVOID, wintypes.LPVOID, wintypes.LPVOID,
+ wintypes.LPVOID, wintypes.LPVOID]
+ get_security.restype = wintypes.DWORD
+ create_file = kernel32.CreateFileW
+ create_file.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
+ wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD,
+ wintypes.HANDLE]
+ create_file.restype = wintypes.HANDLE
+ close_handle = kernel32.CloseHandle
+ close_handle.argtypes = [wintypes.HANDLE]
+ close_handle.restype = wintypes.BOOL
+ local_free = kernel32.LocalFree
+ local_free.argtypes = [wintypes.HLOCAL]
+ local_free.restype = wintypes.HLOCAL
+
+ dacl = ctypes.c_void_p()
+ descriptor = ctypes.c_void_p()
+ error = get_security(longpath.extended(chain), _SE_FILE_OBJECT,
+ _DACL_SECURITY_INFORMATION, None, None,
+ ctypes.byref(dacl), None, ctypes.byref(descriptor))
+ if error:
+ raise ctypes.WinError(error)
+ try:
+ attributes = SecurityAttributes(
+ ctypes.sizeof(SecurityAttributes), descriptor.value, False)
+ handle = create_file(longpath.extended(candidate), _GENERIC_WRITE, 0,
+ ctypes.byref(attributes), _CREATE_NEW,
+ _FILE_ATTRIBUTE_NORMAL, None)
+ if handle is None or handle == ctypes.c_void_p(-1).value:
+ raise ctypes.WinError(ctypes.get_last_error())
+ finally:
+ local_free(descriptor)
+ try:
+ return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY)
+ except BaseException:
+ close_handle(handle)
+ longpath.unlink(candidate)
+ raise
+
+
+def _create_staging(candidate: Path, existing_chain: Path | None) -> int:
+ """Create the staging file exclusively and return its descriptor.
+
+ With an existing chain the file starts with that chain's access rules
+ (Windows DACL) or permission bits (POSIX), so at no moment is it more
+ accessible than the chain it will replace. Without one (a new history) it
+ is an ordinary create and takes what its folder and the umask give.
+ Raises `FileExistsError` when the name is taken.
+ """
+ flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL
+ | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0))
+ if existing_chain is None:
+ return os.open(longpath.extended(candidate), flags, 0o666)
+ if os.name == "nt":
+ return _create_staging_windows(candidate, existing_chain)
+ mode = stat.S_IMODE(os.stat(existing_chain).st_mode)
+ # The chain's bits as the creation mode, so the file never has one the
+ # chain lacks; fchmod then makes them exact, as the umask may have
+ # removed some. Both happen while the file is still empty.
+ descriptor = os.open(longpath.extended(candidate), flags, mode)
+ try:
+ os.fchmod(descriptor, mode)
+ except BaseException:
+ os.close(descriptor)
+ longpath.unlink(candidate) # created here, not yet handed back
+ raise
+ return descriptor
+
+
+def _discard(temporary: Path | None) -> None:
+ """Remove the staging file this call created, if it got as far as one."""
+ if temporary is not None:
+ try:
+ longpath.unlink(temporary)
+ except OSError:
+ pass
+
+
def _replace_atomically(element: ET.Element, path: Path) -> str | None:
"""Write `element` over `path` so a failure leaves the old file as it was.
@@ -421,11 +529,13 @@ def _replace_atomically(element: ET.Element, path: Path) -> str | None:
without following a symlink), so nothing that already exists, a clip or a
link to one included, is ever opened, truncated or removed; only a
temporary file this call created is unlinked. Its name does not match the
- manifest pattern. It is created with the ordinary mode (`mkstemp` would
- make it owner-only, locking other users of a shared volume out). On POSIX
- an existing chain's permission bits are applied before the first byte is
- written. On Windows an existing chain is replaced with `ReplaceFileW`,
- which keeps its access rules. Every operation on the temporary file goes
+ manifest pattern. A new history's file is created with the ordinary mode
+ (`mkstemp` would make it owner-only, locking other users of a shared
+ volume out). Over an existing chain it is created with that chain's
+ permission bits (POSIX) or access rules (Windows) from the first open, so
+ it is never more accessible than the chain; see `_create_staging`. On
+ Windows the chain is then replaced with `ReplaceFileW`, which keeps its
+ access rules. Every operation on the temporary file goes
through `longpath`, since its name is longer than the chain's.
Returns a warning for the caller to pass on, or None.
@@ -434,14 +544,13 @@ def _replace_atomically(element: ET.Element, path: Path) -> str | None:
try:
payload = _serialise(element)
path.parent.mkdir(parents=True, exist_ok=True)
- flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL
- | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0))
+ existing = path if longpath.exists(path) else None
descriptor = -1
for attempt in range(5):
candidate = path.with_name(
f"{path.name}.{secrets.token_hex(8)}.tmp")
try:
- descriptor = os.open(longpath.extended(candidate), flags, 0o666)
+ descriptor = _create_staging(candidate, existing)
except FileExistsError:
if attempt == 4:
raise
@@ -449,25 +558,17 @@ def _replace_atomically(element: ET.Element, path: Path) -> str | None:
temporary = candidate
break
with os.fdopen(descriptor, "wb") as stream:
- if os.name == "posix":
- try:
- mode = stat.S_IMODE(os.stat(path).st_mode)
- except FileNotFoundError:
- mode = None # new history: keep the creation mode
- if mode is not None:
- # Before any content, so a 0600 chain never exists as a
- # copy under the default mode.
- os.fchmod(stream.fileno(), mode)
stream.write(payload)
stream.flush()
os.fsync(stream.fileno())
return _promote(temporary, path)
+ except ChainUpdateError:
+ # The replace failed and the old chain is where the message says; the
+ # staging file this call created is still ours to remove.
+ _discard(temporary)
+ raise
except OSError as exc:
- if temporary is not None:
- try:
- longpath.unlink(temporary)
- except OSError:
- pass
+ _discard(temporary)
raise ChainUpdateError(
f"could not write {path.name}, so the existing chain was kept "
f"and the new generation was not recorded in it: {exc}") from exc
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 44baf7c..cde1e1e 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -11,6 +11,7 @@
import datetime as _dt
import os
import re
+import secrets
import stat
import subprocess
from pathlib import Path
@@ -535,6 +536,35 @@ def spy(fd, mode):
assert stat.S_IMODE(chain.stat().st_mode) == 0o600
+@pytest.mark.skipif(os.name != "posix", reason="POSIX permission bits")
+def test_the_staging_file_is_never_wider_than_the_chain_it_replaces(
+ tmp_path: Path, monkeypatch):
+ """Created restrictive from the first open, not narrowed afterwards: with a
+ umask that removes nothing, the file's mode right after it exists must
+ hold no bit the 0640 chain lacks."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ chain.chmod(0o640)
+ recorded = []
+ real = os.open
+
+ def spy(name, flags, mode=0o777, **kwargs):
+ descriptor = real(name, flags, mode, **kwargs)
+ if str(name).endswith(".tmp"):
+ recorded.append(stat.S_IMODE(os.fstat(descriptor).st_mode))
+ return descriptor
+
+ monkeypatch.setattr(ascmhl.os, "open", spy)
+ previous = os.umask(0o000)
+ try:
+ ascmhl.update_chain(destination)
+ finally:
+ os.umask(previous)
+ assert len(recorded) == 1
+ assert recorded[0] & ~0o640 == 0
+ assert stat.S_IMODE(chain.stat().st_mode) == 0o640
+
+
@pytest.mark.skipif(os.name != "posix", reason="POSIX permission bits")
def test_a_new_chain_gets_the_mode_the_umask_gives(tmp_path: Path):
_jobs, destination = _write_generations(tmp_path, 1)
@@ -582,18 +612,113 @@ def test_updating_the_chain_keeps_its_file_specific_access_rules(tmp_path: Path)
assert len(names) == 2
+def _sddl(path: Path, scratch: Path) -> str:
+ """The SDDL of `path` as `icacls /save` writes it (UTF-16), which holds in
+ any display language."""
+ saved = scratch / f"acl-{secrets.token_hex(4)}.txt"
+ subprocess.run(["icacls", str(path), "/save", str(saved)],
+ check=True, capture_output=True)
+ return saved.read_bytes().decode("utf-16")
+
+
+@pytest.mark.skipif(os.name != "nt", reason="NTFS access rules are Windows-only")
+def test_the_staging_file_holds_the_chains_rules_not_its_folders(
+ tmp_path: Path, monkeypatch):
+ """The folder hands Everyone read down to new files; the chain is
+ protected and has no such rule. The staging file, which holds the new
+ chain's content, must not have it either, at the moment of promotion."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ scratch = tmp_path / "scratch"
+ scratch.mkdir()
+ for command in (
+ ["icacls", str(directory), "/grant", "*S-1-1-0:(OI)(R)"],
+ ["icacls", str(chain), "/inheritance:d"],
+ ["icacls", str(chain), "/remove", "*S-1-1-0"]):
+ try:
+ subprocess.run(command, check=True, capture_output=True)
+ except subprocess.CalledProcessError as exc:
+ pytest.skip(f"icacls failed: {exc.stdout!r} {exc.stderr!r}")
+ assert ";;;WD)" not in _sddl(chain, scratch)
+
+ staged = []
+ real = ascmhl._promote
+
+ def spy(temporary, path):
+ staged.append(_sddl(temporary, scratch))
+ return real(temporary, path)
+
+ monkeypatch.setattr(ascmhl, "_promote", spy)
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert not [f for f in job.report_failures if "ASC MHL chain" in f]
+ assert len(staged) == 1
+ assert ";;;WD)" not in staged[0], staged[0]
+ assert ";;;WD)" not in _sddl(chain, scratch)
+ names = [e.find(f"{{{ascmhl.DIRECTORY_NAMESPACE}}}path").text
+ for e in ET.parse(chain).getroot()]
+ assert len(names) == 2
+
+
+#: Length of `\ascmhl\ascmhl_chain.xml` after the root folder's own name.
+_CHAIN_TAIL = len("\\ascmhl\\ascmhl_chain.xml")
+
+
+def _padding_lengths(current: int, target: int) -> list[int]:
+ """Name lengths (each 1 to 99) of nested folders that take a path of
+ `current` characters to exactly `target`. A folder costs 1 + its name, so
+ a gap of exactly 1 cannot be closed: the step before it is shortened by
+ one to leave 2. Raises ValueError when no combination reaches `target`."""
+ remaining = target - current
+ if remaining < 0 or remaining == 1:
+ raise ValueError(f"cannot pad {current} characters to {target}")
+ lengths = []
+ while remaining:
+ cost = min(100, remaining)
+ if remaining - cost == 1:
+ cost -= 1
+ lengths.append(cost - 1)
+ remaining -= cost
+ return lengths
+
+
+@pytest.mark.parametrize("start", range(0, 213))
+def test_the_padding_reaches_the_target_length_exactly(start: int):
+ target = 212
+ if target - start == 1:
+ with pytest.raises(ValueError):
+ _padding_lengths(start, target)
+ return
+ lengths = _padding_lengths(start, target)
+ assert start + sum(1 + n for n in lengths) == target
+ assert all(1 <= n <= 99 for n in lengths)
+
+
+def test_padding_that_is_already_too_long_is_refused():
+ with pytest.raises(ValueError):
+ _padding_lengths(213, 212)
+
+
@pytest.mark.skipif(os.name != "nt", reason="the Windows path limit")
def test_a_chain_whose_temporary_name_passes_the_path_limit_is_updated(
tmp_path: Path):
"""The temporary name adds 21 characters; with the chain at 241 the
- temporary path is 262, past MAX_PATH even though the chain fits."""
- chain_tail = len("/ascmhl/ascmhl_chain.xml")
- wanted = 241 - chain_tail # length of the destination folder
- deep = tmp_path
- while wanted - len(str(deep)) > 1:
- step = min(90, wanted - len(str(deep)) - 1)
- deep = deep / ("d" * step)
- destination = deep
+ temporary path is 262, past MAX_PATH even though the chain fits. The
+ destination is a folder named A001 (a short, fixed generation filename)
+ and its parent is padded so the chain path is exactly 241, whatever the
+ length of pytest's temp root."""
+ parent = tmp_path
+ try:
+ lengths = _padding_lengths(
+ len(str(parent)), 241 - _CHAIN_TAIL - len("\\A001"))
+ except ValueError:
+ pytest.skip(f"the temp root ({len(str(tmp_path))} characters) cannot "
+ "be padded to a 241-character chain path")
+ for n in lengths:
+ parent = parent / ("d" * n)
+ destination = parent / "A001"
assert len(str(destination / "ascmhl" / "ascmhl_chain.xml")) == 241
source = tmp_path / "card"
source.mkdir()
@@ -1183,6 +1308,42 @@ def behave(replaced, replacement, backup, flags, real):
assert any("ASC MHL chain" in failure for failure in job.report_failures)
+@pytest.mark.skipif(os.name != "nt", reason="ReplaceFileW is Windows only")
+def test_a_failed_restore_of_the_backup_still_removes_the_staging_file(
+ tmp_path: Path, monkeypatch):
+ """ReplaceFileW fails with 1177 (the chain is at the backup name) and the
+ rename back fails too. The old chain stays at the backup name and the
+ message names it, but the complete staging copy must not be left beside
+ it."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ before = chain.read_bytes()
+
+ def behave(replaced, replacement, backup, flags, real):
+ os.replace(replaced, backup)
+ return 1177
+
+ _stand_in_for_replace_file(monkeypatch, behave)
+ real_replace = ascmhl.longpath.replace
+
+ def refuse_restore(source, target):
+ if str(source).endswith(".old"):
+ raise OSError("cannot restore")
+ real_replace(source, target)
+
+ monkeypatch.setattr(ascmhl.longpath, "replace", refuse_restore)
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ ascmhl.write_manifest(job, destination, when=WHEN)
+
+ failures = [f for f in job.report_failures if "ASC MHL chain" in f]
+ assert failures and ".old" in failures[0]
+ backups = [p for p in directory.iterdir() if p.name.endswith(".old")]
+ assert len(backups) == 1
+ assert backups[0].read_bytes() == before
+ assert [p.name for p in directory.iterdir() if p.name.endswith(".tmp")] == []
+
+
@pytest.mark.skipif(os.name != "nt", reason="ReplaceFileW is Windows only")
def test_a_successful_replace_leaves_no_backup_of_the_old_chain(tmp_path: Path):
_jobs, destination = _write_generations(tmp_path, 3)
From 8c2080c17667a944e3719b855c3da3d338f0da2d Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:23:59 -0700
Subject: [PATCH 11/14] Give the new chain the old one's owner, group and
access list on POSIX
Permission bits alone do not say who can read a file. The staging file
belonged to the updating user's group and took whatever access list its
folder hands to new files, so a chain shared through another group, or
with a list of its own, changed readers on its first update.
The staging file is now created open to its owner alone, then given the
chain's owner and group, its access list (Linux xattr, macOS ACL) and its
exact bits, all before any content. When that cannot be done the update
is refused and the old chain kept.
The data safety table and changelog now describe the Windows fallback as
the chain docs do: the chain carries the copy of its rules made when the
update began.
---
CHANGELOG.md | 11 ++-
docs/ascmhl.md | 14 ++-
docs/data-safety.md | 2 +-
src/offloader/ascmhl.py | 157 ++++++++++++++++++++++++++++---
tests/test_ascmhl.py | 198 ++++++++++++++++++++++++++++++++++++++++
5 files changed, 360 insertions(+), 22 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f87012d..9430b87 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,10 +41,13 @@ project uses [semantic versioning][semver].
chain (rebuilt), adds a job warning. The chain is replaced atomically through
a uniquely named, exclusively created temporary file (nothing that already
exists is opened or removed), so a failed write keeps the old one. The
- temporary file is created with an existing chain's permission bits on POSIX
- or access rules on Windows from the first open, never wider, and the chain
- keeps them (on Windows, when the user may not change
- permissions the update still goes through without them, with a warning), and a chain path
+ temporary file is given an existing chain's access before any content: its
+ owner, group, access list and permission bits on POSIX, its access rules on
+ Windows. It is never wider than the chain, and the chain is readable by the
+ same people afterwards; where that cannot be reproduced the old chain is
+ kept. (On Windows, when the replace may not merge the rules, the update
+ still goes through with the copy of them made when it began, with a
+ warning), and a chain path
close to the Windows limit no longer fails on its longer temporary name. Sequence numbers never reuse a
number the chain records, compared by value (`0002` is 2). A chain that cannot be read (left untouched) or written
leaves the new generation unrecorded, which is a report failure: the job
diff --git a/docs/ascmhl.md b/docs/ascmhl.md
index 32b8f4a..0ca7a0b 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -117,10 +117,16 @@ temporary file in the `ascmhl/` folder, created exclusively so that nothing
already there is opened, followed or removed, and moved over the old one. A
failed write (a full disk) leaves the existing chain exactly as it was, and
only a temporary file this write created is cleaned up. Over an existing
-chain the temporary file is created with that chain's permission bits (POSIX)
-or access rules (Windows) from the first open, so it is never more accessible
-than the chain it replaces; a new history's file gets the ordinary creation
-mode. On Windows the chain is then replaced with `ReplaceFileW`, which keeps
+chain the temporary file is given that chain's access before any content goes
+into it: its owner, group, access list and permission bits on POSIX, its access
+rules on Windows. Permission bits alone do not say who can read a file, so
+copying only those would change the chain's readers whenever the new file's
+group or its folder's defaults differ. The file is never more accessible than
+the chain it replaces, and the chain is readable by the same people afterwards.
+When that access cannot be reproduced (on POSIX, a chain owned by another
+user, whose ownership only that user or root can give a file) the update is
+refused, the old chain is kept and the job reports the failure. A new
+history's file gets the ordinary creation mode. On Windows the chain is then replaced with `ReplaceFileW`, which keeps
the access rules set on the file itself (when the user may write the chain but
not change its permissions, the update still goes through with the copy of
the rules made when it began, and a job warning says so). The replace is always given a backup name, so each failure it documents
diff --git a/docs/data-safety.md b/docs/data-safety.md
index fee509b..c893929 100644
--- a/docs/data-safety.md
+++ b/docs/data-safety.md
@@ -290,7 +290,7 @@ folder used.
| A directory symlink or junction in the source | Never entered, and each one skipped is named in a warning. Nothing under it was copied, so it fails the job like a folder that could not be listed: the CLI exits `1` and each manifest gets an unhashed entry for it. A junction pointing at its own parent cannot loop, and an alias listed before its target (`A_alias -> Z_real`) can no longer claim the real folder: the real folder is always scanned under its real name. Cloud-storage placeholder folders are reparse points too but are real folders, so only links (name-surrogate reparse points) are skipped. |
| A manifest whose digests are uppercase | Compared case-insensitively for hex formats, exactly for C4. Another tool's casing is not corruption. |
| A filename or metadata value that a spreadsheet would run as a formula | A CSV cell (job name, name, path, error, any media metadata) starting with `=`, `+`, `-`, `@`, a tab, a carriage return, a line feed, or the full-width forms of `=`, `+`, `-` and `@` (U+FF1D, U+FF0B, U+FF0D, U+FF20) is written with a leading apostrophe, so opening the report cannot execute it. A script reading the CSV sees the apostrophe. |
-| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; the temporary file is created with an existing chain's permission bits on POSIX or access rules on Windows from the first open, never wider, and the chain keeps its rules on Windows, where an update by a user who may not change permissions still goes through without them and adds a job warning; long paths are handled), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
+| An ASC MHL chain that cannot be read or written | The chain is replaced atomically through a unique, exclusively created temporary file (an existing file or symlink is never opened or removed; before any content goes into it the temporary file is given the existing chain's access: its owner, group, access list and permission bits on POSIX, its access rules on Windows; it is never open to anyone the chain is not, and the chain is readable by the same people afterwards. Where that access cannot be reproduced (on POSIX, a chain owned by someone else) the update is refused and the old chain kept. On Windows, when the replace is denied the right to merge the rules, the update still goes through carrying the copy of them made when it began, and adds a job warning; long paths are handled), so a failed write keeps the old chain, and an unreadable chain is left untouched. The new generation then has no chain entry, which is a report failure: the job reads `Verified, reports failed` and the CLI exits `5`. Sequence numbers never reuse one the chain records, compared by value. |
| A filename XML or UTF-8 cannot carry | Filtered to U+FFFD in manifests and CSV, so one bad name cannot strand a delivery's paperwork. |
| A malformed chunk in a broadcast WAV | The walk advances on every step and is bounded, so a truncated file cannot hang it; the payload is capped, so a corrupt size field is not an allocation. The file still copies and verifies. |
| An `iXML` chunk carrying a doctype | Refused outright, closing billion-laughs entity expansion and XXE. No recorder writes one. See [`ixml.md`](ixml.md). |
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 9fabd36..24a03b5 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -15,12 +15,14 @@
from __future__ import annotations
import datetime as _dt
+import errno
import glob
import os
import platform
import re
import secrets
import stat
+import sys
from dataclasses import dataclass, field
from pathlib import Path
from xml.etree import ElementTree as ET
@@ -486,11 +488,16 @@ class SecurityAttributes(ctypes.Structure):
def _create_staging(candidate: Path, existing_chain: Path | None) -> int:
"""Create the staging file exclusively and return its descriptor.
- With an existing chain the file starts with that chain's access rules
- (Windows DACL) or permission bits (POSIX), so at no moment is it more
- accessible than the chain it will replace. Without one (a new history) it
- is an ordinary create and takes what its folder and the umask give.
- Raises `FileExistsError` when the name is taken.
+ With an existing chain the file is given that chain's access before any
+ content goes into it: its DACL on Windows; its owner, group, access list
+ and permission bits on POSIX. At no moment is it open to anyone the chain
+ is not, and the chain that replaces the old one is readable by the same
+ people. Without an existing chain (a new history) it is an ordinary
+ create and takes what its folder and the umask give.
+
+ Raises `FileExistsError` when the name is taken, and `OSError` when the
+ chain's access cannot be reproduced, in which case nothing is written and
+ the existing chain stays as it is.
"""
flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL
| getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0))
@@ -498,12 +505,51 @@ def _create_staging(candidate: Path, existing_chain: Path | None) -> int:
return os.open(longpath.extended(candidate), flags, 0o666)
if os.name == "nt":
return _create_staging_windows(candidate, existing_chain)
- mode = stat.S_IMODE(os.stat(existing_chain).st_mode)
- # The chain's bits as the creation mode, so the file never has one the
- # chain lacks; fchmod then makes them exact, as the umask may have
- # removed some. Both happen while the file is still empty.
- descriptor = os.open(longpath.extended(candidate), flags, mode)
+ return _create_staging_posix(candidate, existing_chain, flags)
+
+
+def _create_staging_posix(candidate: Path, chain: Path, flags: int) -> int:
+ """Create `candidate` and make it the existing `chain`'s twin in access.
+
+ Permission bits alone do not say who can read a file. A file created
+ here belongs to this user and this user's group (or the folder's, under
+ setgid), and takes whatever access list the folder hands to new files;
+ the chain it replaces may have another owner, another group and a list
+ of its own. Copying the bits and renaming would then quietly change who
+ can read the chain: `0640` means something else once the group has.
+
+ So the file is created open to its owner alone (the owner half of the
+ chain's bits, which no folder default can widen), then given the chain's
+ owner and group, then its access list, then its exact bits, all while it
+ is empty. If any of that is refused the file is removed and the error
+ raised: the old chain is kept rather than replaced by one with different
+ readers.
+ """
+ recorded = os.stat(chain)
+ mode = stat.S_IMODE(recorded.st_mode)
+ descriptor = os.open(longpath.extended(candidate), flags, mode & 0o700)
try:
+ created = os.fstat(descriptor)
+ owner = recorded.st_uid if recorded.st_uid != created.st_uid else -1
+ group = recorded.st_gid if recorded.st_gid != created.st_gid else -1
+ if owner != -1 or group != -1:
+ try:
+ os.fchown(descriptor, owner, group)
+ except OSError as exc:
+ raise OSError(
+ exc.errno,
+ "could not give the new chain the owner and group of the "
+ f"existing one ({recorded.st_uid}:{recorded.st_gid}): "
+ f"{exc.strerror}") from exc
+ try:
+ _copy_access_list(chain, descriptor)
+ except OSError as exc:
+ raise OSError(
+ exc.errno,
+ "could not give the new chain the access list of the "
+ f"existing one: {exc.strerror}") from exc
+ # Last, and exact: the umask took bits off at creation, and on Linux
+ # the group bits are the mask of the list just set.
os.fchmod(descriptor, mode)
except BaseException:
os.close(descriptor)
@@ -512,6 +558,89 @@ def _create_staging(candidate: Path, existing_chain: Path | None) -> int:
return descriptor
+#: Where Linux keeps a file's POSIX access list.
+_ACL_XATTR = "system.posix_acl_access"
+#: "This file has none" and "this volume keeps none", for an access list.
+_NO_ACCESS_LIST = {code for code in (
+ getattr(errno, "ENODATA", None), getattr(errno, "ENOATTR", None),
+ getattr(errno, "ENOTSUP", None), getattr(errno, "EOPNOTSUPP", None))
+ if code is not None}
+
+
+def _copy_access_list(chain: Path, descriptor: int) -> None:
+ """Make the open file's access list the same as `chain`'s: copied when
+ the chain has one, removed when the chain has none and the folder gave
+ the new file one. A volume that keeps no access lists has nothing to do.
+ """
+ if hasattr(os, "getxattr"):
+ _copy_access_list_linux(chain, descriptor)
+ elif sys.platform == "darwin":
+ _copy_access_list_macos(chain, descriptor)
+
+
+def _copy_access_list_linux(chain: Path, descriptor: int) -> None:
+ try:
+ recorded = os.getxattr(chain, _ACL_XATTR)
+ except OSError as exc:
+ if exc.errno not in _NO_ACCESS_LIST:
+ raise
+ recorded = None
+ if recorded is not None:
+ os.setxattr(descriptor, _ACL_XATTR, recorded)
+ return
+ try:
+ os.removexattr(descriptor, _ACL_XATTR)
+ except OSError as exc:
+ if exc.errno not in _NO_ACCESS_LIST:
+ raise
+
+
+def _copy_access_list_macos(chain: Path, descriptor: int) -> None:
+ import ctypes
+
+ extended = 0x100 # ACL_TYPE_EXTENDED, the only kind macOS has
+ try:
+ libc = ctypes.CDLL(None, use_errno=True)
+ get_file, get_fd = libc.acl_get_file, libc.acl_get_fd_np
+ set_fd, new, free = libc.acl_set_fd_np, libc.acl_init, libc.acl_free
+ except (OSError, AttributeError):
+ return
+ get_file.restype = get_fd.restype = new.restype = ctypes.c_void_p
+ get_file.argtypes = [ctypes.c_char_p, ctypes.c_int]
+ get_fd.argtypes = [ctypes.c_int, ctypes.c_int]
+ set_fd.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
+ set_fd.restype = ctypes.c_int
+ new.argtypes = [ctypes.c_int]
+ free.argtypes = [ctypes.c_void_p]
+ free.restype = ctypes.c_int
+
+ ctypes.set_errno(0)
+ recorded = get_file(os.fsencode(chain), extended)
+ if not recorded:
+ code = ctypes.get_errno()
+ if code not in (0, errno.ENOENT) and code not in _NO_ACCESS_LIST \
+ and code != errno.EINVAL:
+ raise OSError(code, os.strerror(code))
+ if code not in (0, errno.ENOENT):
+ return # the volume keeps no access lists
+ inherited = get_fd(descriptor, extended)
+ empty = None
+ try:
+ if not recorded and not inherited:
+ return # none on either: nothing to do
+ wanted = recorded
+ if not wanted:
+ # An empty list is how one is removed (what `chmod -N` does).
+ wanted = empty = new(0)
+ if set_fd(descriptor, wanted, extended) != 0:
+ code = ctypes.get_errno()
+ raise OSError(code, os.strerror(code))
+ finally:
+ for acl in (recorded, inherited, empty):
+ if acl:
+ free(acl)
+
+
def _discard(temporary: Path | None) -> None:
"""Remove the staging file this call created, if it got as far as one."""
if temporary is not None:
@@ -531,9 +660,11 @@ def _replace_atomically(element: ET.Element, path: Path) -> str | None:
temporary file this call created is unlinked. Its name does not match the
manifest pattern. A new history's file is created with the ordinary mode
(`mkstemp` would make it owner-only, locking other users of a shared
- volume out). Over an existing chain it is created with that chain's
- permission bits (POSIX) or access rules (Windows) from the first open, so
- it is never more accessible than the chain; see `_create_staging`. On
+ volume out). Over an existing chain it is given that chain's access
+ before any content: its owner, group, access list and permission bits
+ (POSIX) or its access rules (Windows). It is never more accessible than
+ the chain, and the chain is readable by the same people afterwards; when
+ that cannot be done the old chain is kept. See `_create_staging`. On
Windows the chain is then replaced with `ReplaceFileW`, which keeps its
access rules. Every operation on the temporary file goes
through `longpath`, since its name is longer than the chain's.
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index cde1e1e..94012d1 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -1350,3 +1350,201 @@ def test_a_successful_replace_leaves_no_backup_of_the_old_chain(tmp_path: Path):
names = sorted(p.name for p in (destination / "ascmhl").iterdir())
assert len(names) == 4
assert not [name for name in names if name.endswith((".tmp", ".old"))]
+
+
+# ------------------------- who can read the chain, beyond its mode bits
+
+
+def _another_group() -> int:
+ """A group this user belongs to that is not the one new files get."""
+ mine = os.getegid()
+ others = [gid for gid in os.getgroups() if gid != mine]
+ if not others:
+ pytest.skip("this user is in one group only")
+ return others[0]
+
+
+@pytest.mark.skipif(os.name != "posix", reason="POSIX ownership")
+def test_replacing_the_chain_keeps_its_group(tmp_path: Path):
+ """`0640` says who can read a file only together with its group. A new
+ file takes this user's group, so a chain shared through another group
+ stopped being readable by that group after its first update."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ group = _another_group()
+ os.chown(chain, -1, group)
+ os.chmod(chain, 0o640)
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ after = os.stat(chain)
+ assert (after.st_gid, stat.S_IMODE(after.st_mode)) == (group, 0o640)
+ assert manifest.name in chain.read_text("utf-8")
+ assert not job.report_failures
+
+
+@pytest.mark.skipif(os.name != "posix", reason="POSIX ownership")
+def test_a_chain_whose_owner_or_group_cannot_be_kept_is_left_as_it_is(
+ tmp_path: Path, monkeypatch):
+ """When the new file cannot be given the chain's owner and group, the
+ update is refused: a chain with different readers is not a replacement."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ os.chown(chain, -1, _another_group())
+ before = chain.read_bytes()
+ before_names = sorted(p.name for p in directory.iterdir())
+
+ def refused(*_args, **_kwargs):
+ raise PermissionError(1, "Operation not permitted")
+
+ monkeypatch.setattr(ascmhl.os, "fchown", refused)
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert chain.read_bytes() == before
+ assert sorted(p.name for p in directory.iterdir()) == sorted(
+ before_names + [manifest.name])
+ assert any("ASC MHL chain" in failure and "owner and group" in failure
+ for failure in job.report_failures)
+
+
+@pytest.mark.skipif(os.name != "posix", reason="POSIX ownership")
+def test_the_staging_file_is_open_to_its_owner_alone_until_it_matches(
+ tmp_path: Path, monkeypatch):
+ """Created with the owner half of the chain's bits, so nothing a folder
+ hands to new files can let anyone else in before the chain's own access
+ has been put on it."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ os.chmod(chain, 0o664)
+ seen = []
+ real = os.open
+
+ def spy(path, flags, mode=0o777, **kwargs):
+ descriptor = real(path, flags, mode, **kwargs)
+ if str(path).endswith(".tmp"):
+ seen.append(stat.S_IMODE(os.fstat(descriptor).st_mode))
+ return descriptor
+
+ monkeypatch.setattr(ascmhl.os, "open", spy)
+ previous = os.umask(0o000)
+ try:
+ ascmhl.write_chain(destination)
+ finally:
+ os.umask(previous)
+ assert seen == [0o600]
+ assert stat.S_IMODE(os.stat(chain).st_mode) == 0o664
+
+
+def _acl_bytes(*entries: tuple[int, int, int]) -> bytes:
+ """A Linux POSIX access list as its xattr stores it: version 2, then
+ (tag, permissions, id) entries."""
+ import struct
+
+ return struct.pack(" None:
+ try:
+ os.setxattr(path, name, value)
+ except OSError as exc:
+ pytest.skip(f"this volume keeps no POSIX access lists: {exc}")
+
+
+@pytest.mark.skipif(not hasattr(os, "setxattr"), reason="Linux access lists")
+def test_replacing_the_chain_keeps_its_access_list(tmp_path: Path):
+ """A named group granted read on the chain itself keeps it."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ os.chmod(chain, 0o640)
+ granted = _acl_bytes((_USER_OBJ, 6, _UNDEFINED), (_GROUP_OBJ, 4, _UNDEFINED),
+ (_GROUP, 4, _another_group()), (_MASK, 4, _UNDEFINED),
+ (_OTHER, 0, _UNDEFINED))
+ _set_acl(chain, _ACL_ACCESS, granted)
+ recorded = os.getxattr(chain, _ACL_ACCESS)
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert os.getxattr(chain, _ACL_ACCESS) == recorded
+ assert stat.S_IMODE(os.stat(chain).st_mode) == 0o640
+ assert manifest.name in chain.read_text("utf-8")
+ assert not job.report_failures
+
+
+@pytest.mark.skipif(not hasattr(os, "setxattr"), reason="Linux access lists")
+def test_a_chain_with_no_access_list_does_not_take_its_folders(tmp_path: Path):
+ """The folder hands a named group read on every new file. The chain has
+ no list of its own, and must not come out of an update with the
+ folder's."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ os.chmod(chain, 0o600)
+ _set_acl(directory, _ACL_DEFAULT, _acl_bytes(
+ (_USER_OBJ, 7, _UNDEFINED), (_GROUP_OBJ, 5, _UNDEFINED),
+ (_GROUP, 4, _another_group()), (_MASK, 5, _UNDEFINED),
+ (_OTHER, 0, _UNDEFINED)))
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ with pytest.raises(OSError):
+ os.getxattr(chain, _ACL_ACCESS)
+ assert stat.S_IMODE(os.stat(chain).st_mode) == 0o600
+ assert manifest.name in chain.read_text("utf-8")
+ assert not job.report_failures
+
+
+def _macos_acl(path: Path) -> list[str]:
+ listing = subprocess.run(["ls", "-le", str(path)], check=True,
+ capture_output=True, text=True).stdout
+ return [line.strip() for line in listing.splitlines()[1:]]
+
+
+@pytest.mark.skipif(os.uname().sysname != "Darwin" if hasattr(os, "uname")
+ else True, reason="macOS access lists")
+def test_replacing_the_chain_keeps_its_macos_access_list(tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ chain = destination / "ascmhl" / "ascmhl_chain.xml"
+ subprocess.run(["chmod", "+a", "everyone allow read", str(chain)],
+ check=True, capture_output=True)
+ recorded = _macos_acl(chain)
+ assert any("everyone allow read" in line for line in recorded)
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert _macos_acl(chain) == recorded
+ assert manifest.name in chain.read_text("utf-8")
+ assert not job.report_failures
+
+
+@pytest.mark.skipif(os.uname().sysname != "Darwin" if hasattr(os, "uname")
+ else True, reason="macOS access lists")
+def test_a_macos_chain_with_no_access_list_does_not_take_its_folders(
+ tmp_path: Path):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ subprocess.run(["chmod", "+a", "everyone allow read,file_inherit",
+ str(directory)], check=True, capture_output=True)
+ assert _macos_acl(chain) == []
+
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert _macos_acl(chain) == []
+ assert manifest.name in chain.read_text("utf-8")
+ assert not job.report_failures
From 31aa3f94885a9bbb175fd35133ff293738624db4 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:43:42 -0700
Subject: [PATCH 12/14] Create the macOS staging file refusing inheritance, and
fail on a failed lookup
On macOS an entry a folder hands to new files is granted before the mode
bits are looked at, so creating the staging file owner-only did not keep
that entry's grantee out of it until the chain's own list was applied.
When the folder has an access list the file is now created with openx_np
and an initial list flagged no-inherit, so it takes nothing from the
folder from its first moment.
A failed lookup of the staging file's list was read as "it has none",
which let an inherited list stay on the new chain. Only ENOENT (and a
volume that keeps no lists) means none now; anything else is raised and
the old chain is kept.
---
CHANGELOG.md | 7 +-
docs/ascmhl.md | 4 +
src/offloader/ascmhl.py | 181 ++++++++++++++++++++++++++++++++--------
tests/test_ascmhl.py | 79 ++++++++++++++++++
4 files changed, 234 insertions(+), 37 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9430b87..b91ce3d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,9 +43,10 @@ project uses [semantic versioning][semver].
exists is opened or removed), so a failed write keeps the old one. The
temporary file is given an existing chain's access before any content: its
owner, group, access list and permission bits on POSIX, its access rules on
- Windows. It is never wider than the chain, and the chain is readable by the
- same people afterwards; where that cannot be reproduced the old chain is
- kept. (On Windows, when the replace may not merge the rules, the update
+ Windows. It is never wider than the chain (on macOS it is created refusing
+ the entries its folder hands down), and the chain is readable by the
+ same people afterwards; where that cannot be reproduced, or an access list
+ cannot be read, the old chain is kept. (On Windows, when the replace may not merge the rules, the update
still goes through with the copy of them made when it began, with a
warning), and a chain path
close to the Windows limit no longer fails on its longer temporary name. Sequence numbers never reuse a
diff --git a/docs/ascmhl.md b/docs/ascmhl.md
index 0ca7a0b..62a6951 100644
--- a/docs/ascmhl.md
+++ b/docs/ascmhl.md
@@ -123,6 +123,10 @@ rules on Windows. Permission bits alone do not say who can read a file, so
copying only those would change the chain's readers whenever the new file's
group or its folder's defaults differ. The file is never more accessible than
the chain it replaces, and the chain is readable by the same people afterwards.
+It is created open to its owner alone; on macOS, where an entry a folder hands
+down is granted regardless of those bits, it is created refusing inheritance,
+so it takes nothing from its folder even for a moment. A failure to read an
+access list is an error, never taken to mean there is none.
When that access cannot be reproduced (on POSIX, a chain owned by another
user, whose ownership only that user or root can give a file) the update is
refused, the old chain is kept and the job reports the failure. A new
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 24a03b5..37f7ed2 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -519,15 +519,24 @@ def _create_staging_posix(candidate: Path, chain: Path, flags: int) -> int:
can read the chain: `0640` means something else once the group has.
So the file is created open to its owner alone (the owner half of the
- chain's bits, which no folder default can widen), then given the chain's
- owner and group, then its access list, then its exact bits, all while it
- is empty. If any of that is refused the file is removed and the error
- raised: the old chain is kept rather than replaced by one with different
- readers.
+ chain's bits), then given the chain's owner and group, then its access
+ list, then its exact bits, all while it is empty. If any of that is
+ refused the file is removed and the error raised: the old chain is kept
+ rather than replaced by one with different readers.
+
+ Owner-only bits are enough at creation on Linux, where a folder's default
+ list reaches a new file only through its group bits, which are off. They
+ are not on macOS: an entry a folder hands down is granted before the bits
+ are looked at, and whoever it names could open the empty file and keep
+ it open. There the file is created refusing inheritance; see
+ `_create_uninherited_macos`.
"""
recorded = os.stat(chain)
mode = stat.S_IMODE(recorded.st_mode)
- descriptor = os.open(longpath.extended(candidate), flags, mode & 0o700)
+ if sys.platform == "darwin" and _macos_has_access_list(candidate.parent):
+ descriptor = _create_uninherited_macos(candidate, flags, mode & 0o700)
+ else:
+ descriptor = os.open(longpath.extended(candidate), flags, mode & 0o700)
try:
created = os.fstat(descriptor)
owner = recorded.st_uid if recorded.st_uid != created.st_uid else -1
@@ -595,50 +604,154 @@ def _copy_access_list_linux(chain: Path, descriptor: int) -> None:
raise
-def _copy_access_list_macos(chain: Path, descriptor: int) -> None:
+_ACL_TYPE_EXTENDED = 0x100 # the only kind macOS has
+_ACL_FLAG_NO_INHERIT = 1 << 17
+_FILESEC_MODE = 4
+_FILESEC_ACL = 5
+
+
+def _absent_access_list(code: int) -> bool:
+ """What a failed macOS access-list lookup means: True when the file has
+ no list (or its volume keeps none). Anything else is a real failure and
+ is raised, never read as "no list": taking `ENOMEM` for an empty answer
+ would let a list the folder handed down survive into the new chain.
+ """
+ if code in (0, errno.ENOENT) or code in _NO_ACCESS_LIST:
+ return True
+ raise OSError(code, os.strerror(code))
+
+
+def _macos_acl_api():
+ """libc's access-list calls, with their types declared. macOS only."""
import ctypes
- extended = 0x100 # ACL_TYPE_EXTENDED, the only kind macOS has
+ pointer, integer = ctypes.c_void_p, ctypes.c_int
+ signatures = {
+ "acl_get_file": (pointer, [ctypes.c_char_p, integer]),
+ "acl_get_fd_np": (pointer, [integer, integer]),
+ "acl_set_fd_np": (integer, [integer, pointer, integer]),
+ "acl_init": (pointer, [integer]),
+ "acl_free": (integer, [pointer]),
+ "acl_get_flagset_np": (integer, [pointer, ctypes.POINTER(pointer)]),
+ "acl_add_flag_np": (integer, [pointer, integer]),
+ "filesec_init": (pointer, []),
+ "filesec_set_property": (integer, [pointer, integer, pointer]),
+ "filesec_free": (None, [pointer]),
+ "openx_np": (integer, [ctypes.c_char_p, integer, pointer]),
+ }
try:
libc = ctypes.CDLL(None, use_errno=True)
- get_file, get_fd = libc.acl_get_file, libc.acl_get_fd_np
- set_fd, new, free = libc.acl_set_fd_np, libc.acl_init, libc.acl_free
- except (OSError, AttributeError):
- return
- get_file.restype = get_fd.restype = new.restype = ctypes.c_void_p
- get_file.argtypes = [ctypes.c_char_p, ctypes.c_int]
- get_fd.argtypes = [ctypes.c_int, ctypes.c_int]
- set_fd.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
- set_fd.restype = ctypes.c_int
- new.argtypes = [ctypes.c_int]
- free.argtypes = [ctypes.c_void_p]
- free.restype = ctypes.c_int
+ for name, (restype, argtypes) in signatures.items():
+ function = getattr(libc, name)
+ function.restype, function.argtypes = restype, argtypes
+ except AttributeError as exc:
+ raise OSError(errno.ENOSYS, f"access-list calls unavailable: {exc}") from exc
+ return libc
+
+
+def _macos_acl_of_path(libc, path: Path):
+ """The access list at `path` (to be freed), or None when it has none."""
+ import ctypes
ctypes.set_errno(0)
- recorded = get_file(os.fsencode(chain), extended)
- if not recorded:
- code = ctypes.get_errno()
- if code not in (0, errno.ENOENT) and code not in _NO_ACCESS_LIST \
- and code != errno.EINVAL:
+ acl = libc.acl_get_file(os.fsencode(path), _ACL_TYPE_EXTENDED)
+ if acl or _absent_access_list(ctypes.get_errno()):
+ return acl or None
+ return None
+
+
+def _macos_acl_of_descriptor(libc, descriptor: int):
+ """The access list of an open file (to be freed), or None."""
+ import ctypes
+
+ ctypes.set_errno(0)
+ acl = libc.acl_get_fd_np(descriptor, _ACL_TYPE_EXTENDED)
+ if acl or _absent_access_list(ctypes.get_errno()):
+ return acl or None
+ return None
+
+
+def _macos_has_access_list(folder: Path) -> bool:
+ """Whether `folder` has an access list, so may hand entries down."""
+ libc = _macos_acl_api()
+ acl = _macos_acl_of_path(libc, folder)
+ if acl:
+ libc.acl_free(acl)
+ return bool(acl)
+
+
+def _create_uninherited_macos(candidate: Path, flags: int, mode: int) -> int:
+ """Create `candidate` exclusively, taking nothing from its folder.
+
+ `openx_np` creates a file with its security given up front. An initial
+ access list flagged `ACL_FLAG_NO_INHERIT` is how the kernel is told not
+ to add the entries the folder hands to new files, so the file exists
+ from its first moment with an empty list and the given bits, and nobody
+ a folder entry names can open it.
+ """
+ import ctypes
+
+ libc = _macos_acl_api()
+
+ def check(result: int) -> None:
+ if result != 0:
+ code = ctypes.get_errno()
raise OSError(code, os.strerror(code))
- if code not in (0, errno.ENOENT):
- return # the volume keeps no access lists
- inherited = get_fd(descriptor, extended)
- empty = None
+
+ acl = libc.acl_init(0)
+ security = libc.filesec_init()
+ try:
+ if not acl or not security:
+ raise OSError(errno.ENOMEM, os.strerror(errno.ENOMEM))
+ flagset = ctypes.c_void_p()
+ check(libc.acl_get_flagset_np(acl, ctypes.byref(flagset)))
+ check(libc.acl_add_flag_np(flagset, _ACL_FLAG_NO_INHERIT))
+ boxed_acl = ctypes.c_void_p(acl)
+ boxed_mode = ctypes.c_uint16(mode)
+ check(libc.filesec_set_property(security, _FILESEC_ACL,
+ ctypes.byref(boxed_acl)))
+ check(libc.filesec_set_property(security, _FILESEC_MODE,
+ ctypes.byref(boxed_mode)))
+ ctypes.set_errno(0)
+ descriptor = libc.openx_np(os.fsencode(candidate), flags, security)
+ if descriptor < 0:
+ code = ctypes.get_errno()
+ # OSError picks FileExistsError for EEXIST, which the caller's
+ # retry on a taken name relies on.
+ raise OSError(code, os.strerror(code), str(candidate))
+ return descriptor
+ finally:
+ if security:
+ libc.filesec_free(security)
+ if acl:
+ libc.acl_free(acl)
+
+
+def _copy_access_list_macos(chain: Path, descriptor: int) -> None:
+ import ctypes
+
+ libc = _macos_acl_api()
+ recorded = _macos_acl_of_path(libc, chain)
+ current = empty = None
try:
- if not recorded and not inherited:
+ # Raises when the lookup fails: only a file known to have no list
+ # may be left without one being set.
+ current = _macos_acl_of_descriptor(libc, descriptor)
+ if not recorded and not current:
return # none on either: nothing to do
wanted = recorded
if not wanted:
# An empty list is how one is removed (what `chmod -N` does).
- wanted = empty = new(0)
- if set_fd(descriptor, wanted, extended) != 0:
+ wanted = empty = libc.acl_init(0)
+ if not wanted:
+ raise OSError(errno.ENOMEM, os.strerror(errno.ENOMEM))
+ if libc.acl_set_fd_np(descriptor, wanted, _ACL_TYPE_EXTENDED) != 0:
code = ctypes.get_errno()
raise OSError(code, os.strerror(code))
finally:
- for acl in (recorded, inherited, empty):
+ for acl in (recorded, current, empty):
if acl:
- free(acl)
+ libc.acl_free(acl)
def _discard(temporary: Path | None) -> None:
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 94012d1..4ece4bc 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -1548,3 +1548,82 @@ def test_a_macos_chain_with_no_access_list_does_not_take_its_folders(
assert _macos_acl(chain) == []
assert manifest.name in chain.read_text("utf-8")
assert not job.report_failures
+
+
+def test_a_failed_access_list_lookup_is_never_read_as_no_list():
+ """`ENOENT` is how macOS says a file has no access list. Any other
+ failure says nothing about the file, and reading `ENOMEM` as "none" let
+ a list the folder handed down stay on the new chain."""
+ import errno
+
+ assert ascmhl._absent_access_list(errno.ENOENT) is True
+ assert ascmhl._absent_access_list(0) is True
+ for code in (errno.ENOMEM, errno.EACCES, errno.EIO, errno.EINVAL):
+ with pytest.raises(OSError) as raised:
+ ascmhl._absent_access_list(code)
+ assert raised.value.errno == code
+
+
+_ON_MACOS = hasattr(os, "uname") and os.uname().sysname == "Darwin"
+
+
+@pytest.mark.skipif(not _ON_MACOS, reason="macOS access lists")
+@pytest.mark.parametrize("chain_rule", [None, "everyone allow write"])
+def test_the_macos_staging_file_takes_nothing_from_its_folder(
+ tmp_path: Path, monkeypatch, chain_rule):
+ """A folder entry marked to be handed down is granted before the mode
+ bits are looked at, so owner-only bits do not keep its grantee out of a
+ new file. The staging file must exist without it from the first moment,
+ not have it taken off afterwards."""
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ if chain_rule:
+ subprocess.run(["chmod", "+a", chain_rule, str(chain)], check=True,
+ capture_output=True)
+ recorded = _macos_acl(chain)
+ subprocess.run(["chmod", "+a", "everyone allow read,file_inherit",
+ str(directory)], check=True, capture_output=True)
+
+ at_creation = []
+ real = ascmhl._copy_access_list
+
+ def spy(existing, descriptor):
+ (staging,) = directory.glob("*.tmp")
+ at_creation.append((_macos_acl(staging),
+ stat.S_IMODE(os.fstat(descriptor).st_mode) & 0o077))
+ return real(existing, descriptor)
+
+ monkeypatch.setattr(ascmhl, "_copy_access_list", spy)
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert at_creation == [([], 0)]
+ assert _macos_acl(chain) == recorded
+ assert manifest.name in chain.read_text("utf-8")
+ assert not job.report_failures
+
+
+@pytest.mark.skipif(not _ON_MACOS, reason="macOS access lists")
+def test_a_failed_lookup_of_the_staging_files_list_keeps_the_old_chain(
+ tmp_path: Path, monkeypatch):
+ _jobs, destination = _write_generations(tmp_path, 1)
+ directory = destination / "ascmhl"
+ chain = directory / "ascmhl_chain.xml"
+ before = chain.read_bytes()
+ before_names = sorted(p.name for p in directory.iterdir())
+
+ def out_of_memory(_libc, _descriptor):
+ import errno
+
+ raise OSError(errno.ENOMEM, "Cannot allocate memory")
+
+ monkeypatch.setattr(ascmhl, "_macos_acl_of_descriptor", out_of_memory)
+ job, _ = _offload(tmp_path, {"a.mov": b"aaaa"})
+ manifest = ascmhl.write_manifest(job, destination, when=WHEN)
+
+ assert chain.read_bytes() == before
+ assert sorted(p.name for p in directory.iterdir()) == sorted(
+ before_names + [manifest.name])
+ assert any("ASC MHL chain" in failure and "access list" in failure
+ for failure in job.report_failures)
From ac47893f1c91ea0dd7236dbd87d78e6263be2d25 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 14:55:11 -0700
Subject: [PATCH 13/14] Open the macOS staging file close-on-exec
os.open makes every descriptor non-inheritable, but the openx_np call
that creates the staging file on macOS did not ask for O_CLOEXEC. A
helper process launched while the chain is written could inherit the
descriptor and keep a removable archive busy after the offload. The flag
is passed now, and the descriptor is marked non-inheritable on every
platform's path.
---
src/offloader/ascmhl.py | 10 ++++++++--
tests/test_ascmhl.py | 20 ++++++++++++++++++++
2 files changed, 28 insertions(+), 2 deletions(-)
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 37f7ed2..73a4c5f 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -478,7 +478,8 @@ class SecurityAttributes(ctypes.Structure):
finally:
local_free(descriptor)
try:
- return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY)
+ return msvcrt.open_osfhandle(
+ handle, os.O_WRONLY | os.O_BINARY | os.O_NOINHERIT)
except BaseException:
close_handle(handle)
longpath.unlink(candidate)
@@ -713,12 +714,17 @@ def check(result: int) -> None:
check(libc.filesec_set_property(security, _FILESEC_MODE,
ctypes.byref(boxed_mode)))
ctypes.set_errno(0)
- descriptor = libc.openx_np(os.fsencode(candidate), flags, security)
+ # Close-on-exec, as `os.open` makes every descriptor: a helper
+ # launched while the chain is written must not inherit this one and
+ # keep a removable archive busy after the offload is over.
+ descriptor = libc.openx_np(os.fsencode(candidate),
+ flags | getattr(os, "O_CLOEXEC", 0), security)
if descriptor < 0:
code = ctypes.get_errno()
# OSError picks FileExistsError for EEXIST, which the caller's
# retry on a taken name relies on.
raise OSError(code, os.strerror(code), str(candidate))
+ os.set_inheritable(descriptor, False)
return descriptor
finally:
if security:
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index 4ece4bc..bbffec5 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -1592,6 +1592,8 @@ def spy(existing, descriptor):
(staging,) = directory.glob("*.tmp")
at_creation.append((_macos_acl(staging),
stat.S_IMODE(os.fstat(descriptor).st_mode) & 0o077))
+ # Close-on-exec, like any descriptor `os.open` returns.
+ assert os.get_inheritable(descriptor) is False
return real(existing, descriptor)
monkeypatch.setattr(ascmhl, "_copy_access_list", spy)
@@ -1627,3 +1629,21 @@ def out_of_memory(_libc, _descriptor):
before_names + [manifest.name])
assert any("ASC MHL chain" in failure and "access list" in failure
for failure in job.report_failures)
+
+
+@pytest.mark.parametrize("existing", [True, False])
+def test_the_staging_descriptor_is_not_inherited_by_child_processes(
+ tmp_path: Path, existing):
+ """Whichever way the staging file is created on this platform, a helper
+ process started during the write must not inherit its descriptor and
+ hold the archive's volume busy afterwards."""
+ chain = tmp_path / "ascmhl_chain.xml"
+ if existing:
+ chain.write_bytes(b"")
+ candidate = tmp_path / "ascmhl_chain.xml.0123456789abcdef.tmp"
+ descriptor = ascmhl._create_staging(candidate, chain if existing else None)
+ try:
+ assert os.get_inheritable(descriptor) is False
+ finally:
+ os.close(descriptor)
+ candidate.unlink()
From 4c8d3b83920aae5b22b8949b88c0105e9077d899 Mon Sep 17 00:00:00 2001
From: owenpkent <20529132+owenpkent@users.noreply.github.com>
Date: Sun, 29 Nov 2026 15:09:28 -0700
Subject: [PATCH 14/14] Close and remove the staging file when it cannot be
kept from children
After openx_np created the staging file, a refused os.set_inheritable
left the file on disk and its descriptor open, with the caller holding
neither. The open flag is now relied on alone where it exists, and where
it does not, a refused setter closes the descriptor and removes the file
before the error goes up.
---
src/offloader/ascmhl.py | 26 ++++++++++++++++++++++++--
tests/test_ascmhl.py | 29 +++++++++++++++++++++++++++++
2 files changed, 53 insertions(+), 2 deletions(-)
diff --git a/src/offloader/ascmhl.py b/src/offloader/ascmhl.py
index 73a4c5f..91c443b 100644
--- a/src/offloader/ascmhl.py
+++ b/src/offloader/ascmhl.py
@@ -717,14 +717,15 @@ def check(result: int) -> None:
# Close-on-exec, as `os.open` makes every descriptor: a helper
# launched while the chain is written must not inherit this one and
# keep a removable archive busy after the offload is over.
+ close_on_exec = getattr(os, "O_CLOEXEC", 0)
descriptor = libc.openx_np(os.fsencode(candidate),
- flags | getattr(os, "O_CLOEXEC", 0), security)
+ flags | close_on_exec, security)
if descriptor < 0:
code = ctypes.get_errno()
# OSError picks FileExistsError for EEXIST, which the caller's
# retry on a taken name relies on.
raise OSError(code, os.strerror(code), str(candidate))
- os.set_inheritable(descriptor, False)
+ _keep_from_children(descriptor, candidate, already=bool(close_on_exec))
return descriptor
finally:
if security:
@@ -733,6 +734,27 @@ def check(result: int) -> None:
libc.acl_free(acl)
+def _keep_from_children(descriptor: int, candidate: Path, *, already: bool) -> None:
+ """Make sure a descriptor this module opened itself is not inherited.
+
+ The open flag does it where there is one (`already`), and then nothing
+ more is asked: setting it afterwards is a separate operation that can be
+ refused on its own. Without the flag it is set here, and if that fails
+ the file just created is closed and removed before the error goes up,
+ since the caller has not been handed the descriptor or the name yet and
+ could clean up neither. A descriptor left open would keep the archive's
+ volume busy until the process ends.
+ """
+ if already:
+ return
+ try:
+ os.set_inheritable(descriptor, False)
+ except BaseException:
+ os.close(descriptor)
+ longpath.unlink(candidate)
+ raise
+
+
def _copy_access_list_macos(chain: Path, descriptor: int) -> None:
import ctypes
diff --git a/tests/test_ascmhl.py b/tests/test_ascmhl.py
index bbffec5..b802bf7 100644
--- a/tests/test_ascmhl.py
+++ b/tests/test_ascmhl.py
@@ -1647,3 +1647,32 @@ def test_the_staging_descriptor_is_not_inherited_by_child_processes(
finally:
os.close(descriptor)
candidate.unlink()
+
+
+def test_a_descriptor_that_cannot_be_kept_from_children_is_closed_and_removed(
+ tmp_path: Path, monkeypatch):
+ """Setting the flag after the open can be refused on its own. The file
+ has been created by then and its descriptor handed to no one, so it is
+ closed and removed here: left open, it holds the archive's volume busy."""
+ import errno
+
+ def refused(_descriptor, _inheritable):
+ raise PermissionError(errno.EPERM, "Operation not permitted")
+
+ monkeypatch.setattr(ascmhl.os, "set_inheritable", refused)
+
+ # With the open flag there is nothing to set, so nothing to refuse.
+ candidate = tmp_path / "flagged.tmp"
+ descriptor = os.open(candidate, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
+ ascmhl._keep_from_children(descriptor, candidate, already=True)
+ os.fstat(descriptor)
+ os.close(descriptor)
+
+ candidate = tmp_path / "unflagged.tmp"
+ descriptor = os.open(candidate, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
+ with pytest.raises(PermissionError):
+ ascmhl._keep_from_children(descriptor, candidate, already=False)
+ with pytest.raises(OSError) as closed:
+ os.fstat(descriptor)
+ assert closed.value.errno == errno.EBADF
+ assert not candidate.exists()