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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,11 @@ All notable changes to SkillEvaluator are documented in this file.

### Fixed

- Local Tier 3 shell commands map virtual paths once, preserving existing host
paths when a run or installed runtime is under `/workspace` or contains
another virtual root. Artifact directory checks and collection retain the
intended host locations, including quoted paths and paths attached to short
options such as `-I`, `-C`, and `-o`.
- `harness-check` checks a plugin's manifest file or manifest folder (for
example `.claude-plugin/plugin.json`) as the plugin folder it belongs to. In
`--json` output the plugin entry for such a target is now keyed by the plugin
Expand Down
55 changes: 13 additions & 42 deletions src/skillevaluator/tier3/harbor/local_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
LOCAL_RUNTIME_AGENTS,
default_runtime_root,
local_subprocess_env,
rewrite_local_command_paths,
runtime_bin_dirs,
runtime_command_roots,
validate_runtime_root,
Expand Down Expand Up @@ -1962,10 +1963,11 @@ def _path_map(self) -> list[tuple[str, Path]]:
]

def _rewrite_command(self, command: str) -> str:
rewritten = command
for remote, local in self._path_map():
rewritten = self._replace_shell_path(rewritten, remote, local)
return rewritten
return rewrite_local_command_paths(
command,
self._path_map(),
host_roots=(*self._allowed_write_roots(), self._runtime_root, Path(sys.executable).parent),
)

def _rewrite_raw_paths(self, value: str) -> str:
path_map = dict(self._path_map())
Expand All @@ -1987,43 +1989,6 @@ def replace(match: re.Match[str]) -> str:

return pattern.sub(replace, value)

@staticmethod
def _replace_shell_path(command: str, remote: str, local: Path) -> str:
"""Replace a container path while preserving shell token boundaries."""
output: list[str] = []
index = 0
quote = ""
local_text = str(local)
shell_boundaries = "/ \t\r\n'\";&|<>"
while index < len(command):
if command.startswith(remote, index) and (
index + len(remote) == len(command) or command[index + len(remote)] in shell_boundaries
):
if quote == "'":
replacement = local_text.replace("'", "'\"'\"'")
elif quote == '"':
replacement = (
local_text.replace("\\", "\\\\").replace('"', '\\"').replace("$", "\\$").replace("`", "\\`")
)
else:
replacement = shlex.quote(local_text)
output.append(replacement)
index += len(remote)
continue

char = command[index]
output.append(char)
if char == "\\" and quote != "'" and index + 1 < len(command):
index += 1
output.append(command[index])
elif char in {"'", '"'}:
if not quote:
quote = char
elif quote == char:
quote = ""
index += 1
return "".join(output)

def _rewrite_uploaded_scripts(self, target: Path) -> None:
if target.is_file():
self._rewrite_uploaded_script(target)
Expand Down Expand Up @@ -2052,6 +2017,13 @@ def _resolve_path(self, path: str | Path | None) -> Path:
if path is None:
return self._workspace
raw = str(path)
candidate = Path(raw)
if candidate.is_absolute() and any(
candidate.is_relative_to(root.absolute()) for root in self._allowed_write_roots()
Comment thread
Afloat16 marked this conversation as resolved.
Resolved
):
if not self._path_is_within_allowed_local_roots(candidate):
raise ValueError(f"path {raw} is outside the local run directory")
return candidate
# Normalize logical spellings before choosing a role mapping, without
# following untrusted filesystem links through the virtual parent.
logical = str(PurePosixPath(raw))
Expand All @@ -2062,7 +2034,6 @@ def _resolve_path(self, path: str | Path | None) -> Path:
return local / logical[len(remote) + 1 :]
if raw.startswith("~/"):
return self._home / raw[2:]
candidate = Path(raw)
if candidate.is_absolute():
if not self._path_is_within_allowed_local_roots(candidate):
raise ValueError(f"path {raw} is outside the local run directory")
Expand Down
66 changes: 66 additions & 0 deletions src/skillevaluator/tier3/harbor/local_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,72 @@ class RuntimePathResolutionError(RuntimeError):
}


def rewrite_local_command_paths(
command: str, path_map: Sequence[tuple[str, Path]], *, host_roots: Sequence[Path] = ()
) -> str:
"""Map original shell paths once, preserving quotes and known host paths."""

def quote_path(path: str, quote: str) -> str:
if quote == "'":
return path.replace("'", "'\"'\"'")
if quote == '"':
return path.replace("\\", "\\\\").replace('"', '\\"').replace("$", "\\$").replace("`", "\\`")
return shlex.quote(path)

mappings: dict[str, list[tuple[str, str]]] = {}
for quote in ("", "'", '"'):
entries = [(remote, quote_path(str(local), quote)) for remote, local in path_map]
for root in (*host_roots, *(local for _, local in path_map)):
spelling = quote_path(str(root), quote) if quote else str(root)
entries.append((spelling, spelling))
mappings[quote] = sorted(entries, key=lambda entry: len(entry[0]), reverse=True)

output: list[str] = []
index = 0
quote = ""
shell_boundaries = "/ \t\r\n'\";&|<>"
while index < len(command):
match = None
option_start = index
if command[index] == "/":
while option_start and command[option_start - 1].isascii() and command[option_start - 1].isalpha():
option_start -= 1
short_option = (
option_start < index
and option_start > 0
and command[option_start - 1] == "-"
and (option_start == 1 or command[option_start - 2] in shell_boundaries[1:])
)
if index == 0 or short_option or not (command[index - 1].isalnum() or command[index - 1] in "_.-/"):
match = next(
(
(remote, replacement)
for remote, replacement in mappings[quote]
if command.startswith(remote, index)
and (index + len(remote) == len(command) or command[index + len(remote)] in shell_boundaries)
),
None,
)
if match is not None:
remote, replacement = match
output.append(replacement)
index += len(remote)
continue

char = command[index]
output.append(char)
if char == "\\" and quote != "'" and index + 1 < len(command):
index += 1
output.append(command[index])
elif char in {"'", '"'}:
if not quote:
quote = char
elif quote == char:
quote = ""
index += 1
return "".join(output)


def validate_runtime_root(root: Path | str) -> Path:
"""Return a canonical dedicated runtime root without exposing host home."""
resolved = Path(root).expanduser().resolve(strict=False)
Expand Down
77 changes: 76 additions & 1 deletion tests/test_harbor_local_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import asyncio
import logging
import os
import shlex
import shutil
import stat
import subprocess
Expand Down Expand Up @@ -42,7 +43,8 @@ def local_output_environment(tmp_path: Path) -> SkillEvaluatorLocalEnvironment:
environment_dir.mkdir()
runtime_root = tmp_path / "runtime"
runtime_root.mkdir()
paths = TrialPaths(tmp_path / "trial")
# Host paths can contain the same components as the virtual runtime roots.
paths = TrialPaths(tmp_path / "workspace" / "tests" / "trial")
paths.mkdir()
return SkillEvaluatorLocalEnvironment(
environment_dir=environment_dir,
Expand Down Expand Up @@ -426,6 +428,79 @@ def test_raw_path_rewrite_ignores_url_and_local_path_suffixes(tmp_path: Path) ->
assert rewritten == f'"{local_tests}{os.sep}api" "https://example.invalid/tests/api" "{local_tests}/api"'


@pytest.mark.skipif(os.name == "nt", reason="local subprocess backend requires POSIX")
@pytest.mark.parametrize("quote", ["", "'", '"'])
@pytest.mark.parametrize("reverse", [False, True])
@pytest.mark.parametrize(
"option,suffix", [("", "/answer.txt"), ("-I", "/include"), ("-C", ""), ("-o", "/a.out"), ("-abc", "/answer.txt")]
)
def test_shell_paths_are_mapped_once_with_overlapping_roots(
local_output_environment: SkillEvaluatorLocalEnvironment,
tmp_path: Path,
quote: str,
reverse: bool,
option: str,
suffix: str,
) -> None:
environment = local_output_environment
target = tmp_path / "workspace" / "tests" / "quote ' \" $ `"
mappings = [("/logs", target / "logs"), ("/logs/agent", target / "agent"), ("/workspace", target / "workspace")]
environment._path_map = lambda: list(reversed(mappings)) if reverse else mappings
operands = [f"{quote}{option}{remote}{suffix}{quote}" for remote, _ in mappings]
rewritten = environment._rewrite_command("printf '%s\\n' " + " ".join(operands))

result = subprocess.run(["bash", "-c", rewritten], capture_output=True, text=True, timeout=10)

assert result.returncode == 0, result.stderr
assert result.stdout.splitlines() == [f"{option}{local}{suffix}" for _, local in mappings]


@pytest.mark.skipif(os.name == "nt", reason="local subprocess backend requires POSIX")
def test_shell_paths_preserve_host_paths_and_adjacent_text(
local_output_environment: SkillEvaluatorLocalEnvironment,
) -> None:
environment = local_output_environment
operands = [
str(environment._tmp / "tests" / "archive.tar"),
str(environment._workspace / "logs" / "answer.txt"),
str(environment._runtime_root / "workspace" / "bin"),
"-I" + str(environment._workspace / "include"),
"https://example.invalid/tests/eval.py",
"https://example.invalid/-I/workspace/include",
"prefix/workspace/answer.txt",
"prefix-I/workspace/include",
"./-I/workspace/include",
"--include/workspace/include",
"项目/workspace/answer.txt",
"/workspace-other/answer.txt",
"/testsuite/eval.py",
]
command = "printf '%s\\n' " + " ".join(shlex.quote(operand) for operand in operands)

result = subprocess.run(
["bash", "-c", environment._rewrite_command(command)], capture_output=True, text=True, timeout=10
)

assert result.returncode == 0, result.stderr
assert result.stdout.splitlines() == operands


@pytest.mark.skipif(os.name == "nt", reason="literal POSIX host roots")
def test_resolve_path_preserves_host_root_before_virtual_mapping(
local_output_environment: SkillEvaluatorLocalEnvironment,
) -> None:
environment = local_output_environment
environment._root = Path("/workspace/ci/run")
environment._workspace = environment._root / "workspace"
environment.trial_paths = TrialPaths(environment._root / "trial")
host_path = environment.trial_paths.trial_dir / "agent" / "work"

assert environment._resolve_path(str(host_path)) == host_path
assert environment._resolve_path("/workspace/other/x") == environment._workspace / "other/x"
with pytest.raises(ValueError, match="outside the local run directory"):
environment._resolve_path("/workspace/ci/run/trial/../../../etc/passwd")


@pytest.mark.integration
@pytest.mark.skipif(os.name == "nt", reason="local subprocess backend requires POSIX")
@pytest.mark.parametrize("secret_name", ["SANDBOX_TOKEN", "MYSECRET", "SOMEKEY", "AUTHENTICATION"])
Expand Down
6 changes: 3 additions & 3 deletions tests/test_harbor_local_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -5307,7 +5307,7 @@ def capture_bins(runtime_root, *, agents=None):
def test_shell_path_rewrite_quotes_unquoted_path_with_spaces(tmp_path: Path) -> None:
target = tmp_path / "result with spaces"
target.mkdir()
environment = object.__new__(SkillEvaluatorLocalEnvironment)
environment = _local_environment(tmp_path)
environment._path_map = lambda: [("/logs", target)]

rewritten = environment._rewrite_command("printf ok > /logs/output.txt")
Expand All @@ -5321,7 +5321,7 @@ def test_shell_path_rewrite_quotes_unquoted_path_with_spaces(tmp_path: Path) ->
def test_shell_path_rewrite_preserves_existing_quotes(tmp_path: Path) -> None:
target = tmp_path / "result with spaces"
target.mkdir()
environment = object.__new__(SkillEvaluatorLocalEnvironment)
environment = _local_environment(tmp_path)
environment._path_map = lambda: [("/logs", target)]

rewritten = environment._rewrite_command('printf ok > "/logs/output.txt"')
Expand All @@ -5335,7 +5335,7 @@ def test_shell_path_rewrite_preserves_existing_quotes(tmp_path: Path) -> None:
def test_shell_path_rewrite_handles_exact_path_before_shell_separator(tmp_path: Path) -> None:
target = tmp_path / "result with spaces"
target.mkdir()
environment = object.__new__(SkillEvaluatorLocalEnvironment)
environment = _local_environment(tmp_path)
environment._path_map = lambda: [("/workspace", target)]

rewritten = environment._rewrite_command("cd /workspace && printf ok > output.txt")
Expand Down
Loading