Repository navigation
Neutralise CSV formulas and make the ASC MHL chain append-only - #42
Conversation
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.
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.
owenpkent
left a comment
There was a problem hiding this comment.
The ASC MHL writer can reuse a generation number and can return a successful CLI status when it could not update the chain. I exercised the writer and CLI on disposable Windows archives and traced the job and timeline CSV outputs to SafeWriter. Eleven focused tests passed at 87aa4f7, including the six tested CSV trigger characters. All nine GitHub checks passed.
| 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, |
There was a problem hiding this comment.
[P2] Reserve generation numbers already recorded in the chain
If the newest manifest is missing, next_sequence() uses only the surviving files. Starting with generations 1 and 2, I set the second manifest aside and wrote another generation the next day. The new chain contained sequence numbers 1, 2, 2. The existing regression removes generation 1, which leaves the maximum on disk intact.
Allocate the new number above both the recorded and on-disk maxima. Assert the ordered list of sequence numbers in the regression so a dictionary keyed by sequence cannot hide a duplicate. ASC MHL requires unique, consecutive sequence numbers. ASC MHL specification, §7.4
| 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 |
There was a problem hiding this comment.
[P2] Propagate an unwritten chain entry as a report failure
This return reaches write_manifest() as a warning, even though the requested ASC MHL history never received its new chain entry. With a directory occupying ascmhl_chain.xml, the CLI wrote a generation and exited 0 on this head. The same offload exited 5 on the merge base. Scripts rely on exit 5 to distinguish a successful copy with incomplete paperwork.
Preserve the unreadable chain and propagate a distinct update failure through job.report_failures. A CLI regression should assert exit 5 and that the existing chain path is untouched.
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.
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.
owenpkent
left a comment
There was a problem hiding this comment.
The amended writer fixes the previously reported missing-generation number reuse, report failure exit code, interrupted replacement of an existing chain, and CSV trigger coverage. Twenty focused Windows tests passed for those cases. All nine GitHub checks passed at 80af849.
I found a remaining numeric-identity issue with valid imported chains and a permissions regression when replacing a shared POSIX chain. The numeric result was reproduced on Windows. The permissions finding follows from the file creation and replacement calls.
| "since it was recorded; the chain no longer matches it.") | ||
|
|
||
| entries = list(recorded) | ||
| numbers = {sequence for sequence, _name, _c4 in recorded} |
There was a problem hiding this comment.
[P2] Compare sequence numbers by their integer value
The chain preserves sequence strings as written, but the new filename’s number is normalized through int(). The existing duplicate-number fixture with the second chain entry spelled 0002 produced 1, 0002, 2 and no warning. Both spellings denote the same integer, so the resulting chain violates the uniqueness requirement.
Use integers for the duplicate check and retain the recorded string for serialization. Include a zero-padded attribute in the existing regression. ASC MHL specification, §7.4 · XML Schema integer
| stream.write(payload) | ||
| stream.flush() | ||
| os.fsync(stream.fileno()) | ||
| os.replace(temporary, path) |
There was a problem hiding this comment.
[P2] Preserve an existing chain’s access mode during replacement
The new file inherits the updating process’s creation permissions. On a shared POSIX archive using ordinary mode bits, a group-readable chain set to 0640 becomes 0600 after an update under umask 0077. The next operator in the group loses read access. The previous in-place write retained the chain’s mode.
Apply the existing chain’s access mode to its replacement before promotion. Keep the ordinary creation mode for a new history, and add a POSIX test with different existing and default permissions.
…, numeric sequence check
owenpkent
left a comment
There was a problem hiding this comment.
The changes at 9ca61d5 address the earlier sequence-number, temporary-file collision, and final POSIX mode findings. Two Windows compatibility issues remain. I ran the focused CSV and ASC MHL checks on Windows, with 20 passing and two POSIX-only mode tests skipped. I also compared chain replacement with the base on NTFS and exercised the legacy path-length boundary.
| if mode is not None: | ||
| os.fchmod(stream.fileno(), mode) | ||
| os.fsync(stream.fileno()) | ||
| os.replace(temporary, path) |
There was a problem hiding this comment.
[P2] Preserve file-specific Windows access rules when updating a chain
A shared archive may grant a reader access directly on its chain file. On NTFS the base writer preserved an existing protected ACL. After write_chain() on this head, the same chain inherited the parent directory's rules again. A reader who depends on a file-specific grant can lose access after the next update. Preserve the existing chain's access rules during replacement and cover an existing, explicitly permissioned chain in a Windows test. Windows provides a replacement operation that carries over the original access rules. Microsoft ReplaceFileW documentation
| descriptor = -1 | ||
| for attempt in range(5): | ||
| candidate = path.with_name( | ||
| f"{path.name}.{secrets.token_hex(8)}.tmp") |
There was a problem hiding this comment.
[P3] Account for the temporary filename at the Windows path limit
The random suffix can push only the staging path past MAX_PATH. With the legacy Win32 limit simulated, the base wrote both a 257-character generation path and its 241-character chain path. This head wrote the generation, then reported a chain failure opening its 262-character temporary path. Apply the existing longpath.extended() helper to the temporary file operations, including promotion and cleanup, or use a short exclusive staging name. A boundary test can cover a destination where both final paths fit. Microsoft path-length documentation
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.
owenpkent
left a comment
There was a problem hiding this comment.
The protected ACL on an existing NTFS chain now survives an ordinary update. With the legacy Windows path limit simulated, two generations were also recorded successfully at the previously failing boundary. I found two remaining issues in error cleanup and the new test fixture. I shared a separate access-control finding privately with the maintainer.
The focused Windows run had 36 passing tests, four skips, and one fixture failure. Three skips require POSIX permission bits and one requires permission to create a symlink. The failing boundary test passed with a shorter temporary root.
| stream.flush() | ||
| os.fsync(stream.fileno()) | ||
| return _promote(temporary, path) | ||
| except OSError as exc: |
There was a problem hiding this comment.
[P3] Clean up the owned staging file when backup restoration fails
If Windows returns 1177 and restoring the backup also fails, _replace_file_windows() raises ChainUpdateError. This handler catches only OSError, so the staging file survives next to the backup. With those two failures injected, the old chain remained recoverable at .old and one complete .tmp remained in the archive. Clean up the owned staging path for both exception types. Preserve the backup and the existing recovery message. The 1177 test can cover a failed restore as well as a successful one.
| 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: |
There was a problem hiding this comment.
[P3] Make the path-length fixture independent of the pytest root
When the padding loop leaves one character to add, it stops with a 240-character chain path and the 241 assertion fails before the writer runs. I hit this on Windows. The test passed under a shorter pytest root. The variable-length final directory name also appears in the generated manifest filename, which reached 342 characters for the failing layout. Reserve a short leaf such as A001 and pad its parent. That yielded a 257-character manifest, a 241-character chain, and a 262-character stage in my check. Both generations were recorded with the legacy limit simulated.
… clean it up when a restore fails
owenpkent
left a comment
There was a problem hiding this comment.
The earlier Windows staging, backup-restoration cleanup, and long-path fixture findings are addressed at a95695c. A protected NTFS chain retained its access rules in a normal update and when I injected an initial access-denied error to exercise the fallback. The updated boundary test also passed using the same temporary-root layout that failed last time. I shared a separate POSIX access-control finding privately with the maintainer.
The focused Windows run had 40 passes and five skips. Four skipped cases require POSIX mode bits and one requires permission to create a symlink. The inline comment identifies two documents that still describe the old Windows fallback.
| | 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. | |
There was a problem hiding this comment.
[P3] Update the description of the Windows access-denied fallback
This row and CHANGELOG.md line 47 say an update proceeds without the file’s access rules. The new writer copies the rules onto the stage at creation. When the first replacement call is denied, the warning explains that the replacement carries that copy. I exercised the fallback on NTFS and the final protected access rules matched the original. Align both passages with docs/ascmhl.md so an operator reading the warning knows which permissions the resulting chain carries.
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.
owenpkent
left a comment
There was a problem hiding this comment.
The previous POSIX group and final access-list findings are addressed at 8c2080c. I checked the Linux and macOS CI results for the new group-preservation, refused-ownership-change, and native access-list tests. The changelog and safety guide now describe the Windows fallback consistently with the writer. Two macOS access-control issues remain, which I shared privately with the maintainer.
The focused Windows run passed 40 tests. Twelve platform-dependent cases were skipped locally. Ubuntu CI · macOS CI
…led 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.
owenpkent
left a comment
There was a problem hiding this comment.
Both previous macOS P2 findings are fixed at 31aa3f9. The new tests ran on macOS CI. They check the stage immediately after creation with and without an existing chain ACL, and verify that a failed ACL lookup leaves the old chain intact and reports the failure. I also repeated the ENOMEM fault injection against the libc wrapper and confirmed that the error propagates.
One low-priority descriptor-lifetime issue remains in the new native open. I checked the flags passed by this code with a stand-in and traced their handling in Apple’s implementation. Locally, 41 focused Windows tests passed and 15 platform-dependent cases were skipped. macOS CI
| 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) |
There was a problem hiding this comment.
[P3] Set close-on-exec when opening the macOS staging file
Updating an existing chain in a directory with an ACL takes this native path. openx_np forwards the supplied flags to the kernel, and they omit O_CLOEXEC. If a host application starts a long-lived helper with ordinary posix_spawn while the chain is being written, the helper can retain the open file after Offloader finishes. That reference can keep a removable archive volume busy when the operator tries to eject it.
Pass flags | os.O_CLOEXEC to openx_np so the descriptor is non-inheritable from creation, as it is on the os.open path. The existing macOS staging test can check os.get_inheritable(descriptor) alongside the ACL. Apple’s openx_np implementation · Apple’s posix_spawn documentation
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.
owenpkent
left a comment
There was a problem hiding this comment.
One P3 remains at ac47893. If the post-open descriptor call fails on macOS, the chain writer leaves the staging file open. I reproduced the cleanup failure with fault injection.
The previous inheritance finding is fixed. openx_np now receives O_CLOEXEC at creation. Both tests for directories with inheritable ACLs passed on macOS. The new and existing chain descriptor tests passed in that job and locally on Windows. macOS CI
| # 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) |
There was a problem hiding this comment.
[P3] Clean up the macOS staging file if setting the descriptor flag fails
openx_np has already created the file exclusively. If os.set_inheritable raises here, the caller never receives the descriptor or records the staging path for cleanup. CPython uses ioctl(FIOCLEX) for this call, and Darwin checks permission for that operation separately from the open. CPython descriptor handling · Darwin ioctl handling
I injected EPERM here with a stand-in for openx_np that created a real temporary file. After ChainUpdateError, the original chain was intact, os.fstat still succeeded on the descriptor, and the empty .tmp remained. That open descriptor can keep the archive volume busy until the process exits.
Use the O_CLOEXEC flag alone when it is available. If the fallback setter is needed, close the descriptor and unlink the owned candidate when it raises. A regression test can inject PermissionError and check that os.fstat reports EBADF and that the staging path is gone.
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.
…ning # Conflicts: # CHANGELOG.md
owenpkent
left a comment
There was a problem hiding this comment.
No actionable findings at fe95cd4. The previous P3 is fixed. The macOS writer passes O_CLOEXEC at file creation and skips the separate setter when the flag is available. I replayed the fallback failure through the chain writer on Windows using a real temporary file and a stand-in for the Darwin open. Injecting EPERM preserved the original chain byte for byte, closed the descriptor (os.fstat returned EBADF), and removed the staging file before the writer reported the error.
I compared the added and removed lines in all eight PR files against their respective bases before and after the merge from main. They matched, including the changelog. Eleven focused Windows tests passed, covering cleanup, chain updates, job identity, two cards sharing one destination, and CSV output. All nine CI checks passed at this head. The macOS job ran both native ACL staging cases and the new cross-platform cleanup regression. macOS CI
What
Two writer fixes, one commit each, plus a one-line doc correction from review.
=,+,-,@, a tab or a carriage return is now written with a leading apostrophe. The change is inSafeWriter.writerow, so every column and both CSV outputs (the job report andresolve --csv) are covered. Numbers and the header row are unchanged.Behaviour to know about
docs/data-safety.md.write_chainkeeps its signature.update_chainis the new function that also returns the warnings.offloader verifystill does not read the chain file, so a changed or missing generation is reported when the next generation is written, not byverify. The docs say so.Tests
tests/test_reports.py: three new tests (seven cases). All seven failed with the fix removed.tests/test_ascmhl.py: six new tests. The tampered, deleted, unreadable and missing-chain tests failed with the fix removed. The byte-stability test and the first-generation test passed before and are guards.No existing test was modified.
Checked
ruff check src tests: clean--fuzz): 95 passed, 1 skipped