diff --git a/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md b/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md new file mode 100644 index 000000000..f6152bcf3 --- /dev/null +++ b/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md @@ -0,0 +1,8 @@ + + +### Security + +- **Reject escaping task paths** — `repo run` refuses task directories and task JSON links that leave the repository or escape the relocated eval directory. diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index 69c937850..1b76a28e2 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -375,6 +375,11 @@ belongs to the repository's grader and is passed through unread, except `grader` `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` refuses a task whose `task.json` link leaves the source repository, with exit 2. +It checks again after exporting the eval directory: relocation can make a relative link escape that was contained in the source tree. +After export, a task directory or task target that resolves outside the exported eval directory is refused before it is read. +Unresolved in-tree links are left to the selection-aware loader: a selected broken task fails, while an unrelated unselected broken task does not block the run. + | Key | Required | Read by | Meaning | |---|---|---|---| | `id` | yes | framework | equals the directory name, and contains no whitespace or comma: the workflow's `tasks`, `smoke-tasks` and `exclude-tasks` inputs are lists of ids split on whitespace and commas, so `eval check --schema-only` refuses an id containing either | diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 0fc3e3031..c025aa0a3 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -25,6 +25,10 @@ from dokimi.exit_codes import EXIT_INCONCLUSIVE, EXIT_INFRA from dokimi.repos.harness_profile import DELEGATION_MODES from dokimi.repos.source import SourceArgumentError, tree_path +from dokimi.repos.task_source import ( + check_exported_task_json_links as _check_exported_task_json_links, + check_task_json_links as _check_task_json_links, +) from dokimi.digest import tree_digest from dokimi.files import InputError from dokimi.commands._shared import run_errors @@ -33,8 +37,8 @@ def refuse_typed(source, args: argparse.Namespace) -> None: - """Exit 2 for what the user typed: a pinned local path inside a repository, or a ``--manifest`` that leaves - the tree as written. A path the tree supplies (a link out of it) fails later, with exit 1.""" + """Exit 2 for what the user typed, and for a ``--manifest`` or ``--suite`` leaving the tree. + Task links are checked in ``_context``; other tree paths fail later, with exit 1.""" from dokimi.repos.source import check_pinned_root try: @@ -84,6 +88,7 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): tree = open_source(source, cache_dir_from_args(args)) manifest = manifest_for_tree(tree, args) + _check_task_json_links(tree, manifest) # refuse task paths that leave the source repository require_runnable(manifest) if manifest.image is None: raise ValueError(f"{manifest.path} declares no `image`; entry points and agents run in it") @@ -92,6 +97,7 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): content = out / "_eval" / "content" # a pinned batch keeps its content until the pin is checked staged = export_eval_dir(tree, manifest, content.with_name("content.next") if pin else content) + _check_exported_task_json_links(staged, manifest) _require_grade(staged, manifest, args.task) # before the pin and the image build suite = _suite_bases(args, tree, staged, manifest, cache_dir_from_args(args)) # its pins go in the batch pin runner = DockerRunner(args.docker) diff --git a/dokimi/dokimi/repos/task_source.py b/dokimi/dokimi/repos/task_source.py new file mode 100644 index 000000000..816c56bc0 --- /dev/null +++ b/dokimi/dokimi/repos/task_source.py @@ -0,0 +1,69 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Validate task paths before and after exporting a repository evaluation tree.""" + +from __future__ import annotations + +from pathlib import Path + +from dokimi.files import InputError +from dokimi.repos.source import SourceArgumentError + + +def _check_source_path(tree, path: str, *, dirs: bool = False) -> None: + """Convert confirmed repository escapes; leave other resolution errors to the loader.""" + try: + tree.resolve(path, dirs=dirs) + except SourceArgumentError as exc: + if str(exc).startswith("path escapes the repository:"): + raise InputError(str(exc)) from exc + + +def check_task_json_links(tree, manifest) -> None: + """Refuse task directories and task files that leave the source repository (contract §3).""" + _eval_dir, tasks = manifest.run_paths() + files = tree.files() + # A symlinked tasks root is itself an entry, even when it has no children. + if tasks in files: + _check_source_path(tree, tasks, dirs=True) + task_prefix = f"{tasks}/" + task_ids = { + rel[len(task_prefix):].partition("/")[0] + for rel in files + if rel.startswith(task_prefix) and rel[len(task_prefix):] + } + for task_id in sorted(task_ids): + task_dir = f"{tasks}/{task_id}" + _check_source_path(tree, task_dir, dirs=True) + _check_source_path(tree, f"{task_dir}/task.json") + + +def _refuse_export_escape(path: Path, root: Path, kind: str, shown: str) -> bool: + """Refuse a resolved path outside the exported eval tree; defer loops and other resolution errors.""" + try: + path.resolve(strict=False).relative_to(root) + except ValueError as exc: + raise InputError(f"{kind} escapes the exported eval directory: {shown}") from exc + except (OSError, RuntimeError): + return False + return True + + +def check_exported_task_json_links(content: Path, manifest) -> None: + """Reject exported task paths outside eval_dir without pre-empting selection-aware loading.""" + eval_dir, tasks = manifest.run_paths() + tasks_dir = content / Path(tasks).relative_to(eval_dir) + root = content.resolve() + if not _refuse_export_escape(tasks_dir, root, "tasks directory", tasks): + return + if not tasks_dir.is_dir(): + return + for task_dir in tasks_dir.iterdir(): + shown_dir = f"{tasks}/{task_dir.name}" + if not _refuse_export_escape(task_dir, root, "task directory", shown_dir): + continue + task_json = task_dir / "task.json" + if not task_json.is_symlink() and not task_json.exists(): + continue # mutation-ok[delete-statement]: absent in-tree task files are still contained + _refuse_export_escape(task_json, root, "task link", f"{shown_dir}/task.json") diff --git a/dokimi/tests/test_repo_run_source_task_link_escape.py b/dokimi/tests/test_repo_run_source_task_link_escape.py new file mode 100644 index 000000000..03f13ad40 --- /dev/null +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -0,0 +1,470 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""repo run rejects escaping task.json links (repository evaluation contract §3).""" + +import os +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from dokimi.commands import repo_run +from dokimi.files import InputError +from dokimi.repos.source import SourceArgumentError, WorkTree + +ROOT = Path(__file__).resolve().parents[1] + +MANIFEST = """schema: repo_manifest.v1 +id: toy +source: {url: "https://example.invalid/toy"} +eval_dir: .agent-eval +guidance: {globs: ["**/AGENTS.md"]} +image: {dockerfile: .agent-eval/Dockerfile, network: none} +entry_points: {grade: "python3 {eval_dir}/grade.py grade {run_dir}"} +tasks: .agent-eval/tasks +""" + + +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() + + +@pytest.mark.parametrize( + ("suffix", "link_kind"), + [("", "file"), ("@HEAD", "file"), ("", "directory"), ("", "directory_with_external_file"), ("@HEAD", "directory_with_external_file")], +) +def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str, link_kind: str) -> None: + """Contract §3: task JSON links cannot leave the source repository.""" + repo = tmp_path / "fx" + task_dir = repo / ".agent-eval" / "tasks" / "t1" + task_dir.mkdir(parents=True) + (repo / "AGENTS.md").write_text("hi\n", encoding="utf-8") + (repo / ".agent-eval" / "Dockerfile").write_text("FROM scratch\n", encoding="utf-8") + (repo / ".agent-eval" / "grade.py").write_text("x\n", encoding="utf-8") + (repo / ".agent-eval" / "repo-eval.yaml").write_text(MANIFEST, encoding="utf-8") + subprocess.run(["git", "init", "-q", str(repo)], check=True) + _git(repo, "add", "-A") + _git(repo, "commit", "-qm", "base") + base = _git(repo, "rev-parse", "HEAD") + outside_task = tmp_path / "outside" / "t1" + outside_task.mkdir(parents=True) + (outside_task / "task.json").write_text( + '{"id":"t1","base":"%s","instruction":"x","grader":"g"}' % base, + encoding="utf-8", + ) + if link_kind == "file": + (task_dir / "task.json").symlink_to(outside_task / "task.json") + elif link_kind == "directory": + task_dir.rmdir() + task_dir.symlink_to(outside_task, target_is_directory=True) + else: + shared = repo / ".agent-eval" / "shared" + shared.mkdir() + (shared / "task.json").symlink_to(outside_task / "task.json") + task_dir.rmdir() + task_dir.symlink_to(shared, target_is_directory=True) + _git(repo, "add", "-A") + _git(repo, "commit", "-qm", "link") + + docker = tmp_path / "fakedocker" + docker.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + docker.chmod(0o755) + batch = tmp_path / "b" + run = subprocess.run( + [ + sys.executable, str(ROOT / "cli.py"), "repo", "run", str(repo) + suffix, + "--manifest", ".agent-eval/repo-eval.yaml", "--arm", "guidance:none", + "--model", "m", "--name", "run", "--out-dir", str(batch), + "--image", "nonexist", "--bin", "/bin/true", "--docker", str(docker), + ], + capture_output=True, text=True, cwd=ROOT, + ) + out = run.stdout + run.stderr + assert "path escapes the repository" in out, out + assert run.returncode == 2, out + assert not (batch / "run" / "_eval" / "content" / "tasks" / "t1" / "task.json").exists() + + +def test_run_refuses_task_link_that_escapes_after_eval_dir_relocation(tmp_path: Path) -> None: + """Contract §3: exported eval-directory relocation cannot make a task link escape.""" + repo = tmp_path / "fx" + task_dir = repo / "a" / "b" / "c" / "d" / "tasks" / "t1" + task_dir.mkdir(parents=True) + (repo / "AGENTS.md").write_text("hi\n", encoding="utf-8") + eval_dir = repo / "a" / "b" / "c" / "d" + (eval_dir / "Dockerfile").write_text("FROM scratch\n", encoding="utf-8") + (eval_dir / "grade.py").write_text("x\n", encoding="utf-8") + manifest = repo / "repo-eval.yaml" + manifest.write_text( + MANIFEST.replace("eval_dir: .agent-eval", "eval_dir: a/b/c/d") + .replace("tasks: .agent-eval/tasks", "tasks: a/b/c/d/tasks") + .replace("dockerfile: .agent-eval/Dockerfile", "dockerfile: a/b/c/d/Dockerfile"), + encoding="utf-8", + ) + subprocess.run(["git", "init", "-q", str(repo)], check=True) + _git(repo, "add", "-A") + _git(repo, "commit", "-qm", "base") + base = _git(repo, "rev-parse", "HEAD") + outside_data = '{"id":"t1","base":"%s","instruction":"x","grader":"g"}' % base + (repo / "outside.json").write_text(outside_data, encoding="utf-8") + # After export, the same relative link resolves here, outside the staged eval directory. + (tmp_path / "outside.json").write_text(outside_data, encoding="utf-8") + (task_dir / "task.json").symlink_to("../../../../../../outside.json") + _git(repo, "add", "-A") + _git(repo, "commit", "-qm", "relocated task link") + + docker = tmp_path / "fakedocker" + docker.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + docker.chmod(0o755) + batch = tmp_path / "b" + run = subprocess.run( + [ + sys.executable, str(ROOT / "cli.py"), "repo", "run", str(repo), + "--manifest", "repo-eval.yaml", "--arm", "guidance:none", + "--model", "m", "--name", "run", "--out-dir", str(batch), + "--image", "nonexist", "--bin", "/bin/true", "--docker", str(docker), + ], + capture_output=True, text=True, cwd=ROOT, + ) + out = run.stdout + run.stderr + assert "task link escapes the exported eval directory" in out, out + assert run.returncode == 2, out + + +def test_task_paths_are_derived_from_task_tree_entries() -> None: + paths = [] + + def resolve(path: str, dirs: bool = False) -> str: + paths.append((path, dirs)) + return path + + tree = SimpleNamespace( + files=lambda: ["tasks/t1/task.json", "tasks/t2/nested/data", "tasks/", "other/file"], + resolve=resolve, + ) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", "tasks")) + + repo_run._check_task_json_links(tree, manifest) + + assert paths == [ + ("tasks/t1", True), ("tasks/t1/task.json", False), + ("tasks/t2", True), ("tasks/t2/task.json", False), + ] + + +def test_task_directory_alias_to_external_file_is_refused(tmp_path: Path) -> None: + root = tmp_path / "repo" + shared = root / ".agent-eval" / "shared" + tasks = root / ".agent-eval" / "tasks" + shared.mkdir(parents=True) + tasks.mkdir() + outside = tmp_path / "outside.json" + outside.write_text("{}", encoding="utf-8") + (shared / "task.json").symlink_to(outside) + (tasks / "t1").symlink_to(shared, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", ".agent-eval/tasks")) + + with pytest.raises(InputError, match="path escapes the repository"): + repo_run._check_task_json_links(WorkTree(root), manifest) + + +@pytest.mark.parametrize(("create_tasks", "create_task_file"), [(False, False), (True, False), (True, True)]) +def test_exported_task_link_check_skips_missing_tasks( # test-quality: ok must-not-raise smoke test for absent tasks and ordinary task files + tmp_path: Path, create_tasks: bool, create_task_file: bool +) -> None: + content = tmp_path / "content" + task_dir = content / "tasks" / "t1" + if create_tasks: + task_dir.mkdir(parents=True) + if create_task_file: + (task_dir / "task.json").write_text("{}", encoding="utf-8") + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_check_refuses_external_target(tmp_path: Path) -> None: + content = tmp_path / "content" + task_dir = content / "tasks" / "t1" + task_dir.mkdir(parents=True) + outside = tmp_path / "outside.json" + outside.write_text("{}", encoding="utf-8") + (task_dir / "task.json").symlink_to(outside) + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + with pytest.raises(InputError, match="task link escapes the exported eval directory"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_check_refuses_external_task_directory_alias(tmp_path: Path) -> None: + """A task directory symlink must be checked even when task.json itself is not a symlink.""" + content = tmp_path / "content" + tasks = content / "tasks" + tasks.mkdir(parents=True) + outside_task = tmp_path / "outside-task" + outside_task.mkdir() + (outside_task / "task.json").write_text("{}", encoding="utf-8") + (tasks / "t1").symlink_to(outside_task, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + with pytest.raises(InputError, match="task directory escapes the exported eval directory"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_check_refuses_external_fifo(tmp_path: Path) -> None: + if not hasattr(os, "mkfifo"): + pytest.skip("FIFO creation is unavailable") + content = tmp_path / "content" + task_dir = content / "tasks" / "t1" + task_dir.mkdir(parents=True) + outside_fifo = tmp_path / "outside.fifo" + os.mkfifo(outside_fifo) + (task_dir / "task.json").symlink_to(outside_fifo) + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + with pytest.raises(InputError, match="task link escapes the exported eval directory"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_check_defers_in_tree_dangling_symlink(tmp_path: Path) -> None: # test-quality: ok must-not-raise smoke test for selection-aware link loading + content = tmp_path / "content" + task_dir = content / "tasks" / "t1" + task_dir.mkdir(parents=True) + (task_dir / "task.json").symlink_to("missing.json") + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + # Selection-aware load_tasks() reports this only if the task is selected. + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_check_refuses_external_dangling_target(tmp_path: Path) -> None: + content = tmp_path / "content" + task_dir = content / "tasks" / "t1" + task_dir.mkdir(parents=True) + outside = tmp_path / "outside" / "missing.json" + (task_dir / "task.json").symlink_to(outside) + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + with pytest.raises(InputError, match="task link escapes the exported eval directory"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_resolution_error_is_deferred( # test-quality: ok must-not-raise smoke test for selection-aware link loading + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An unresolved in-tree path is deferred to the selection-aware task loader.""" + content = tmp_path / "content" + task_json = content / "tasks" / "t1" / "task.json" + task_json.parent.mkdir(parents=True) + task_json.write_text("{}", encoding="utf-8") + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + original_resolve = Path.resolve + + def resolve(path: Path, strict: bool = False) -> Path: + if path == task_json: + raise OSError("unreadable task path") + return original_resolve(path, strict=strict) + + monkeypatch.setattr(Path, "resolve", resolve) + # The loader owns selection-aware diagnostics for paths it cannot resolve. + repo_run._check_exported_task_json_links(content, manifest) + + +def test_context_checks_task_links_before_and_after_export(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + calls = [] + tree = SimpleNamespace(label="source") + manifest = SimpleNamespace( + id="toy", + path="manifest.yaml", + image=SimpleNamespace(caches=[]), + entry_points={}, + ) + content = tmp_path / "content" + content.mkdir() + args = SimpleNamespace( + cache=None, + cache_root=str(tmp_path / "cache"), + docker="docker", + image="existing", + task=None, + source_dir=None, + grade_timeout=1, + suite=None, + ) + + monkeypatch.setattr("dokimi.repos.open_source", lambda *args: tree) + monkeypatch.setattr("dokimi.commands.repo.manifest_for_tree", lambda *args: manifest) + monkeypatch.setattr("dokimi.repos.manifest.require_runnable", lambda *_: None) + monkeypatch.setattr("dokimi.commands._shared.cache_dir_from_args", lambda *_: None) + monkeypatch.setattr(repo_run, "_check_task_json_links", lambda *_: calls.append("source")) + monkeypatch.setattr(repo_run, "_check_exported_task_json_links", lambda *_: calls.append("exported")) + monkeypatch.setattr(repo_run, "_check_cache_paths", lambda *_: None) + monkeypatch.setattr(repo_run, "_require_grade", lambda *_: calls.append("grade")) + monkeypatch.setattr(repo_run, "_suite_bases", lambda *_: None) + monkeypatch.setattr("dokimi.repos.workspace.source_git_dir", lambda *_: tmp_path / "git") + monkeypatch.setattr("dokimi.repos.workspace.export_eval_dir", lambda *_: calls.append("export") or content) + monkeypatch.setattr("dokimi.repos.container.DockerRunner", lambda *_: SimpleNamespace(image_exists=lambda _: True)) + monkeypatch.setattr("dokimi.repos.grading.EvalContext", lambda **kwargs: kwargs) + + repo_run._context(args, tmp_path, SimpleNamespace()) + + assert calls == ["source", "export", "exported", "grade"] + + + +def test_source_task_directory_link_without_task_json_is_refused(tmp_path: Path) -> None: + root = tmp_path / "repo" + tasks = root / ".agent-eval" / "tasks" + tasks.mkdir(parents=True) + outside = tmp_path / "outside-empty" + outside.mkdir() + (tasks / "t1").symlink_to(outside, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", ".agent-eval/tasks")) + + with pytest.raises(InputError, match="path escapes the repository"): + repo_run._check_task_json_links(WorkTree(root), manifest) + + + +def test_source_task_directory_link_cannot_hide_a_task_file_inside_repo(tmp_path: Path) -> None: + root = tmp_path / "repo" + tasks = root / ".agent-eval" / "tasks" + shared = root / ".agent-eval" / "shared" + tasks.mkdir(parents=True) + shared.mkdir() + inside_task = shared / "task.json" + inside_task.write_text("{}", encoding="utf-8") + outside = tmp_path / "outside-task" + outside.mkdir() + (outside / "task.json").symlink_to(inside_task) + (tasks / "t1").symlink_to(outside, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", ".agent-eval/tasks")) + + with pytest.raises(InputError, match="path escapes the repository"): + repo_run._check_task_json_links(WorkTree(root), manifest) + + + +def test_source_tasks_root_link_without_children_is_refused(tmp_path: Path) -> None: + root = tmp_path / "repo" + eval_dir = root / ".agent-eval" + eval_dir.mkdir(parents=True) + outside = tmp_path / "outside-empty-tasks" + outside.mkdir() + (eval_dir / "tasks").symlink_to(outside, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", ".agent-eval/tasks")) + + with pytest.raises(InputError, match="path escapes the repository"): + repo_run._check_task_json_links(WorkTree(root), manifest) + + + +def test_source_non_escape_resolution_error_is_deferred() -> None: + calls = [] + + def resolve(path: str, dirs: bool = False) -> str: + calls.append((path, dirs)) + if dirs: + return path + raise SourceArgumentError("tasks/t1/task.json links to nothing: missing") + + tree = SimpleNamespace(files=lambda: ["tasks/t1/task.json"], resolve=resolve) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", "tasks")) + + repo_run._check_task_json_links(tree, manifest) + + assert calls == [("tasks/t1", True), ("tasks/t1/task.json", False)] + + + +def test_exported_empty_external_task_directory_is_refused(tmp_path: Path) -> None: + content = tmp_path / "content" + tasks = content / "tasks" + tasks.mkdir(parents=True) + outside = tmp_path / "outside-empty-task" + outside.mkdir() + (tasks / "t1").symlink_to(outside, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + with pytest.raises(InputError, match="task directory escapes the exported eval directory"): + repo_run._check_exported_task_json_links(content, manifest) + + + +def test_exported_task_directory_is_refused_even_if_task_json_resolves_inside(tmp_path: Path) -> None: + content = tmp_path / "content" + tasks = content / "tasks" + shared = tasks / "shared" + shared.mkdir(parents=True) + (shared / "task.json").write_text("{}", encoding="utf-8") + outside = tmp_path / "outside-task" + outside.mkdir() + (outside / "task.json").symlink_to(shared / "task.json") + (tasks / "t1").symlink_to(outside, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + with pytest.raises(InputError, match="task directory escapes the exported eval directory"): + repo_run._check_exported_task_json_links(content, manifest) + + + +def test_exported_empty_tasks_root_link_is_refused(tmp_path: Path) -> None: + content = tmp_path / "content" + content.mkdir() + outside = tmp_path / "outside-empty-tasks" + outside.mkdir() + (content / "tasks").symlink_to(outside, target_is_directory=True) + manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) + + with pytest.raises(InputError, match="tasks directory escapes the exported eval directory"): + repo_run._check_exported_task_json_links(content, manifest) + + + +def test_run_refuses_task_directory_that_escapes_after_eval_dir_relocation_without_task_json( + tmp_path: Path, +) -> None: + """An in-repository directory link can leave the exported eval tree after relocation.""" + repo = tmp_path / "fx" + task_dir = repo / "a" / "b" / "c" / "d" / "tasks" / "t1" + task_dir.parent.mkdir(parents=True) + outside_task = repo / "outside-task" + outside_task.mkdir() + (repo / "AGENTS.md").write_text("hi\n", encoding="utf-8") + eval_dir = repo / "a" / "b" / "c" / "d" + (eval_dir / "Dockerfile").write_text("FROM scratch\n", encoding="utf-8") + (eval_dir / "grade.py").write_text("x\n", encoding="utf-8") + manifest = repo / "repo-eval.yaml" + manifest.write_text( + MANIFEST.replace("eval_dir: .agent-eval", "eval_dir: a/b/c/d") + .replace("tasks: .agent-eval/tasks", "tasks: a/b/c/d/tasks") + .replace("dockerfile: .agent-eval/Dockerfile", "dockerfile: a/b/c/d/Dockerfile"), + encoding="utf-8", + ) + task_dir.symlink_to(os.path.relpath(outside_task, task_dir.parent), target_is_directory=True) + subprocess.run(["git", "init", "-q", str(repo)], check=True) + _git(repo, "add", "-A") + _git(repo, "commit", "-qm", "base with external task directory") + docker = tmp_path / "fakedocker" + docker.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + docker.chmod(0o755) + batch = tmp_path / "b" + run = subprocess.run( + [ + sys.executable, str(ROOT / "cli.py"), "repo", "run", str(repo), + "--manifest", "repo-eval.yaml", "--arm", "guidance:none", + "--model", "m", "--name", "run", "--out-dir", str(batch), + "--image", "nonexist", "--bin", "/bin/true", "--docker", str(docker), + ], + capture_output=True, text=True, cwd=ROOT, + ) + out = run.stdout + run.stderr + assert "task directory escapes the exported eval directory" in out, out + assert "no task under" not in out, out + assert run.returncode == 2, out