diff --git a/dokimi/changelog.d/20261127_140000_catalog-eval-receipts-keep-group-mode.md b/dokimi/changelog.d/20261127_140000_catalog-eval-receipts-keep-group-mode.md new file mode 100644 index 000000000..a96e7c5fa --- /dev/null +++ b/dokimi/changelog.d/20261127_140000_catalog-eval-receipts-keep-group-mode.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **`catalog eval --out-dir` keeps the group and mode of the receipts a rerun replaces** — `catalog.json`, `plan.json`, `result.json` and `report.md` were staged as new files and renamed over the previous ones, so a `0o640` receipt in a supplementary group came back `0o664` in the user's primary group (the cause of #1067 and #1165). The staged file now gets the previous receipt's mode and, where the user may give it, its group (root also the owner) before the rename, through `dokimi.atomic_write.keep_owner_group_mode`. A user who may not give the group keeps the receipt published in their own group, without an error; a receipt with no previous file keeps the umask mode as before. An access ACL the staged file inherited from the output directory's default ACL is dropped before the mode is set, so the receipt grants no named user more than the one it replaces. The previous receipts are still moved aside first and put back as they were when the swap fails, and a new receipt that took a read-only mode is made writable before that rollback removes it, as Windows refuses to unlink a read-only file. diff --git a/dokimi/dokimi/atomic_write.py b/dokimi/dokimi/atomic_write.py index 298008447..04d56e960 100644 --- a/dokimi/dokimi/atomic_write.py +++ b/dokimi/dokimi/atomic_write.py @@ -260,6 +260,22 @@ def _keep_owner_and_group(fd: int, old: os.stat_result, *, keep_group: bool = Fa raise _OwnerRefused(exc.errno, "root may not give the new file the owner or group of the file it replaces") from exc +def keep_owner_group_mode(path: Path, old: os.stat_result) -> None: + """Give the file at ``path`` (the user's own, not yet published) the group, for root the owner, and the mode of ``old``. + + For a file a caller renames over another, where :func:`write_text_atomic` cannot make it. The group and owner follow :func:`_keep_owner_and_group`: a user who is not root and may not give the group keeps the one the file has, without an error, and root raises ``PermissionError`` when it may not chown. The mode is set last, as a change of owner may clear set-user-ID and set-group-ID. + """ + fd = os.open(path, os.O_RDONLY) + try: + _keep_owner_and_group(fd, old) + finally: + os.close(fd) + # As in _publish: an access ACL inherited from the directory's default would stay effective through the chmod's mask. + with contextlib.suppress(AttributeError, OSError): + os.removexattr(path, "system.posix_acl_access") + os.chmod(path, stat.S_IMODE(old.st_mode)) + + def _existing_stat(path: Path) -> os.stat_result | None: try: # A link is replaced by the rename, so it is the file replaced: its target's mode and group are not kept. diff --git a/dokimi/dokimi/commands/catalog_eval.py b/dokimi/dokimi/commands/catalog_eval.py index 1fd7d599a..d634e5a00 100644 --- a/dokimi/dokimi/commands/catalog_eval.py +++ b/dokimi/dokimi/commands/catalog_eval.py @@ -12,12 +12,14 @@ import os import platform import shutil +import stat import tempfile from collections.abc import Iterator from pathlib import Path from typing import Any from dokimi import __version__ +from dokimi.atomic_write import keep_owner_group_mode from dokimi.artifacts import save_artifact from dokimi.utils import InputError @@ -98,6 +100,25 @@ def _workdir(out: Path) -> Iterator[Path]: shutil.rmtree(work, ignore_errors=True) +def _keep_previous_owner(new: Path, previous: Path) -> None: + """Give the staged receipt the group and mode of the one moved aside to *previous*, if there was one.""" + try: + old = previous.lstat() + except FileNotFoundError: + return + if stat.S_ISREG(old.st_mode): + keep_owner_group_mode(new, old) + + +def _unlink_receipt(path: Path) -> None: + """Remove a receipt this swap placed; a read-only one (the mode of a read-only previous receipt) is made writable first, as Windows refuses to unlink it.""" + try: + path.unlink(missing_ok=True) + except PermissionError: + os.chmod(path, stat.S_IREAD | stat.S_IWRITE) + path.unlink(missing_ok=True) + + def _replace_receipts(out: Path, staged: Path, backup: Path) -> None: """Swap the four receipt files within *out*; the directory itself is never renamed or removed.""" placed: list[str] = [] @@ -107,11 +128,12 @@ def _replace_receipts(out: Path, staged: Path, backup: Path) -> None: os.replace(out / name, backup / name) for name in sorted(path.name for path in staged.iterdir()): placed.append(name) + _keep_previous_owner(staged / name, backup / name) os.replace(staged / name, out / name) except BaseException as exc: try: for name in placed: - (out / name).unlink(missing_ok=True) + _unlink_receipt(out / name) for name in _OUTPUTS: if (backup / name).exists(): os.replace(backup / name, out / name) diff --git a/dokimi/tests/test_catalog_eval_cli.py b/dokimi/tests/test_catalog_eval_cli.py index 95352bab5..9851f0e82 100644 --- a/dokimi/tests/test_catalog_eval_cli.py +++ b/dokimi/tests/test_catalog_eval_cli.py @@ -10,6 +10,7 @@ import io import os import re +import struct import subprocess import sys from pathlib import Path @@ -460,6 +461,92 @@ def flaky(src, dst): assert kept and str(kept[0]) in done.stderr +def _rerun_receipts(tmp_path, name, mode, group=None): + """``out/`` of *mode* (and *group*), then a rerun that stages a new file of that name; the replaced file's stat.""" + from dokimi.commands.catalog_eval import _replace_receipts + + out, staged, backup = tmp_path / "out", tmp_path / "new", tmp_path / "old" + for directory in (out, staged, backup): + directory.mkdir() + (out / name).write_text("old", encoding="utf-8") + os.chmod(out / name, mode) # after creation, so the umask does not hide a loss + if group is not None: + os.chown(out / name, -1, group) + (staged / name).write_text("new", encoding="utf-8") + os.chmod(staged / name, 0o644) + _replace_receipts(out, staged, backup) + assert (out / name).read_text(encoding="utf-8") == "new" + return (out / name).stat() + + +@pytest.mark.skipif(not hasattr(os, "getgroups"), reason="needs POSIX groups") +def test_a_rerun_keeps_the_group_and_mode_of_the_receipt_it_replaces(tmp_path): + other = [g for g in os.getgroups() if g != os.getegid()] + if not other: + pytest.skip("the user has no supplementary group") + info = _rerun_receipts(tmp_path, "catalog.json", 0o640, other[0]) + assert (info.st_gid, oct(info.st_mode & 0o7777)) == (other[0], "0o640") + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes") +def test_a_rerun_keeps_the_mode_of_the_receipt_it_replaces(tmp_path): + info = _rerun_receipts(tmp_path, "report.md", 0o600) + assert oct(info.st_mode & 0o7777) == "0o600" + + +@pytest.mark.skipif(not hasattr(os, "getgroups"), reason="needs POSIX groups") +def test_a_rerun_publishes_with_the_users_group_when_the_group_cannot_be_kept(tmp_path, monkeypatch): + other = [g for g in os.getgroups() if g != os.getegid()] + if not other or os.geteuid() == 0: + pytest.skip("needs a user who is not root and has a supplementary group") + + def denied(fd, uid, gid): + raise PermissionError(1, "not permitted") + + monkeypatch.setattr(os, "fchown", denied) + info = _rerun_receipts(tmp_path, "report.md", 0o640, other[0]) + assert (info.st_gid, oct(info.st_mode & 0o7777)) == (os.getegid(), "0o640") + + +def _acl(*entries): + """A ``system.posix_acl_*`` value: version 2, then (tag, perm, id) per entry.""" + return struct.pack("