Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

fix(tier3): stage over existing trees on older glibc and explain bwrap failures (#267)

Narendran Raghavan8d8dc250932a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd454422..bd12b384 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -451,6 +451,23 @@ All notable changes to SkillEvaluator are documented in this file.
treated as a standard agent. Scores were already cleared for these
conditions, and observed rewards still determine their own metric set.
+- Tier 3 staging no longer fails with `chmod: cannot use dir_fd and
+ follow_symlinks together` when it replaces or merges into an existing
+ directory or file on Linux hosts whose glibc cannot change a mode without
+ following symlinks (glibc before 2.32, or newer glibc without `/proc`). This
+ affected, for example, `init-custom-grader` and `init-harbor-task` over an
+ existing `evals/` directory. Staging still changes modes without following
+ links where the platform supports it. Elsewhere it opens the entry without
+ following links, confirms it is the entry it checked, and changes the mode
+ through that open descriptor, so a link swapped in is refused instead of
+ followed. Only an entry that cannot be opened, such as one its owner cannot
+ read, is still changed by name, with an identity check afterwards.
+
+- Local-mode sandbox errors now include Bubblewrap's own failure line when its
+ startup probe fails, note that `pivot_root: Operation not permitted` can mean
+ an enclosing container's seccomp profile blocks Bubblewrap, and suggest
+ `SKILLEVALUATOR_LOCAL_SANDBOX=prefer` alongside `off`.
+
- PII email scans recognize all RFC 2606 reserved domains, including their
subdomains, mixed-case forms, trailing dots, and prose ellipses. A local-part
boundary prevents quadratic rescanning of long excluded addresses. Ordinary
diff --git a/docs/agents-and-sandboxes.mdx b/docs/agents-and-sandboxes.mdx
index d396a047..249c1869 100644
--- a/docs/agents-and-sandboxes.mdx
+++ b/docs/agents-and-sandboxes.mdx
@@ -615,6 +615,14 @@ Full semantics for each variable are in
verifies the sandbox backend and the installed agent CLIs before you commit to
a run.
+When Bubblewrap is installed but fails its startup probe, the error includes
+Bubblewrap's own failure line. Inside a container,
+`pivot_root: Operation not permitted` can mean the container's seccomp profile
+blocks Bubblewrap; only the options the container was launched with can change
+that. On such a host, use `--env-mode docker` where a Docker daemon is
+available, or set `SKILLEVALUATOR_LOCAL_SANDBOX=prefer` (advisory-only
+guardrails) or `off` for skills you fully trust.
+
## Workspace modes
SkillEvaluator stages the agent's workspace itself, in both arms, so the
diff --git a/src/skillevaluator/tier3/harbor/local_sandbox.py b/src/skillevaluator/tier3/harbor/local_sandbox.py
index b071424f..13158dc6 100644
--- a/src/skillevaluator/tier3/harbor/local_sandbox.py
+++ b/src/skillevaluator/tier3/harbor/local_sandbox.py
@@ -274,8 +274,11 @@ def detect(mode: str = "require") -> Sandbox:
# cwd set to the writable workspace, so a relative PATH entry could
# pick up a launcher planted there by an earlier sandboxed command.
bwrap = str(Path(bwrap).resolve())
- if bwrap and _userns_enabled() and _bwrap_smoke_test(bwrap):
- return Sandbox(SandboxPlan("bubblewrap", "kernel", f"bubblewrap at {bwrap}", bwrap))
+ smoke_detail = ""
+ if bwrap and _userns_enabled():
+ smoke_ok, smoke_detail = _bwrap_smoke_result(bwrap)
+ if smoke_ok:
+ return Sandbox(SandboxPlan("bubblewrap", "kernel", f"bubblewrap at {bwrap}", bwrap))
if not bwrap:
reason = "bubblewrap not installed (install the bubblewrap package)"
elif not _userns_enabled():
@@ -285,6 +288,13 @@ def detect(mode: str = "require") -> Sandbox:
)
else:
reason = f"bubblewrap at {bwrap} failed its smoke test"
+ if smoke_detail:
+ reason = f"{reason} ({smoke_detail})"
+ if "pivot_root: operation not permitted" in smoke_detail.casefold():
+ reason = (
+ f"{reason}; this can mean an enclosing container's seccomp profile blocks "
+ "bubblewrap, which only the container's launch configuration can change"
+ )
elif system == "Darwin":
if _seatbelt_available() and _seatbelt_smoke_test():
# Seatbelt confines the filesystem (reads/writes) and network at the
@@ -307,8 +317,9 @@ def detect(mode: str = "require") -> Sandbox:
if mode == "require":
raise SandboxUnavailable(
f"Harbor local mode requires an OS-level sandbox, but none is usable: {reason}. "
- f"Fix the host, use --env-mode docker, or set {SANDBOX_MODE_ENV}=off to run "
- "without a sandbox for skills you fully trust."
+ "Fix the host, use --env-mode docker where a Docker daemon is available, "
+ f"set {SANDBOX_MODE_ENV}=prefer to continue with advisory-only guardrails, "
+ f"or set {SANDBOX_MODE_ENV}=off to run without a sandbox for skills you fully trust."
)
return Sandbox(SandboxPlan("none", "advisory-only", reason))
@@ -459,14 +470,29 @@ def _bwrap_smoke_argv(bwrap: str) -> list[str]:
return argv
+def _bwrap_smoke_result(bwrap: str) -> tuple[bool, str]:
+ """Run the probe, returning success plus bubblewrap's own failure line.
+
+ The detail separates causes that otherwise share one message:
+ ``pivot_root: Operation not permitted`` can come from a container seccomp
+ profile, which no sysctl or capability change inside the container lifts.
+ """
+ try:
+ result = subprocess.run(_bwrap_smoke_argv(bwrap), capture_output=True, timeout=5)
+ except subprocess.TimeoutExpired as exc:
+ return False, f"timed out after {exc.timeout:g}s"
+ except (OSError, subprocess.SubprocessError) as exc:
+ return False, str(exc)
+ if result.returncode == 0:
+ return True, ""
+ lines = result.stderr.decode("utf-8", "replace").strip().splitlines()
+ return False, lines[-1].strip() if lines else f"exit status {result.returncode}"
+
+
def _bwrap_smoke_test(bwrap: str) -> bool:
# Some hosts have bwrap installed but user namespaces refused at runtime
# (containers, seccomp policies); prove the launcher actually works.
- try:
- result = subprocess.run(_bwrap_smoke_argv(bwrap), capture_output=True, timeout=5)
- return result.returncode == 0
- except (OSError, subprocess.SubprocessError):
- return False
+ return _bwrap_smoke_result(bwrap)[0]
def _seatbelt_available() -> bool:
diff --git a/src/skillevaluator/tier3/harbor/secure_copy.py b/src/skillevaluator/tier3/harbor/secure_copy.py
index 98157665..d7d3ff25 100644
--- a/src/skillevaluator/tier3/harbor/secure_copy.py
+++ b/src/skillevaluator/tier3/harbor/secure_copy.py
@@ -45,6 +45,23 @@ _FILE_FLAGS = (
| getattr(os, "O_NONBLOCK", 0)
| getattr(os, "O_NOCTTY", 0)
)
+# Mode changes by descriptor when fchmodat(AT_SYMLINK_NOFOLLOW) is rejected.
+_CHMOD_BY_DESCRIPTOR = hasattr(os, "O_NOFOLLOW") and hasattr(os, "fchmod")
+_CHMOD_OPEN_FLAGS = (
+ os.O_RDONLY
+ | getattr(os, "O_NOFOLLOW", 0)
+ | getattr(os, "O_NONBLOCK", 0)
+ | getattr(os, "O_CLOEXEC", 0)
+ | getattr(os, "O_NOCTTY", 0)
+)
+# open(O_NOFOLLOW) of a final symlink fails with ELOOP (Linux, macOS), EMLINK
+# (FreeBSD) or EFTYPE (NetBSD).
+_NOFOLLOW_LINK_ERRNOS = frozenset(
+ code for code in (errno.ELOOP, errno.EMLINK, getattr(errno, "EFTYPE", None)) if code is not None
+)
+_CHMOD_OPEN_PERMISSION_ERRNOS = frozenset({errno.EACCES, errno.EPERM})
+_CHMOD_LINK_REFUSAL = "refusing to change the mode of a staging symlink or reparse point"
+_CHMOD_CHANGED = "staging entry changed while its mode was being changed"
_WINDOWS_CHMOD_SEMANTICS = os.name == "nt"
_PATH_DESCRIPTOR_IDENTITIES_COMPARABLE = os.name == "posix"
_DESCRIPTOR_BACKEND = (
@@ -825,6 +842,77 @@ def _destination_metadata(parent_descriptor: int, name: str) -> os.stat_result |
return None
+def _names_link(parent_descriptor: int, name: str) -> bool:
+ try:
+ return _is_link(os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False))
+ except OSError:
+ return False
+
+
+def _fchmod_opened_entry(parent_descriptor: int, name: str, mode: int, named: os.stat_result) -> bool:
+ """Change ``name``'s mode through a no-follow descriptor that matches ``named``.
+
+ Returns False only when the entry cannot be opened for a permission reason
+ (for example an entry its owner cannot read), so the caller can fall back to
+ a checked change by name. A link at ``name`` is refused, never followed.
+ """
+
+ flags = _CHMOD_OPEN_FLAGS
+ if stat.S_ISDIR(named.st_mode):
+ flags |= getattr(os, "O_DIRECTORY", 0)
+ try:
+ descriptor = os.open(name, flags, dir_fd=parent_descriptor)
+ except OSError as exc:
+ if exc.errno in _NOFOLLOW_LINK_ERRNOS:
+ raise UnsafeStagingError(_CHMOD_LINK_REFUSAL) from exc
+ if exc.errno in _CHMOD_OPEN_PERMISSION_ERRNOS:
+ return False
+ if exc.errno == errno.ENOTDIR:
+ # macOS reports O_DIRECTORY | O_NOFOLLOW on a link as ENOTDIR, not ELOOP.
+ refusal = _CHMOD_LINK_REFUSAL if _names_link(parent_descriptor, name) else _CHMOD_CHANGED
+ raise UnsafeStagingError(refusal) from exc
+ raise
+ try:
+ opened = os.fstat(descriptor)
+ if (opened.st_dev, opened.st_ino) != (named.st_dev, named.st_ino):
+ raise UnsafeStagingError(_CHMOD_CHANGED)
+ os.fchmod(descriptor, mode)
+ finally:
+ os.close(descriptor)
+ return True
+
+
+def _chmod_named_entry(parent_descriptor: int, name: str, mode: int) -> None:
+ """Change a named entry's mode without following a final link.
+
+ CPython has no ``lchmod`` on Linux and maps ``dir_fd`` plus ``follow_symlinks=False``
+ to ``fchmodat(AT_SYMLINK_NOFOLLOW)``, which glibc before 2.32 (and newer glibc
+ without ``/proc``) rejects, surfacing as ``ValueError``. The no-follow call is
+ used wherever it works. Otherwise a no-follow stat refuses a link, and the
+ entry is opened with ``O_NOFOLLOW``, matched to that stat by device and inode,
+ and changed with ``fchmod``, so a link swapped in after the stat is refused
+ instead of followed. A plain change by name, followed by a device and inode
+ re-check, remains only for an entry that cannot be opened for a permission
+ reason and for platforms without ``O_NOFOLLOW``. Callers re-check identity
+ afterwards as well.
+ """
+
+ try:
+ os.chmod(name, mode, dir_fd=parent_descriptor, follow_symlinks=False)
+ return
+ except (NotImplementedError, ValueError):
+ pass
+ named = os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False)
+ if _is_link(named):
+ raise UnsafeStagingError(_CHMOD_LINK_REFUSAL)
+ if _CHMOD_BY_DESCRIPTOR and _fchmod_opened_entry(parent_descriptor, name, mode, named):
+ return
+ os.chmod(name, mode, dir_fd=parent_descriptor)
+ current = os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False)
+ if _is_link(current) or (current.st_dev, current.st_ino) != (named.st_dev, named.st_ino):
+ raise UnsafeStagingError(_CHMOD_CHANGED)
+
+
def _remove_tree_at(
parent_descriptor: int,
name: str,
@@ -843,7 +931,7 @@ def _remove_tree_at(
raise UnsafeStagingError("refusing to remove an unsafe staging entry")
os.unlink(name, dir_fd=parent_descriptor)
return
- os.chmod(name, 0o700, dir_fd=parent_descriptor, follow_symlinks=False)
+ _chmod_named_entry(parent_descriptor, name, 0o700)
writable = os.stat(name, dir_fd=parent_descriptor, follow_symlinks=False)
if _is_link(writable) or (writable.st_dev, writable.st_ino) != (metadata.st_dev, metadata.st_ino):
raise UnsafeStagingError("staging directory changed while making it removable")
@@ -1303,7 +1391,7 @@ def _prepare_moved_backup(
):
raise UnsafeStagingError(f"destination changed while it was moved to backup: {backup_path}")
private_mode = 0o700 if kind == "directory" else 0o600
- os.chmod(backup_name, private_mode, dir_fd=parent_descriptor, follow_symlinks=False)
+ _chmod_named_entry(parent_descriptor, backup_name, private_mode)
private = os.stat(backup_name, dir_fd=parent_descriptor, follow_symlinks=False)
if (
_is_link(private)
diff --git a/tests/test_harbor_local_sandbox.py b/tests/test_harbor_local_sandbox.py
index 8d6955e0..063da947 100644
--- a/tests/test_harbor_local_sandbox.py
+++ b/tests/test_harbor_local_sandbox.py
@@ -49,7 +49,7 @@ class TestDetect:
monkeypatch.setattr(local_sandbox.platform, "system", lambda: "Linux")
monkeypatch.setattr(local_sandbox.shutil, "which", lambda _name: "/usr/bin/bwrap")
monkeypatch.setattr(local_sandbox, "_userns_enabled", lambda: True)
- monkeypatch.setattr(local_sandbox, "_bwrap_smoke_test", lambda _bwrap: True)
+ monkeypatch.setattr(local_sandbox, "_bwrap_smoke_result", lambda _bwrap: (True, ""))
sandbox = local_sandbox.detect("require")
assert sandbox.plan.backend == "bubblewrap"
assert sandbox.plan.strength == "kernel"
@@ -115,6 +115,74 @@ class TestDetect:
with pytest.raises(ValueError):
local_sandbox.detect("bogus")
+ def test_smoke_failure_detail_reaches_the_reason(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(local_sandbox.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(local_sandbox.shutil, "which", lambda _name: "/usr/bin/bwrap")
+ monkeypatch.setattr(local_sandbox, "_userns_enabled", lambda: True)
+ monkeypatch.setattr(
+ local_sandbox,
+ "_bwrap_smoke_result",
+ lambda _bwrap: (False, "bwrap: pivot_root: Operation not permitted"),
+ )
+
+ sandbox = local_sandbox.detect("prefer")
+
+ # Without bubblewrap's own line every container-policy failure reads like
+ # the sysctl causes detect() names for the other branches.
+ assert "pivot_root: Operation not permitted" in sandbox.plan.reason
+ assert "seccomp" in sandbox.plan.reason
+
+ def test_other_pivot_root_failure_does_not_claim_seccomp(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(local_sandbox.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(local_sandbox.shutil, "which", lambda _name: "/usr/bin/bwrap")
+ monkeypatch.setattr(local_sandbox, "_userns_enabled", lambda: True)
+ monkeypatch.setattr(
+ local_sandbox,
+ "_bwrap_smoke_result",
+ lambda _bwrap: (False, "bwrap: pivot_root: Invalid argument"),
+ )
+
+ with pytest.raises(local_sandbox.SandboxUnavailable) as excinfo:
+ local_sandbox.detect("require")
+
+ message = str(excinfo.value)
+ assert "pivot_root: Invalid argument" in message
+ assert "seccomp" not in message
+
+ def test_require_mode_remediation_offers_prefer_and_off(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(local_sandbox.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(local_sandbox.shutil, "which", lambda _name: None)
+
+ with pytest.raises(local_sandbox.SandboxUnavailable) as excinfo:
+ local_sandbox.detect("require")
+
+ message = str(excinfo.value)
+ # "off" drops every guardrail; "prefer" keeps the advisory ones and must
+ # be offered alongside it.
+ assert f"{local_sandbox.SANDBOX_MODE_ENV}=prefer" in message
+ assert f"{local_sandbox.SANDBOX_MODE_ENV}=off" in message
+
+ def test_smoke_result_reports_launch_failure_detail(self) -> None:
+ ok, detail = local_sandbox._bwrap_smoke_result("/nonexistent/bwrap")
+
+ assert ok is False
+ assert detail
+
+ def test_smoke_result_returns_last_stderr_line(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ completed = subprocess.CompletedProcess(
+ args=["bwrap"],
+ returncode=1,
+ stdout=b"",
+ stderr=b"warning: ignored\nbwrap: pivot_root: Operation not permitted\n",
+ )
+ monkeypatch.setattr(local_sandbox.subprocess, "run", lambda *_args, **_kwargs: completed)
+
+ assert local_sandbox._bwrap_smoke_result("/usr/bin/bwrap") == (
+ False,
+ "bwrap: pivot_root: Operation not permitted",
+ )
+ assert local_sandbox._bwrap_smoke_test("/usr/bin/bwrap") is False
+
def test_bwrap_smoke_argv_binds_lib_dirs(self) -> None:
# Regression: the smoke test must bind the ELF-interpreter dirs, not just
# /usr, or a dynamically-linked /usr/bin/true fails ENOENT on usr-merged
@@ -143,7 +211,7 @@ class TestDetect:
monkeypatch.setattr(local_sandbox.platform, "system", lambda: "Linux")
monkeypatch.setattr(local_sandbox.shutil, "which", lambda _name: str(link))
monkeypatch.setattr(local_sandbox, "_userns_enabled", lambda: True)
- monkeypatch.setattr(local_sandbox, "_bwrap_smoke_test", lambda bwrap: probes.append(bwrap) is None)
+ monkeypatch.setattr(local_sandbox, "_bwrap_smoke_result", lambda bwrap: (probes.append(bwrap) is None, ""))
sandbox = local_sandbox.detect("require")
# A later PATH lookup must not change which launcher runs.
@@ -172,7 +240,7 @@ class TestDetect:
monkeypatch.setattr(local_sandbox.platform, "system", lambda: "Linux")
monkeypatch.setattr(local_sandbox.shutil, "which", lambda _name: "bin/bwrap")
monkeypatch.setattr(local_sandbox, "_userns_enabled", lambda: True)
- monkeypatch.setattr(local_sandbox, "_bwrap_smoke_test", lambda _bwrap: True)
+ monkeypatch.setattr(local_sandbox, "_bwrap_smoke_result", lambda _bwrap: (True, ""))
sandbox = local_sandbox.detect("require")
@@ -206,7 +274,7 @@ class TestDetect:
monkeypatch.setenv("PATH", host_path)
monkeypatch.setattr(local_sandbox.platform, "system", lambda: "Linux")
monkeypatch.setattr(local_sandbox, "_userns_enabled", lambda: True)
- monkeypatch.setattr(local_sandbox, "_bwrap_smoke_test", lambda _bwrap: True)
+ monkeypatch.setattr(local_sandbox, "_bwrap_smoke_result", lambda _bwrap: (True, ""))
sandbox = local_sandbox.detect("require")
argv = sandbox.wrap(
diff --git a/tests/test_harbor_secure_copy.py b/tests/test_harbor_secure_copy.py
index f40bdca7..59a98ae7 100644
--- a/tests/test_harbor_secure_copy.py
+++ b/tests/test_harbor_secure_copy.py
@@ -15,6 +15,7 @@ import stat
import tempfile
import threading
import time
+from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as FutureTimeoutError
from pathlib import Path
@@ -537,6 +538,310 @@ def test_exact_replacement_and_merge_modes_are_mutually_exclusive(tmp_path: Path
_copytree_secure(source, tmp_path / "destination", dirs_exist_ok=True, replace_existing=True)
+def _reject_chmod_without_follow(monkeypatch: pytest.MonkeyPatch, module: object) -> list[str]:
+ # CPython raises this when fchmodat(AT_SYMLINK_NOFOLLOW) is unsupported, as on
+ # Linux with glibc before 2.32 or without /proc. CI hosts support the flag.
+ original = os.chmod
+ rejected: list[str] = []
+
+ def chmod(path: object, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None:
+ if dir_fd is not None and not follow_symlinks:
+ rejected.append(os.fspath(path))
+ raise ValueError("chmod: cannot use dir_fd and follow_symlinks together")
+ original(path, mode, dir_fd=dir_fd, follow_symlinks=follow_symlinks)
+
+ monkeypatch.setattr(module.os, "chmod", chmod)
+ return rejected
+
+
[email protected]("mode", ["merge", "replace"])
+def test_existing_destination_publish_survives_chmod_without_nofollow_support(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ mode: str,
+) -> None:
+ module = importlib.import_module("skillevaluator.tier3.harbor.secure_copy")
+ if not module._DESCRIPTOR_BACKEND:
+ pytest.skip("descriptor-relative staging is unavailable")
+ source = tmp_path / "source"
+ source.mkdir()
+ (source / "new.txt").write_text("new", encoding="utf-8")
+ destination = tmp_path / "destination"
+ locked = destination / "locked"
+ locked.mkdir(parents=True)
+ (locked / "old.txt").write_text("old", encoding="utf-8")
+ # A read-only directory is what makes the chmod before removal load-bearing.
+ locked.chmod(0o500)
+ rejected = _reject_chmod_without_follow(monkeypatch, module)
+
+ try:
+ if mode == "merge":
+ module.copytree_secure(source, destination, dirs_exist_ok=True)
+ else:
+ module.copytree_secure(source, destination, replace_existing=True)
+ finally:
+ for path in (locked, *tmp_path.glob(".destination.backup-*/locked")):
+ if path.is_dir():
+ path.chmod(0o700)
+
+ assert rejected
+ assert (destination / "new.txt").read_text(encoding="utf-8") == "new"
+ if mode == "merge":
+ assert (locked / "old.txt").read_text(encoding="utf-8") == "old"
+ else:
+ assert sorted(path.name for path in destination.iterdir()) == ["new.txt"]
+ assert not list(tmp_path.glob(".destination.backup-*"))
+
+
+def test_existing_file_replacement_survives_chmod_without_nofollow_support(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ module = importlib.import_module("skillevaluator.tier3.harbor.secure_copy")
+ if not module._DESCRIPTOR_BACKEND:
+ pytest.skip("descriptor-relative staging is unavailable")
+ source = tmp_path / "source.txt"
+ source.write_text("new", encoding="utf-8")
+ destination = tmp_path / "destination.txt"
+ destination.write_text("old", encoding="utf-8")
+ rejected = _reject_chmod_without_follow(monkeypatch, module)
+
+ module.copy_file_secure(source, destination, allowed_root=tmp_path)
+
+ assert rejected
+ assert destination.read_text(encoding="utf-8") == "new"
+ assert not list(tmp_path.glob(".destination.txt.backup-*"))
+
+
+def test_chmod_fallback_refuses_a_link_without_following_it(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ module = importlib.import_module("skillevaluator.tier3.harbor.secure_copy")
+ if not module._DESCRIPTOR_BACKEND:
+ pytest.skip("descriptor-relative staging is unavailable")
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ outside.chmod(0o755)
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ (parent / "entry").symlink_to(outside, target_is_directory=True)
+ rejected = _reject_chmod_without_follow(monkeypatch, module)
+
+ descriptor = os.open(parent, module._DIRECTORY_FLAGS)
+ try:
+ with pytest.raises(module.UnsafeStagingError, match="symlink"):
+ module._chmod_named_entry(descriptor, "entry", 0o700)
+ finally:
+ os.close(descriptor)
+
+ assert rejected == ["entry"]
+ assert stat.S_IMODE(outside.stat().st_mode) == 0o755
+
+
+def _descriptor_chmod_module() -> object:
+ module = importlib.import_module("skillevaluator.tier3.harbor.secure_copy")
+ if not module._DESCRIPTOR_BACKEND or not module._CHMOD_BY_DESCRIPTOR:
+ pytest.skip("descriptor-relative staging with O_NOFOLLOW is unavailable")
+ return module
+
+
+def _record_chmod_fallback(monkeypatch: pytest.MonkeyPatch, module: object) -> SimpleNamespace:
+ """Reject no-follow chmod, then record chmod-by-name and fchmod calls."""
+ calls = SimpleNamespace(rejected=_reject_chmod_without_follow(monkeypatch, module), by_name=[], fchmod=[])
+ rejecting_chmod = module.os.chmod
+ original_fchmod = os.fchmod
+
+ def chmod(path: object, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None:
+ if dir_fd is not None and follow_symlinks:
+ calls.by_name.append(os.fspath(path))
+ rejecting_chmod(path, mode, dir_fd=dir_fd, follow_symlinks=follow_symlinks)
+
+ def fchmod(descriptor: int, mode: int) -> None:
+ calls.fchmod.append((os.fstat(descriptor).st_ino, mode))
+ original_fchmod(descriptor, mode)
+
+ monkeypatch.setattr(module.os, "chmod", chmod)
+ monkeypatch.setattr(module.os, "fchmod", fchmod)
+ return calls
+
+
+def _swap_after_first_entry_stat(monkeypatch: pytest.MonkeyPatch, module: object, swap: Callable[[], None]) -> None:
+ # Emulate a same-name replacement landing between the helper's no-follow stat
+ # and whatever it does next with the name.
+ original_stat = os.stat
+ pending = [swap]
+
+ def racing_stat(path: object, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> os.stat_result:
+ result = original_stat(path, dir_fd=dir_fd, follow_symlinks=follow_symlinks)
+ if pending and dir_fd is not None and not follow_symlinks and path == "entry":
+ pending.pop()()
+ return result
+
+ monkeypatch.setattr(module.os, "stat", racing_stat)
+
+
+def _chmod_entry(module: object, parent: Path, mode: int) -> None:
+ descriptor = os.open(parent, module._DIRECTORY_FLAGS)
+ try:
+ module._chmod_named_entry(descriptor, "entry", mode)
+ finally:
+ os.close(descriptor)
+
+
[email protected]("kind", ["directory", "file"])
+def test_chmod_fallback_changes_mode_through_the_opened_descriptor(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ kind: str,
+) -> None:
+ module = _descriptor_chmod_module()
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ entry = parent / "entry"
+ if kind == "directory":
+ entry.mkdir()
+ entry.chmod(0o500)
+ target = 0o700
+ else:
+ entry.write_text("old", encoding="utf-8")
+ entry.chmod(0o644)
+ target = 0o600
+ inode = entry.stat().st_ino
+ calls = _record_chmod_fallback(monkeypatch, module)
+
+ _chmod_entry(module, parent, target)
+
+ assert calls.rejected == ["entry"]
+ assert calls.fchmod == [(inode, target)]
+ assert calls.by_name == []
+ assert stat.S_IMODE(entry.stat().st_mode) == target
+
+
[email protected]("kind", ["directory", "file"])
+def test_chmod_fallback_refuses_a_link_swapped_in_after_the_stat(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ kind: str,
+) -> None:
+ module = _descriptor_chmod_module()
+ outside = tmp_path / "outside"
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ entry = parent / "entry"
+ if kind == "directory":
+ outside.mkdir()
+ entry.mkdir()
+ else:
+ outside.write_text("outside", encoding="utf-8")
+ entry.write_text("entry", encoding="utf-8")
+ outside.chmod(0o755)
+
+ def swap() -> None:
+ entry.rename(parent / "moved")
+ entry.symlink_to(outside, target_is_directory=kind == "directory")
+
+ calls = _record_chmod_fallback(monkeypatch, module)
+ _swap_after_first_entry_stat(monkeypatch, module, swap)
+
+ with pytest.raises(module.UnsafeStagingError, match="symlink"):
+ _chmod_entry(module, parent, 0o700)
+
+ # A chmod by name here would follow the link and change the outside mode.
+ assert calls.by_name == []
+ assert calls.fchmod == []
+ assert stat.S_IMODE(outside.stat().st_mode) == 0o755
+
+
[email protected]("replacement", ["directory", "file"])
+def test_chmod_fallback_refuses_an_entry_replaced_after_the_stat(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ replacement: str,
+) -> None:
+ module = _descriptor_chmod_module()
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ entry = parent / "entry"
+ entry.mkdir()
+ entry.chmod(0o500)
+
+ def swap() -> None:
+ entry.rename(parent / "moved")
+ if replacement == "directory":
+ entry.mkdir()
+ entry.chmod(0o555)
+ else:
+ entry.write_text("swapped", encoding="utf-8")
+ entry.chmod(0o555)
+
+ calls = _record_chmod_fallback(monkeypatch, module)
+ _swap_after_first_entry_stat(monkeypatch, module, swap)
+
+ with pytest.raises(module.UnsafeStagingError, match="changed"):
+ _chmod_entry(module, parent, 0o700)
+
+ assert calls.by_name == []
+ assert calls.fchmod == []
+ assert stat.S_IMODE((parent / "moved").stat().st_mode) == 0o500
+ assert stat.S_IMODE(entry.stat().st_mode) == 0o555
+
+
[email protected]("code", [errno.EACCES, errno.EPERM], ids=["EACCES", "EPERM"])
+def test_chmod_fallback_keeps_checked_chmod_by_name_when_entry_cannot_be_opened(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ code: int,
+) -> None:
+ module = _descriptor_chmod_module()
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ entry = parent / "entry"
+ entry.mkdir()
+ entry.chmod(0o300)
+ calls = _record_chmod_fallback(monkeypatch, module)
+ original_open = os.open
+ refused: list[str] = []
+
+ def unreadable_open(path: object, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int:
+ # The owner may chmod an entry it cannot read; root would bypass a real
+ # 0o000/0o300 mode, so the refusal is injected.
+ if dir_fd is not None and path == "entry":
+ refused.append(path)
+ raise PermissionError(code, os.strerror(code), path)
+ return original_open(path, flags, mode, dir_fd=dir_fd)
+
+ monkeypatch.setattr(module.os, "open", unreadable_open)
+
+ _chmod_entry(module, parent, 0o700)
+
+ assert refused == ["entry"]
+ assert calls.fchmod == []
+ assert calls.by_name == ["entry"]
+ assert stat.S_IMODE(entry.stat().st_mode) == 0o700
+
+
+def test_chmod_fallback_without_nofollow_open_keeps_checked_chmod_by_name(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ module = _descriptor_chmod_module()
+ parent = tmp_path / "parent"
+ parent.mkdir()
+ entry = parent / "entry"
+ entry.mkdir()
+ entry.chmod(0o500)
+ calls = _record_chmod_fallback(monkeypatch, module)
+ # Platforms without os.O_NOFOLLOW (native Windows) keep the checked call by name.
+ monkeypatch.setattr(module, "_CHMOD_BY_DESCRIPTOR", False)
+
+ _chmod_entry(module, parent, 0o700)
+
+ assert calls.fchmod == []
+ assert calls.by_name == ["entry"]
+ assert stat.S_IMODE(entry.stat().st_mode) == 0o700
+
+
def test_copy_file_rejects_source_and_destination_links_and_hardlinks(tmp_path: Path) -> None:
outside = tmp_path / "outside.txt"
outside.write_text("outside-canary", encoding="utf-8")