diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d848d1..1394f95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -90,6 +90,32 @@ project uses [semantic versioning][semver]. compared names with `normcase`, which folds case on Windows only, so a copied `a001_Reports/` and a job named `A001` shared one folder on APFS. It now uses the flatten collision check's casefolded, NFC-normalized key. +- **A filename could run as a formula in the CSV report.** A cell starting + 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. +- **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, 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. 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 (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 + 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 copy it printed "every reference is already here" and exited 0 while references were missing or ambiguous, and with gaps to copy it reported diff --git a/README.md b/README.md index e92057c..69126c6 100644 --- a/README.md +++ b/README.md @@ -294,7 +294,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/ascmhl.md b/docs/ascmhl.md index 9a7510e..76cc9b6 100644 --- a/docs/ascmhl.md +++ b/docs/ascmhl.md @@ -116,6 +116,67 @@ 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. + +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. Over an existing +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. +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 +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 +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 +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; +- 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. + ## Verification `offloader verify` reads ASC MHL histories as well as classic MHL: diff --git a/docs/data-safety.md b/docs/data-safety.md index 8a513b7..02afe89 100644 --- a/docs/data-safety.md +++ b/docs/data-safety.md @@ -484,6 +484,8 @@ and a job named `A001` are one folder on APFS. | 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, 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; 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 924f962..851818f 100644 --- a/src/offloader/ascmhl.py +++ b/src/offloader/ascmhl.py @@ -15,14 +15,19 @@ 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 -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 @@ -247,12 +252,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]]: @@ -314,7 +338,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. @@ -322,24 +354,637 @@ 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) + + +_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. +_ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177 +_REPLACEFILE_IGNORE_ERRORS = 0x2 | 0x4 # MERGE_ERRORS | ACL_ERRORS + + +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, and the returned warning says + 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, + 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 + + 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 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) + 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): + return _replace_file_windows(temporary, path) + longpath.replace(temporary, path) + 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 | os.O_NOINHERIT) + 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 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)) + if existing_chain is None: + return os.open(longpath.extended(candidate), flags, 0o666) + if os.name == "nt": + return _create_staging_windows(candidate, existing_chain) + 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), 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) + 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 + 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) + longpath.unlink(candidate) # created here, not yet handed back + raise + 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 write_chain(root: Path) -> Path: - """Rewrite the chain file from the manifests present, C4-identifying each.""" +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 + + +_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 + + 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) + 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) + 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)) + + 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) + # 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 | 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)) + _keep_from_children(descriptor, candidate, already=bool(close_on_exec)) + return descriptor + finally: + if security: + libc.filesec_free(security) + if acl: + 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 + + libc = _macos_acl_api() + recorded = _macos_acl_of_path(libc, chain) + current = empty = None + try: + # 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 = 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, current, empty): + if acl: + libc.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: + 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. + + 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. 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 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. + + Returns a warning for the caller to pass on, or None. + """ + temporary: Path | None = None + try: + payload = _serialise(element) + path.parent.mkdir(parents=True, exist_ok=True) + 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 = _create_staging(candidate, existing) + except FileExistsError: + if attempt == 4: + raise + continue + temporary = candidate + break + with os.fdopen(descriptor, "wb") as stream: + 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: + _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 + + +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. 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 + manifests = existing_manifests(root) + warnings: list[str] = [] + + recorded: list[tuple[str, str, str]] = [] + if target.exists(): + read = _read_chain(target) + if read is None: + 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( + 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) + # 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: + 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( + 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(number) + entries.append((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 + warning = _replace_atomically(chain, target) + if warning: + warnings.append(warning) + 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, @@ -441,7 +1086,14 @@ 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. + 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 556fa50..73c9a11 100644 --- a/src/offloader/reports/csv_report.py +++ b/src/offloader/reports/csv_report.py @@ -8,6 +8,29 @@ 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, +#: 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: + """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 +39,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 +49,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_ascmhl.py b/tests/test_ascmhl.py index 6e53dd8..343e35b 100644 --- a/tests/test_ascmhl.py +++ b/tests/test_ascmhl.py @@ -9,13 +9,17 @@ from __future__ import annotations import datetime as _dt +import os import re +import secrets +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 @@ -293,6 +297,534 @@ 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 _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" + 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_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"] + + +@pytest.mark.parametrize("spelling", ["2", "0002"]) +def test_an_unrecorded_file_reusing_a_recorded_number_is_not_appended( + tmp_path: Path, spelling: str): + _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" + 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", 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_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_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) + 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 _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 + + +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. 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() + (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 + + def full(*_args, **_kwargs): + raise OSError(errno.ENOSPC, "No space left on device") + + monkeypatch.setattr(ascmhl, "_promote", full) + + +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._promote + + def spy(source, target): + seen.append((Path(source), Path(target))) + return real(source, target) + + monkeypatch.setattr(ascmhl, "_promote", 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): + _jobs, destination = _write_generations(tmp_path, 1) + (destination / "ascmhl" / "ascmhl_chain.xml").unlink() + + job, _ = _offload(tmp_path, {"a.mov": b"aaaa"}) + ascmhl.write_manifest(job, destination, when=WHEN) + + assert set(_chain_entries(destination)) == {"1", "2"} + assert any("missing" in w and "rebuilt" in w for w in job.warnings) + + +def test_a_first_generation_with_no_chain_does_not_warn(tmp_path: Path): + job, destination = _offload(tmp_path, {"a.mov": b"aaaa"}) + ascmhl.write_manifest(job, destination, when=WHEN) + assert _chain_warnings(job) == [] + + # --------------------------------------------------------------- verifying @@ -712,3 +1244,443 @@ 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_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) + 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 + + +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)) + # 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) + 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) + + +@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() + + +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() diff --git a/tests/test_reports.py b/tests/test_reports.py index ff88c36..c671397 100644 --- a/tests/test_reports.py +++ b/tests/test_reports.py @@ -196,6 +196,66 @@ 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), 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 + 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