diff --git a/hermes_cli/kanban_worker_log.py b/hermes_cli/kanban_worker_log.py index c4eed26ed8..d08d399fd7 100644 --- a/hermes_cli/kanban_worker_log.py +++ b/hermes_cli/kanban_worker_log.py @@ -74,6 +74,14 @@ def open_worker_log(log_path: Path): # Worker output is durable and may quote secrets: never world-readable. Only the other bits # are stripped (a shared-group home keeps group access), and a log created before this fix # is tightened on its next open. + # A private log owned by another account (shared-group home) is reopened as is: chmod would + # raise EPERM. One that is still world-readable fails closed, with the descriptor released. fd = os.open(log_path, os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0), 0o660) - os.chmod(log_path, os.fstat(fd).st_mode & 0o7770) + try: + mode = os.fstat(fd).st_mode + if mode & 0o007: + os.chmod(log_path, mode & 0o7770) + except BaseException: + os.close(fd) + raise return os.fdopen(fd, "ab") diff --git a/tests/hermes_cli/test_kanban_worker_log_shared_owner.py b/tests/hermes_cli/test_kanban_worker_log_shared_owner.py new file mode 100644 index 0000000000..39652e3447 --- /dev/null +++ b/tests/hermes_cli/test_kanban_worker_log_shared_owner.py @@ -0,0 +1,67 @@ +"""Reopening a worker log owned by another account in a shared-group kanban home (#63594).""" + +from __future__ import annotations + +import errno +import os +from pathlib import Path + +import pytest + +from hermes_cli import kanban_worker_log as kwl + +pytestmark = pytest.mark.platforms("posix") + + +def _as_non_owner(monkeypatch: pytest.MonkeyPatch) -> list[int]: + """Make chmod behave as for a file another account owns; track descriptors opened.""" + opened: list[int] = [] + real_open = os.open + + def _open(*args, **kwargs): + fd = real_open(*args, **kwargs) + opened.append(fd) + return fd + + def _chmod(*_args, **_kwargs): + raise PermissionError(errno.EPERM, "Operation not permitted") + + monkeypatch.setattr(kwl.os, "open", _open) + monkeypatch.setattr(kwl.os, "chmod", _chmod) + monkeypatch.setattr(kwl, "worker_log_rotation_config", lambda: (1 << 20, 1)) + return opened + + +def _is_open(fd: int) -> bool: + try: + os.fstat(fd) + except OSError: + return False + return True + + +def test_private_group_writable_log_of_another_owner_reopens(tmp_path: Path, monkeypatch): + log = tmp_path / "t.log" + log.write_bytes(b"earlier run\n") + log.chmod(0o660) + _as_non_owner(monkeypatch) + + with kwl.open_worker_log(log) as f: + f.write(b"next run\n") + + assert log.read_bytes() == b"earlier run\nnext run\n" + + +def test_world_readable_log_that_cannot_be_tightened_fails_closed_without_leaking( + tmp_path: Path, monkeypatch +): + log = tmp_path / "t.log" + log.write_bytes(b"earlier run\n") + log.chmod(0o664) + opened = _as_non_owner(monkeypatch) + + with pytest.raises(PermissionError): + kwl.open_worker_log(log) + + assert opened and not _is_open(opened[-1]) + assert log.read_bytes() == b"earlier run\n"