diff --git a/dokimi/changelog.d/20261204_sazid63_repo-run-task-symlink-escape.md b/dokimi/changelog.d/20261204_sazid63_repo-run-task-symlink-escape.md new file mode 100644 index 000000000..e5b68c1cf --- /dev/null +++ b/dokimi/changelog.d/20261204_sazid63_repo-run-task-symlink-escape.md @@ -0,0 +1,8 @@ + + +### Security + +- **Reject task files outside the evaluation tree** — repo run and eval check refuse a task.json whose resolved path escapes the exported evaluation tree, preventing unrelated host files from entering run artifacts. diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index e4c5571d4..413f24d66 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -291,8 +291,11 @@ The schema is `dokimi/schemas/suite_manifest.v1.json`; an example is The framework interprets the **core** and **workspace** keys. Every other key belongs to the repository's grader and is passed through unread, except `grader`, which the framework reads to tell a `dokimi:` name (§4.5) from a repository's. -`eval check --schema-only` reports a `task.json` that is not valid JSON, not a JSON object, or cannot be -read (a link that loops, names a directory or nothing, or leaves the repository, in a tree or at `@rev`) as an `error:` line, and exits 1. +`eval check --schema-only` reports a `task.json` that is not valid JSON, not a JSON +object, or cannot be read (a link that loops, names a directory or nothing, or +leaves the repository, in a tree or at `@rev`) as an `error:` line, and exits 1. +`repo run` also refuses task paths that escape the exported eval tree; an unrelated +dangling task link does not block a run that selects other tasks. | Key | Required | Read by | Meaning | |---|---|---|---| diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 0fc3e3031..3918c18c8 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -158,10 +158,13 @@ def _suite_pin(suite) -> dict[str, Any]: def _require_grade(content: Path, manifest: RepoManifest, ids: list[str] | None) -> None: """Refuse the selected tasks when one needs ``entry_points.grade`` and the manifest has none.""" from dokimi.repos.manifest import ManifestError, TaskSummary, grade_problems + from dokimi.repos.errors import TaskPathEscapeError from dokimi.repos.workspace import PrepError, load_tasks try: tasks = load_tasks(content, manifest, ids) + except TaskPathEscapeError as exc: + raise InputError(str(exc)) from exc except (OSError, ValueError, PrepError): return # reported where the run loads its tasks graders = [(t.id, str(t.raw.get("grader") or "") if isinstance(t.raw, dict) else "") for t in tasks] @@ -173,10 +176,13 @@ def _require_grade(content: Path, manifest: RepoManifest, ids: list[str] | None) def _uses_builtin_graders(content: Path, manifest: RepoManifest) -> bool: """Whether a task of the exported eval dir names a ``dokimi:`` grader; an unreadable task.json counts.""" from dokimi.repos.graders import builtin_name + from dokimi.repos.errors import TaskPathEscapeError from dokimi.repos.workspace import PrepError, load_tasks try: tasks = load_tasks(content, manifest, check_keys=False) + except TaskPathEscapeError: + raise except (OSError, ValueError, PrepError): # PrepError: a task.json that is not JSON or nested too deeply (#975) return True return any(isinstance(t.raw, dict) and builtin_name(t.raw.get("grader")) is not None for t in tasks) diff --git a/dokimi/dokimi/repos/errors.py b/dokimi/dokimi/repos/errors.py index 03a05d472..1a725a895 100644 --- a/dokimi/dokimi/repos/errors.py +++ b/dokimi/dokimi/repos/errors.py @@ -10,5 +10,9 @@ class PrepError(RuntimeError): """A workspace could not be prepared (a patch does not apply, a base is missing, ...).""" +class TaskPathEscapeError(PrepError): + """A task file resolves outside the exported evaluation tree.""" + + class CodeIndexError(ValueError): """A SCIP code index cannot be read: empty, truncated, garbled, or not an index at all.""" diff --git a/dokimi/dokimi/repos/task_files.py b/dokimi/dokimi/repos/task_files.py new file mode 100644 index 000000000..462bfeddf --- /dev/null +++ b/dokimi/dokimi/repos/task_files.py @@ -0,0 +1,55 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Resolve and read task files from the exported eval tree.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from .errors import PrepError, TaskPathEscapeError + + +def resolve_task_paths( + paths: dict[str, Path], wanted: set[str], content_root: Path, task_root: str, +) -> dict[str, tuple[Path, Path]]: + """Validate containment for every discovered task before resolving selected files. + + This function deliberately does not unlink or otherwise clean up rejected paths: + an exported entry can resolve through a directory symlink into caller-owned files. + """ + found: dict[str, tuple[Path, Path]] = {} + for task_id, path in paths.items(): + shown = f"{task_root}/{task_id}/task.json" + try: + resolved = path.resolve(strict=False) + except (OSError, RuntimeError) as exc: + if task_id not in wanted: + continue + raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc + if not resolved.is_relative_to(content_root): + raise TaskPathEscapeError( + f"{shown}: path escapes the repository (resolves outside the exported eval tree)" + ) + if task_id not in wanted: + continue + try: + resolved = path.resolve(strict=True) + except (OSError, RuntimeError) as exc: + raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc + if not resolved.is_relative_to(content_root): + raise TaskPathEscapeError( + f"{shown}: path escapes the repository (resolves outside the exported eval tree)" + ) + found[task_id] = (path, resolved) + return found + + +def read_task_json(path: Path, shown: str) -> Any: + """Parse task JSON and report malformed content with its repository path.""" + try: + return json.loads(path.read_text(encoding="utf-8")) + except (ValueError, RecursionError) as exc: + raise PrepError(f"{shown}: cannot read task.json: {type(exc).__name__}: {str(exc)[:200]}") from exc diff --git a/dokimi/dokimi/repos/workspace.py b/dokimi/dokimi/repos/workspace.py index 81ba0e4a4..29b7adfe3 100644 --- a/dokimi/dokimi/repos/workspace.py +++ b/dokimi/dokimi/repos/workspace.py @@ -38,7 +38,6 @@ from __future__ import annotations import hashlib -import json import os import posixpath import re @@ -65,6 +64,7 @@ from .skill_dirs import only_empty_dirs from .source import (GitTree, RepoSource, RepoTree, SourceError, cache_path, clone_once, default_cache_dir, isolated_git_env, resolve_rev) +from .task_files import read_task_json, resolve_task_paths from .uptake import MCP_CONFIG, base_servers, mcp_servers from .useful_spec import Useful, parse_useful from dokimi.treatments.specs import COMBINE, split_parts @@ -264,27 +264,24 @@ def load_tasks(content_dir: Path, manifest: RepoManifest, ids: list[str] | None No task at all is refused: a check or run over none would report 0/0 as a pass.""" eval_dir, tasks = manifest.run_paths() tasks_dir = content_dir / PurePosixPath(tasks).relative_to(eval_dir) - found = {p.parent.name: p for p in sorted(tasks_dir.glob("*/task.json"))} - if not found: + paths = sorted(tasks_dir.glob("*/task.json")) + found_paths = {path.parent.name: path for path in paths} + if not found_paths: raise PrepError(f"no task under {manifest.tasks} (no */task.json): nothing to check or run") - wanted = ids or sorted(found) - missing = [t for t in wanted if t not in found] + wanted = ids or sorted(found_paths) + missing = [task_id for task_id in wanted if task_id not in found_paths] if missing: raise PrepError(f"no such task(s) under {manifest.tasks}: {', '.join(missing)}") - raws = {t: _read_task_json(found[t], f"{manifest.tasks}/{t}/task.json") for t in wanted} - for t, raw in (raws.items() if check_keys else ()): # the checks of `eval check --schema-only`, before a cell depends on them (#1301) - problems = task_key_problems(raw, t) if isinstance(raw, dict) else ["must be a JSON object"] - if problems: - raise PrepError(f"{manifest.tasks}/{t}/task.json: {'; '.join(problems)}") - return [Task(t, raws[t], found[t].parent) for t in wanted] + found = resolve_task_paths(found_paths, set(wanted), content_dir.resolve(), tasks) -def _read_task_json(path: Path, shown: str) -> Any: - """The parsed ``task.json``; one that is not JSON, not UTF-8 or nested too deeply is a ``PrepError`` naming it as ``shown``, its path in the repo (#975).""" - try: - return json.loads(path.read_text(encoding="utf-8")) - except (ValueError, RecursionError) as exc: - raise PrepError(f"{shown}: cannot read task.json: {type(exc).__name__}: {str(exc)[:200]}") from exc + raws = {task_id: read_task_json(found[task_id][1], f"{manifest.tasks}/{task_id}/task.json") + for task_id in wanted} + for task_id, raw in (raws.items() if check_keys else ()): # the checks of `eval check --schema-only`, before a cell depends on them (#1301) + problems = task_key_problems(raw, task_id) if isinstance(raw, dict) else ["must be a JSON object"] + if problems: + raise PrepError(f"{manifest.tasks}/{task_id}/task.json: {'; '.join(problems)}") + return [Task(task_id, raws[task_id], found[task_id][0].parent) for task_id in wanted] def source_git_dir(source: RepoSource, tree: RepoTree, cache_dir: Path | None = None) -> Path: diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py new file mode 100644 index 000000000..031b0e0f0 --- /dev/null +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -0,0 +1,251 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 +"""#1277: repo run must not read task.json through a symlink outside the repository.""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +from repo_eval_fixture import make_repo +from dokimi.repos import RepoSource, load_manifest, open_source +from dokimi.repos.errors import PrepError, TaskPathEscapeError +from dokimi.repos.workspace import export_eval_dir, load_tasks + +ROOT = Path(__file__).resolve().parents[1] + + +def _git(repo: Path, *args: str) -> str: + return subprocess.run( + ["git", "-C", str(repo), "-c", "user.email=a@b", "-c", "user.name=n", *args], + capture_output=True, text=True, check=True, + ).stdout.strip() + + +def _exported_eval(root: Path, tmp_path: Path): + tree = open_source(RepoSource.parse(str(root))) + manifest = load_manifest(tree, ".agent-eval/repo-eval.yaml") + content = export_eval_dir(tree, manifest, tmp_path / "content") + return content, manifest + + +def test_unselected_dangling_task_link_does_not_block_selected_task(tmp_path: Path) -> None: + """A broken link in an unselected task is not read while loading a selected task.""" + root, _ = make_repo(tmp_path / "fixture") + broken = root / ".agent-eval/tasks/broken" + broken.mkdir() + (broken / "task.json").symlink_to("missing.json") + _git(root, "add", "-A") + _git(root, "commit", "-qm", "add unrelated dangling task link") + + content, manifest = _exported_eval(root, tmp_path) + tasks = load_tasks(content, manifest, ["fix_add"], check_keys=False) + + assert [task.id for task in tasks] == ["fix_add"] + + +def test_unselected_external_task_link_is_still_refused(tmp_path: Path) -> None: + """Selection does not permit an unselected task to smuggle an outside file into artifacts.""" + root, _ = make_repo(tmp_path / "fixture") + outside = tmp_path / "outside.json" + outside.write_text("{}", encoding="utf-8") + broken = root / ".agent-eval/tasks/broken" + broken.mkdir() + (broken / "task.json").symlink_to(outside) + _git(root, "add", "-A") + _git(root, "commit", "-qm", "add unrelated external task link") + + content, manifest = _exported_eval(root, tmp_path) + with pytest.raises(TaskPathEscapeError, match="path escapes the repository"): + load_tasks(content, manifest, ["fix_add"], check_keys=False) + assert (content / "tasks/broken/task.json").is_symlink() + assert outside.read_text(encoding="utf-8") == "{}" + + +def test_unselected_dangling_external_task_link_is_still_refused(tmp_path: Path) -> None: + root, _ = make_repo(tmp_path / "fixture") + broken = root / ".agent-eval/tasks/broken" + broken.mkdir() + (broken / "task.json").symlink_to(tmp_path / "missing.json") + _git(root, "add", "-A") + _git(root, "commit", "-qm", "add unrelated dangling external task link") + + content, manifest = _exported_eval(root, tmp_path) + with pytest.raises(TaskPathEscapeError, match="path escapes the repository"): + load_tasks(content, manifest, ["fix_add"], check_keys=False) + exported_link = content / "tasks/broken/task.json" + assert exported_link.is_symlink() + assert exported_link.readlink() == tmp_path / "missing.json" + + +def test_task_file_link_within_eval_tree_keeps_task_directory(tmp_path: Path) -> None: + root, _ = make_repo(tmp_path / "fixture") + task = root / ".agent-eval/tasks/fix_add/task.json" + alias = root / ".agent-eval/tasks/alias" + alias.mkdir() + (alias / "task.json").write_bytes(task.read_bytes()) + task.unlink() + task.symlink_to("../alias/task.json") + _git(root, "add", "-A") + _git(root, "commit", "-qm", "link task file within eval tree") + + content, manifest = _exported_eval(root, tmp_path) + tasks = load_tasks(content, manifest, ["fix_add"], check_keys=False) + + assert tasks[0].dir == content / "tasks/fix_add" + assert tasks[0].raw["id"] == "fix_add" + + +def test_unselected_task_symlink_loop_does_not_block_selected_task(tmp_path: Path) -> None: + root, _ = make_repo(tmp_path / "fixture") + broken = root / ".agent-eval/tasks/broken" + broken.mkdir() + (broken / "task.json").symlink_to("task.json") + _git(root, "add", "-A") + _git(root, "commit", "-qm", "add unrelated task symlink loop") + + content, manifest = _exported_eval(root, tmp_path) + tasks = load_tasks(content, manifest, ["fix_add"], check_keys=False) + + assert [task.id for task in tasks] == ["fix_add"] + + +def test_selected_task_symlink_loop_is_reported(tmp_path: Path) -> None: + root, _ = make_repo(tmp_path / "fixture") + broken = root / ".agent-eval/tasks/broken" + broken.mkdir() + (broken / "task.json").symlink_to("task.json") + _git(root, "add", "-A") + _git(root, "commit", "-qm", "add selected task symlink loop") + + content, manifest = _exported_eval(root, tmp_path) + with pytest.raises(PrepError, match="cannot resolve task.json"): + load_tasks(content, manifest, ["broken"], check_keys=False) + + +def test_selected_task_strict_resolution_is_rechecked_for_escape(tmp_path: Path, monkeypatch) -> None: + from dokimi.repos.task_files import resolve_task_paths + + content = tmp_path / "content" + task = content / "tasks/broken/task.json" + outside = tmp_path / "outside.json" + original_resolve = Path.resolve + + def changing_resolve(path: Path, *, strict: bool = False) -> Path: + if path == task: + return task if strict is False else outside + return original_resolve(path, strict=strict) + + monkeypatch.setattr(Path, "resolve", changing_resolve) + with pytest.raises(TaskPathEscapeError, match="path escapes the repository"): + resolve_task_paths( + {"broken": task}, + {"broken"}, + content, + "tasks", + ) + + +def test_repo_run_helpers_surface_task_path_escapes(tmp_path: Path, monkeypatch) -> None: + from dokimi.commands.repo_run import InputError, _require_grade, _uses_builtin_graders + + root, _ = make_repo(tmp_path / "fixture") + content, manifest = _exported_eval(root, tmp_path) + + def reject_task_paths(*args, **kwargs): + raise TaskPathEscapeError("task path escapes the exported tree") + + monkeypatch.setattr("dokimi.repos.workspace.load_tasks", reject_task_paths) + with pytest.raises(InputError, match="task path escapes"): + _require_grade(content, manifest, ["fix_add"]) + with pytest.raises(TaskPathEscapeError, match="task path escapes"): + _uses_builtin_graders(content, manifest) + + +def test_selected_dangling_task_link_is_still_refused(tmp_path: Path) -> None: + root, _ = make_repo(tmp_path / "fixture") + broken = root / ".agent-eval/tasks/broken" + broken.mkdir() + (broken / "task.json").symlink_to("missing.json") + _git(root, "add", "-A") + _git(root, "commit", "-qm", "add selected dangling task link") + + content, manifest = _exported_eval(root, tmp_path) + with pytest.raises(PrepError, match="cannot resolve task.json"): + load_tasks(content, manifest, ["broken"], check_keys=False) + + +def test_external_task_file_symlink_is_not_unlinked_through_directory_symlink(tmp_path: Path) -> None: + """Reject a linked task directory without mutating a symlink in the host tree.""" + root, _ = make_repo(tmp_path / "fixture") + outside_dir = tmp_path / "outside-task" + outside_dir.mkdir() + payload = tmp_path / "outside-payload.json" + payload.write_text("{}", encoding="utf-8") + external_task = outside_dir / "task.json" + external_task.symlink_to(payload) + + task_dir = root / ".agent-eval/tasks/fix_add" + shutil.rmtree(task_dir) + task_dir.symlink_to(outside_dir, target_is_directory=True) + _git(root, "add", "-A") + _git(root, "commit", "-qm", "link task directory containing external task symlink") + + content, manifest = _exported_eval(root, tmp_path) + with pytest.raises(TaskPathEscapeError, match="path escapes the repository"): + load_tasks(content, manifest, ["fix_add"], check_keys=False) + + assert task_dir.is_symlink() + assert external_task.is_symlink() + assert external_task.resolve() == payload.resolve() + assert payload.read_text(encoding="utf-8") == "{}" + + +@pytest.mark.parametrize("suffix", ["", "@HEAD"], ids=["working-tree", "committed-tree"]) +@pytest.mark.parametrize("link_kind", ["file", "directory"], ids=["task-file-link", "task-directory-link"]) +def test_run_refuses_task_json_symlink_outside_repository( + tmp_path: Path, suffix: str, link_kind: str, +) -> None: + """A task file outside the repository must not be copied into the batch artifacts.""" + root, base = make_repo(tmp_path / "fixture") + task = root / ".agent-eval/tasks/fix_add/task.json" + payload = json.dumps({ + "id": "fix_add", "base": base, "prompt": "x", "grader": "calc", "gate": ["tests_pass"], + }) + if link_kind == "file": + outside = tmp_path / "outside.json" + outside.write_text(payload, encoding="utf-8") + task.unlink() + task.symlink_to(outside) + else: + outside_dir = tmp_path / "outside-task" + outside_dir.mkdir() + (outside_dir / "task.json").write_text(payload, encoding="utf-8") + shutil.rmtree(task.parent) + task.parent.symlink_to(outside_dir, target_is_directory=True) + _git(root, "add", "-A") + _git(root, "commit", "-qm", "link task.json outside the repository") + + docker = tmp_path / "fake-docker" + docker.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + docker.chmod(0o755) + out_dir = tmp_path / "run" + batch = out_dir / "escape" + run = subprocess.run( + [ + sys.executable, str(ROOT / "cli.py"), "repo", "run", str(root) + suffix, + "--manifest", ".agent-eval/repo-eval.yaml", "--arm", "guidance:none", "--model", "m", + "--name", "escape", "--out-dir", str(out_dir), "--task", "fix_add", "--image", "nonexist", + "--bin", "/bin/true", "--docker", str(docker), "--agent-network", "bridge", + ], + capture_output=True, text=True, cwd=ROOT, + ) + output = run.stdout + run.stderr + assert "Traceback" not in output, output + assert "path escapes the repository" in output, output + assert run.returncode == 2, output + assert not (batch / "_eval/content/tasks/fix_add/task.json").exists()