Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### 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.
16 changes: 16 additions & 0 deletions dokimi/dokimi/atomic_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,22 @@
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)

Check warning on line 272 in dokimi/dokimi/atomic_write.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `os.close(fd)` -> `pass`
# 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))
Comment thread
antonwolfy marked this conversation as resolved.
Resolved


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.
Expand Down
24 changes: 23 additions & 1 deletion dokimi/dokimi/commands/catalog_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -98,6 +100,25 @@
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)

Check warning on line 116 in dokimi/dokimi/commands/catalog_eval.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `path.unlink(missing_ok=True)` -> `pass`
except PermissionError:
os.chmod(path, stat.S_IREAD | stat.S_IWRITE)
path.unlink(missing_ok=True)

Check warning on line 119 in dokimi/dokimi/commands/catalog_eval.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: flip-bool `True` -> `False`

Check warning on line 119 in dokimi/dokimi/commands/catalog_eval.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `path.unlink(missing_ok=True)` -> `pass`


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] = []
Expand All @@ -107,11 +128,12 @@
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)
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
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)

Check warning on line 136 in dokimi/dokimi/commands/catalog_eval.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `_unlink_receipt(out / name)` -> `pass`
for name in _OUTPUTS:
if (backup / name).exists():
os.replace(backup / name, out / name)
Expand Down
87 changes: 87 additions & 0 deletions dokimi/tests/test_catalog_eval_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import io
import os
import re
import struct
import subprocess
import sys
from pathlib import Path
Expand Down Expand Up @@ -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/<name>`` 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("<I", 2) + b"".join(struct.pack("<HHI", tag, perm, uid) for tag, perm, uid in entries)


@pytest.mark.skipif(not hasattr(os, "setxattr"), reason="needs POSIX ACLs")
def test_a_rerun_receipt_gets_no_acl_entry_of_the_directory_default(tmp_path):
from dokimi.commands.catalog_eval import _replace_receipts, _workdir

out, none = tmp_path / "out", 0xFFFFFFFF
out.mkdir()
(out / "report.md").write_text("old", encoding="utf-8")
os.chmod(out / "report.md", 0o640)
try: # user::rwx user:12345:r-x group::r-x mask::--- other::r-x
os.setxattr(out, "system.posix_acl_default", _acl((1, 7, none), (2, 5, 12345), (4, 5, none), (0x10, 0, none), (0x20, 5, none)))
except OSError:
pytest.skip("the file system takes no ACL")
with _workdir(out) as work:
(Path(work) / "new").mkdir()
(Path(work) / "new" / "report.md").write_text("new", encoding="utf-8")
_replace_receipts(out, Path(work) / "new", Path(work) / "old")
assert (out / "report.md").read_text(encoding="utf-8") == "new"
assert "system.posix_acl_access" not in os.listxattr(out / "report.md")
assert oct((out / "report.md").stat().st_mode & 0o7777) == "0o640"


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes")
def test_a_first_run_keeps_the_mode_of_the_staged_receipt(tmp_path):
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()
(staged / "report.md").write_text("new", encoding="utf-8")
os.chmod(staged / "report.md", 0o644)
_replace_receipts(out, staged, backup)
assert oct((out / "report.md").stat().st_mode & 0o7777) == "0o644"


def test_deeply_nested_skill_tree_is_bundled(tmp_path):
root = _catalog(tmp_path)
deep = root / "skills" / "alpha"
Expand Down
65 changes: 65 additions & 0 deletions dokimi/tests/test_catalog_eval_rollback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Copyright (C) 2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""The receipt swap of catalog eval: its rollback and a previous receipt that is a link."""

from __future__ import annotations

import os
import sys
from pathlib import Path

import pytest


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes and links")
def test_a_rerun_replaces_a_linked_receipt_without_taking_its_targets_mode(tmp_path):
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()
target = tmp_path / "target.md"
target.write_text("target", encoding="utf-8")
os.chmod(target, 0o600)
(out / "report.md").symlink_to(target)
(staged / "report.md").write_text("new", encoding="utf-8")
os.chmod(staged / "report.md", 0o644)
_replace_receipts(out, staged, backup)
assert not (out / "report.md").is_symlink()
assert (out / "report.md").read_text(encoding="utf-8") == "new"
assert oct((out / "report.md").stat().st_mode & 0o7777) == "0o644"


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX modes")
def test_a_failed_swap_restores_receipts_when_the_unlink_of_a_read_only_one_is_refused(tmp_path, monkeypatch):
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()
for name in ("catalog.json", "plan.json"):
(out / name).write_text(f"old {name}", encoding="utf-8")
(staged / name).write_text(f"new {name}", encoding="utf-8")
os.chmod(out / "catalog.json", 0o444)
real_replace, real_unlink = os.replace, Path.unlink
failure = OSError("injected plan publication failure")

def replace(src, dst):
if Path(dst) == out / "plan.json" and Path(src).parent == staged:
raise failure
return real_replace(src, dst)

def unlink(self, missing_ok=False):
if self.exists() and not self.stat().st_mode & 0o200: # Windows refuses a read-only file
raise PermissionError(13, "read-only", str(self))
return real_unlink(self, missing_ok=missing_ok)

monkeypatch.setattr("dokimi.commands.catalog_eval.os.replace", replace)
monkeypatch.setattr(Path, "unlink", unlink)
with pytest.raises(OSError) as raised:
_replace_receipts(out, staged, backup)
assert raised.value is failure
assert {p.name: p.read_text(encoding="utf-8") for p in out.iterdir()} == {
"catalog.json": "old catalog.json", "plan.json": "old plan.json"}
assert oct((out / "catalog.json").stat().st_mode & 0o7777) == "0o444"
Loading