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): contain local Harbor directory transfers (#493)

Narendran Raghavan69584dd959d6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c237d316..3cf33d99 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -545,6 +545,11 @@ All notable changes to SkillEvaluator are documented in this file.
### Fixed
+- Harbor local mode keeps exclusion and filtered download archives inside the
+ allowed run directory, so pinned Harbor 0.25 transfers copy selected file
+ contents without granting host `/tmp` access. Filters retain exact protected
+ paths, and failed scans or unsafe destinations leave outputs untouched.
+
- Configure CLI stdout to replace characters that its encoding cannot
represent, so reports and root help complete on legacy Windows code pages.
JSON dataset previews and validation output preserve Unicode values, using
diff --git a/src/skillevaluator/tier3/harbor/local_environment.py b/src/skillevaluator/tier3/harbor/local_environment.py
index e2b740db..9214ea71 100644
--- a/src/skillevaluator/tier3/harbor/local_environment.py
+++ b/src/skillevaluator/tier3/harbor/local_environment.py
@@ -18,6 +18,7 @@ import signal
import stat
import subprocess
import sys
+import tarfile
import tempfile
from collections.abc import Sequence
from pathlib import Path, PurePosixPath
@@ -870,6 +871,22 @@ class SkillEvaluatorLocalEnvironment(BaseEnvironment):
self._reject_logs_parent_transfer(self._resolve_path(source_dir))
await super().download_dir_with_exclusions(source_dir=source_dir, target_dir=target_dir, exclude=exclude)
+ async def _download_dir_with_exclusions_impl(
+ self,
+ *,
+ source_dir: str,
+ target_dir: Path | str,
+ exclude: list[str],
+ service: str | None,
+ ) -> None:
+ if not self.is_main_service(service):
+ from harbor.environments.base import ServiceOperationsUnsupportedError
+
+ raise ServiceOperationsUnsupportedError(self._service_unsupported_message(service))
+ await self._download_local_directory(
+ source_dir=source_dir, target_dir=target_dir, exclude=exclude, filter_files=False
+ )
+
async def download_dir_filtered(
self,
*,
@@ -880,10 +897,111 @@ class SkillEvaluatorLocalEnvironment(BaseEnvironment):
protect: Sequence[str] | None = None,
) -> None:
self._reject_logs_parent_transfer(self._resolve_path(source_dir))
- await super().download_dir_filtered(
- source_dir=source_dir, target_dir=target_dir, include=include, exclude=exclude, protect=protect
+ await self._download_local_directory(
+ source_dir=source_dir,
+ target_dir=target_dir,
+ include=include,
+ exclude=exclude,
+ protect=protect,
+ filter_files=True,
)
+ async def _download_local_directory(
+ self,
+ *,
+ source_dir: str,
+ target_dir: Path | str,
+ include: Sequence[str] | None = None,
+ exclude: Sequence[str] | None = None,
+ protect: Sequence[str] | None = None,
+ filter_files: bool,
+ ) -> None:
+ """Keep Harbor's directory-transfer scratch files within the local run."""
+ from harbor.environments.base import transfer_tar_filter
+ from harbor.utils.path_filter import filter_paths_by_patterns
+
+ source = self._resolve_path(source_dir)
+ if not self._path_is_within_allowed_local_roots(source):
+ raise ValueError(f"local mode download source is outside the run directory: {source_dir}")
+ self._reject_logs_parent_transfer(source)
+ source_metadata = source.lstat()
+ if not stat.S_ISDIR(source_metadata.st_mode) or stat_is_link_or_reparse(source_metadata):
+ raise ValueError("local directory transfer source must be a non-linked directory")
+ source_root = source.resolve()
+ selected: list[str] | None = None
+ if filter_files:
+
+ def raise_walk_error(error: OSError) -> None:
+ raise error
+
+ paths = []
+ for directory, _subdirectories, filenames in os.walk(source, followlinks=False, onerror=raise_walk_error):
+ for filename in filenames:
+ path = Path(directory) / filename
+ metadata = path.lstat()
+ if stat.S_ISREG(metadata.st_mode) and not stat_is_link_or_reparse(metadata):
+ paths.append(path.relative_to(source).as_posix())
+ paths.sort()
+ selected = filter_paths_by_patterns(paths, include=include, exclude=exclude)
+ protected = set(protect or ()) - set(selected)
+ selected += [path for path in paths if path in protected]
+
+ # The SDK uses host /tmp for its archive/list. That location is outside
+ # local mode's grant, so use a private per-call directory under the run
+ # instead; never change the SDK's module-global transfer directory.
+ temporary_metadata = self._tmp.lstat()
+ if (
+ not self._path_is_within_allowed_local_roots(self._tmp)
+ or not stat.S_ISDIR(temporary_metadata.st_mode)
+ or stat_is_link_or_reparse(temporary_metadata)
+ ):
+ raise ValueError("local directory transfer staging must remain inside the run")
+ with tempfile.TemporaryDirectory(prefix=".hb-local-transfer-", dir=self._tmp) as temporary:
+ staging = Path(temporary)
+ unpacked = staging / "unpacked"
+ unpacked.mkdir()
+ if selected != []:
+ archive = staging / "transfer.tar.gz"
+ # TMPDIR is a protected local-backend value. Refer to it in
+ # the shell instead of feeding host paths through the logical
+ # /workspace rewrite a second time.
+ archive_argument = f'"$TMPDIR"/{shlex.quote(staging.name)}/transfer.tar.gz'
+ if selected is not None:
+ listing = staging / "files.list"
+ # NUL records retain literal newlines/leading dashes. A
+ # ./ prefix also prevents filenames from becoming options.
+ listing.write_bytes(b"".join(os.fsencode("./" + name) + b"\0" for name in selected))
+ listing_argument = f'"$TMPDIR"/{shlex.quote(staging.name)}/files.list'
+ command = f"tar czf {archive_argument} --null -T {listing_argument}"
+ else:
+ patterns = list(exclude or ())
+ if staging.is_relative_to(source_root):
+ patterns.append("./" + staging.relative_to(source_root).as_posix())
+ excludes = " ".join(f"--exclude={shlex.quote(pattern)}" for pattern in patterns)
+ command = f"tar czf {archive_argument} {excludes} ."
+ result = await self.exec(command, cwd=str(source), timeout_sec=600, user="root")
+ if result.return_code != 0:
+ raise RuntimeError(f"Failed to pack local directory transfer (exit code {result.return_code})")
+ with tarfile.open(archive, "r:gz") as transfer:
+ for member in transfer.getmembers():
+ parts = PurePosixPath(member.name)
+ if parts.is_absolute() or ".." in parts.parts or member.issym() or member.islnk():
+ raise ValueError("local directory transfer refuses unsafe paths or linked files")
+ if member.isfile():
+ original = source.joinpath(*parts.parts)
+ metadata = original.lstat()
+ if (
+ not original.resolve().is_relative_to(source_root)
+ or not stat.S_ISREG(metadata.st_mode)
+ or stat_is_link_or_reparse(metadata)
+ or metadata.st_nlink != 1
+ ):
+ raise ValueError("local directory transfer requires regular non-linked files")
+ transfer.extractall(path=unpacked, filter=transfer_tar_filter)
+ # Secure publication retains the existing no-follow/hard-link
+ # restrictions for destinations, including pre-existing outputs.
+ copytree_secure(unpacked, Path(target_dir), dirs_exist_ok=True)
+
async def exec(
self,
command: str,
diff --git a/tests/test_harbor_local_environment.py b/tests/test_harbor_local_environment.py
index 693a5423..152d32bb 100644
--- a/tests/test_harbor_local_environment.py
+++ b/tests/test_harbor_local_environment.py
@@ -476,3 +476,289 @@ def test_real_local_exec_streams_redacted_stdout_and_stderr(
assert secret not in (result.stderr or "")
assert "stdout=" in callback_stdout
assert "stderr=" in callback_stderr
+
+
+def _contained_transfer_payload() -> dict[str, bytes]:
+ return {
+ "keep.txt": b"root contents\n",
+ "omit.log": b"excluded root log\n",
+ "protected.log": b"protected contents\n",
+ "nested/keep.txt": b"nested contents\n",
+ "nested/omit.log": b"excluded nested log\n",
+ "nested/deeper/keep.txt": b"deeper contents\n",
+ "odd [x] ' café.txt": b"literal odd filename\n",
+ "--literal.txt": b"literal leading dash\n",
+ "line\nbreak.txt": b"literal newline filename\n",
+ "blob.bin": bytes(range(256)),
+ }
+
+
+def _contained_transfer_files(root: Path) -> dict[str, bytes]:
+ return {path.relative_to(root).as_posix(): path.read_bytes() for path in root.rglob("*") if path.is_file()}
+
+
[email protected](os.name == "nt", reason="real local subprocess backend requires POSIX")
+ ("exclude", "expected"),
+ [
+ (
+ ["*.log"],
+ {
+ "keep.txt",
+ "nested/keep.txt",
+ "nested/deeper/keep.txt",
+ "odd [x] ' café.txt",
+ "--literal.txt",
+ "line\nbreak.txt",
+ "blob.bin",
+ },
+ ),
+ (
+ ["nested"],
+ {
+ "keep.txt",
+ "omit.log",
+ "protected.log",
+ "odd [x] ' café.txt",
+ "--literal.txt",
+ "line\nbreak.txt",
+ "blob.bin",
+ },
+ ),
+ ],
+)
[email protected]("service_wrapper", [False, True], ids=["direct", "main-service"])
+def test_real_contained_exclusion_download_preserves_contents_and_destination(
+ local_output_environment: SkillEvaluatorLocalEnvironment,
+ tmp_path: Path,
+ exclude: list[str],
+ expected: set[str],
+ service_wrapper: bool,
+) -> None:
+ environment = local_output_environment
+ payload = _contained_transfer_payload()
+ target = tmp_path / "downloaded"
+ target.mkdir()
+ (target / "retained.txt").write_bytes(b"existing unrelated output\n")
+ (target / "keep.txt").write_bytes(b"stale selected output\n")
+
+ async def exercise() -> None:
+ await environment.start()
+ try:
+ source = environment._resolve_path("/workspace/export")
+ for name, data in payload.items():
+ path = source / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ before = set(environment._root.rglob("*"))
+ if service_wrapper:
+ await environment.service_download_dir_with_exclusions(
+ source_dir="/workspace/export", target_dir=target, exclude=exclude, service=None
+ )
+ else:
+ await environment.download_dir_with_exclusions(
+ source_dir="/workspace/export", target_dir=target, exclude=exclude
+ )
+ assert _contained_transfer_files(target) == {
+ **{name: payload[name] for name in expected},
+ "retained.txt": b"existing unrelated output\n",
+ }
+ assert _contained_transfer_files(source) == payload
+ assert set(environment._root.rglob("*")) == before
+ finally:
+ await environment.stop(delete=False)
+
+ asyncio.run(exercise())
+
+
[email protected](os.name == "nt", reason="real local subprocess backend requires POSIX")
[email protected]("no_match", [False, True], ids=["include-exclude-protect", "no-match"])
+def test_real_contained_filtered_download_preserves_literal_names_and_source(
+ local_output_environment: SkillEvaluatorLocalEnvironment, tmp_path: Path, no_match: bool
+) -> None:
+ environment = local_output_environment
+ payload = _contained_transfer_payload()
+ target = tmp_path / "filtered"
+ target.mkdir()
+ (target / "retained.txt").write_bytes(b"existing unrelated output\n")
+
+ async def exercise() -> None:
+ await environment.start()
+ try:
+ source = environment._resolve_path("/workspace/export")
+ for name, data in payload.items():
+ path = source / name
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ before = set(environment._root.rglob("*"))
+ await environment.download_dir_filtered(
+ source_dir="/workspace/export",
+ target_dir=target,
+ include=["no-match/*.yaml"] if no_match else ["*.txt"],
+ exclude=["nested/*"],
+ protect=[] if no_match else ["nested/keep.txt", "protected.log"],
+ )
+ expected = (
+ {}
+ if no_match
+ else {
+ name: payload[name]
+ for name in (
+ "keep.txt",
+ "nested/keep.txt",
+ "protected.log",
+ "odd [x] ' café.txt",
+ "--literal.txt",
+ "line\nbreak.txt",
+ )
+ }
+ )
+ assert _contained_transfer_files(target) == {**expected, "retained.txt": b"existing unrelated output\n"}
+ assert _contained_transfer_files(source) == payload
+ assert set(environment._root.rglob("*")) == before
+ finally:
+ await environment.stop(delete=False)
+
+ asyncio.run(exercise())
+
+
[email protected](os.name == "nt", reason="real local subprocess backend requires POSIX")
[email protected]("method", ["download_dir_with_exclusions", "download_dir_filtered"])
[email protected]("spelling", ["absolute", "mapped-escape", "linked-source"])
+def test_contained_transfer_refuses_outside_source_before_destination_or_staging_mutation(
+ local_output_environment: SkillEvaluatorLocalEnvironment,
+ tmp_path: Path,
+ method: str,
+ spelling: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ environment = local_output_environment
+ outside = tmp_path / "outside-source"
+ outside.mkdir()
+ (outside / "private.txt").write_bytes(b"outside sentinel\n")
+ target = tmp_path / "destination"
+ target.mkdir()
+ (target / "retained.txt").write_bytes(b"destination sentinel\n")
+
+ async def exercise() -> None:
+ await environment.start()
+ try:
+ source = str(outside)
+ if spelling == "mapped-escape":
+ source = "/workspace/../../../outside-source"
+ elif spelling == "linked-source":
+ environment._resolve_path("/workspace/linked").symlink_to(outside, target_is_directory=True)
+ source = "/workspace/linked"
+ before = set(environment._root.rglob("*"))
+ commands: list[str] = []
+ original_exec = environment.exec
+
+ async def observe_exec(command: str, **kwargs):
+ commands.append(command)
+ return await original_exec(command, **kwargs)
+
+ monkeypatch.setattr(environment, "exec", observe_exec)
+ options = {"exclude": []} if method == "download_dir_with_exclusions" else {"include": ["*.txt"]}
+ with pytest.raises(ValueError, match="outside"):
+ await getattr(environment, method)(source_dir=source, target_dir=target, **options)
+ assert _contained_transfer_files(target) == {"retained.txt": b"destination sentinel\n"}
+ assert commands == [], "invalid sources must fail before executing find/tar or cleanup"
+ assert _contained_transfer_files(outside) == {"private.txt": b"outside sentinel\n"}
+ assert set(environment._root.rglob("*")) == before
+ finally:
+ await environment.stop(delete=False)
+
+ asyncio.run(exercise())
+
+
[email protected](os.name == "nt", reason="real local subprocess backend requires POSIX")
[email protected]("method", ["download_dir_with_exclusions", "download_dir_filtered"])
[email protected]("kind", ["symlink", "hardlink"])
+def test_contained_transfer_linked_destination_failure_cleans_staging_and_preserves_output(
+ local_output_environment: SkillEvaluatorLocalEnvironment, tmp_path: Path, method: str, kind: str
+) -> None:
+ environment = local_output_environment
+ outside = tmp_path / "outside.txt"
+ outside.write_bytes(b"outside sentinel\n")
+ target = tmp_path / "destination"
+ target.mkdir()
+ (target / "retained.txt").write_bytes(b"destination sentinel\n")
+ if kind == "symlink":
+ (target / "keep.txt").symlink_to(outside)
+ else:
+ os.link(outside, target / "keep.txt")
+
+ async def exercise() -> None:
+ await environment.start()
+ try:
+ source = environment._resolve_path("/workspace/export")
+ source.mkdir()
+ (source / "keep.txt").write_bytes(b"new source contents\n")
+ before = set(environment._root.rglob("*"))
+
+ def destination_identity():
+ return {
+ path.name: (
+ metadata.st_mode,
+ metadata.st_ino,
+ metadata.st_dev,
+ metadata.st_nlink,
+ metadata.st_size,
+ metadata.st_mtime_ns,
+ )
+ for path in target.iterdir()
+ for metadata in [path.lstat()]
+ }
+
+ before_destination = destination_identity()
+ options = {"exclude": []} if method == "download_dir_with_exclusions" else {"include": ["*.txt"]}
+ with pytest.raises(ValueError):
+ await getattr(environment, method)(source_dir="/workspace/export", target_dir=target, **options)
+ assert outside.read_bytes() == b"outside sentinel\n"
+ assert (target / "retained.txt").read_bytes() == b"destination sentinel\n"
+ assert (target / "keep.txt").read_bytes() == b"outside sentinel\n"
+ assert destination_identity() == before_destination
+ assert _contained_transfer_files(source) == {"keep.txt": b"new source contents\n"}
+ assert set(environment._root.rglob("*")) == before
+ finally:
+ await environment.stop(delete=False)
+
+ asyncio.run(exercise())
+
+
[email protected](os.name == "nt", reason="real local subprocess backend requires POSIX")
+def test_contained_filtered_transfer_propagates_directory_traversal_failure(
+ local_output_environment: SkillEvaluatorLocalEnvironment, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ environment = local_output_environment
+ target = tmp_path / "destination"
+ target.mkdir()
+ (target / "retained.txt").write_bytes(b"destination sentinel\n")
+
+ async def exercise() -> None:
+ await environment.start()
+ try:
+ source = environment._resolve_path("/workspace/export")
+ source.mkdir()
+ (source / "private").mkdir()
+ (source / "private" / "keep.txt").write_bytes(b"source sentinel\n")
+ before = set(environment._root.rglob("*"))
+ original_walk = os.walk
+
+ def failed_walk(top, *args, onerror=None, **kwargs):
+ if Path(top) == source:
+ if onerror is not None:
+ onerror(PermissionError("cannot scan private child directory"))
+ return
+ yield from original_walk(top, *args, onerror=onerror, **kwargs)
+
+ monkeypatch.setattr(os, "walk", failed_walk)
+ with pytest.raises(PermissionError, match="cannot scan"):
+ await environment.download_dir_filtered(source_dir="/workspace/export", target_dir=target)
+ assert _contained_transfer_files(target) == {"retained.txt": b"destination sentinel\n"}
+ assert (source / "private" / "keep.txt").read_bytes() == b"source sentinel\n"
+ assert set(environment._root.rglob("*")) == before
+ finally:
+ await environment.stop(delete=False)
+
+ asyncio.run(exercise())