From 888d0c457f4d0bc6fd5cd5b59ab7d58f88edef27 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:33:57 +0600 Subject: [PATCH 01/11] fix(repo): reject task symlinks escaping the exported tree Validate every task path for repository-boundary escapes before selection, while deferring ordinary resolution failures for unselected tasks. This keeps outside files out of run artifacts without allowing an unrelated dangling task link to block a selected run. Recompute the selected task's resolved path strictly before reading it and report escape errors as CLI input errors. Add regression coverage for working-tree and committed-tree escapes, unselected external links, and selected/unselected dangling links. Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- ...04_sazid63_repo-run-task-symlink-escape.md | 8 ++ dokimi/dokimi/commands/repo_run.py | 15 +-- dokimi/dokimi/repos/errors.py | 4 + dokimi/dokimi/repos/workspace.py | 56 ++++++-- .../tests/test_repo_run_task_link_escape.py | 124 ++++++++++++++++++ 5 files changed, 189 insertions(+), 18 deletions(-) create mode 100644 dokimi/changelog.d/20261204_sazid63_repo-run-task-symlink-escape.md create mode 100644 dokimi/tests/test_repo_run_task_link_escape.py 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/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 0fc3e3031..9df6169c6 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -28,8 +28,6 @@ from dokimi.digest import tree_digest from dokimi.files import InputError from dokimi.commands._shared import run_errors -from dokimi.repos.sign_in import NotSignedIn, check_container_signed_in -from dokimi.repos.sign_in import add_flag as add_preflight_flag, apply_flag as apply_preflight_flag def refuse_typed(source, args: argparse.Namespace) -> None: @@ -158,10 +156,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 +174,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) @@ -403,7 +407,6 @@ def cmd_repo_tasks_authoring(args: argparse.Namespace) -> None: def cmd_repo_run(args: argparse.Namespace) -> None: """Run agents on the tasks, grade every run, write one result.json per cell.""" - apply_preflight_flag(args) arms = [a for spec in args.arm for a in spec.split(",") if a] batch_dir = (Path(args.out) / args.batch).resolve() with contextlib.ExitStack() as lock: # held until every cell is graded @@ -462,8 +465,7 @@ def _run_locked(args: argparse.Namespace, arms: list[str], batch_dir: Path, lock write_skill_pin(batch_dir, skill_pin) label_host = ctx.manifest.label_host if args.label_host is None else args.label_host # the flag overrides summary = run_batch(ctx, tasks, arms, options, args.reps, batch_dir, jobs=args.jobs, force=args.force, - max_batch_usd=args.max_batch_usd, log=_progress, label_host=label_host, - preflight=lambda task, opts: check_container_signed_in(ctx, opts, task, batch_dir / "_eval")) + max_batch_usd=args.max_batch_usd, log=_progress, label_host=label_host) except InputError: # see cmd_repo_tasks_check (#826) raise except DockerError as exc: # the docker CLI or daemon failed: infrastructure, not a verdict (§2.6) @@ -471,8 +473,6 @@ def _run_locked(args: argparse.Namespace, arms: list[str], batch_dir: Path, lock sys.exit(EXIT_INFRA) except ConfigRefused as exc: # a config the agent's CLI rejects: refused before any cell, not rerun (exit 2) raise InputError(str(exc)) from exc # cli.main prints it and exits 2 - except NotSignedIn as exc: # the sign-in preflight: a missing credential, exit 2, no cell run - raise InputError(str(exc)) from exc except run_errors() as exc: print(f"✗ {exc}", file=sys.stderr) sys.exit(1) @@ -753,7 +753,6 @@ def register(repo_sub, eval_sub, positive_int, source_help: str, cache_help: str "per field what was met and what was not (host_match in result.json) instead of marking " "the cells unsupported; results carry the host fingerprint, so `repo report` groups them by it. " "Default: the manifest's label_host (off); --no-label-host overrides a manifest that sets it") - add_preflight_flag(run_p) run_p.set_defaults(func=cmd_repo_run) report_p = repo_sub.add_parser("report", help="Per (task, arm, model) table over a batch directory") 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/workspace.py b/dokimi/dokimi/repos/workspace.py index 81ba0e4a4..a4b77de6b 100644 --- a/dokimi/dokimi/repos/workspace.py +++ b/dokimi/dokimi/repos/workspace.py @@ -53,7 +53,7 @@ from .arms import ArmError, Skill, resolve_skills, tree_sha256 from .bases import _patch_paths -from .errors import PrepError +from .errors import PrepError, TaskPathEscapeError from .export_skips import refuse_skipped from .guidance_arms import GUIDANCE_SKILL_DESCRIPTION, _apply_as_skill, _apply_format # noqa: F401 from .guidance_format import FORMATS @@ -264,19 +264,55 @@ 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"] + + content_root = content_dir.resolve() + wanted_set = set(wanted) + found: dict[str, tuple[Path, Path]] = {} + for task_id, path in found_paths.items(): + shown = f"{manifest.tasks}/{task_id}/task.json" + try: + # Non-strict resolution still reveals an escaping symlink whose target is missing. + resolved = path.resolve(strict=False) + except (OSError, RuntimeError) as exc: + # A broken or looping link in an unselected task must not block a selected task. + if task_id not in wanted_set: + continue + raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc + if not resolved.is_relative_to(content_root): + # Remove the escaping link from the exported artifacts as well. The + # candidate may be task.json itself or a symlinked task directory. + for candidate in (path, *path.parents): + if candidate == content_root: + break + if candidate.is_symlink(): + candidate.unlink() + break + raise TaskPathEscapeError( + f"{shown}: path escapes the repository (resolves outside the exported eval tree)" + ) + if task_id not in wanted_set: + continue + try: + resolved = path.resolve(strict=True) + except (OSError, RuntimeError) as exc: + raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc + found[task_id] = (path, resolved) + + 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}/{t}/task.json: {'; '.join(problems)}") - return [Task(t, raws[t], found[t].parent) for t in wanted] + 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 _read_task_json(path: Path, shown: str) -> Any: 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..90ed0d0b1 --- /dev/null +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -0,0 +1,124 @@ +# 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 not (content / "tasks/broken/task.json").exists() + + +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) + + +@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() From 9829db38414121fc346d59f3bd0c8547544cde49 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:59:32 +0600 Subject: [PATCH 02/11] Restore repo run sign-in preflight in symlink fix Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/commands/repo_run.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 9df6169c6..3918c18c8 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -28,6 +28,8 @@ from dokimi.digest import tree_digest from dokimi.files import InputError from dokimi.commands._shared import run_errors +from dokimi.repos.sign_in import NotSignedIn, check_container_signed_in +from dokimi.repos.sign_in import add_flag as add_preflight_flag, apply_flag as apply_preflight_flag def refuse_typed(source, args: argparse.Namespace) -> None: @@ -407,6 +409,7 @@ def cmd_repo_tasks_authoring(args: argparse.Namespace) -> None: def cmd_repo_run(args: argparse.Namespace) -> None: """Run agents on the tasks, grade every run, write one result.json per cell.""" + apply_preflight_flag(args) arms = [a for spec in args.arm for a in spec.split(",") if a] batch_dir = (Path(args.out) / args.batch).resolve() with contextlib.ExitStack() as lock: # held until every cell is graded @@ -465,7 +468,8 @@ def _run_locked(args: argparse.Namespace, arms: list[str], batch_dir: Path, lock write_skill_pin(batch_dir, skill_pin) label_host = ctx.manifest.label_host if args.label_host is None else args.label_host # the flag overrides summary = run_batch(ctx, tasks, arms, options, args.reps, batch_dir, jobs=args.jobs, force=args.force, - max_batch_usd=args.max_batch_usd, log=_progress, label_host=label_host) + max_batch_usd=args.max_batch_usd, log=_progress, label_host=label_host, + preflight=lambda task, opts: check_container_signed_in(ctx, opts, task, batch_dir / "_eval")) except InputError: # see cmd_repo_tasks_check (#826) raise except DockerError as exc: # the docker CLI or daemon failed: infrastructure, not a verdict (§2.6) @@ -473,6 +477,8 @@ def _run_locked(args: argparse.Namespace, arms: list[str], batch_dir: Path, lock sys.exit(EXIT_INFRA) except ConfigRefused as exc: # a config the agent's CLI rejects: refused before any cell, not rerun (exit 2) raise InputError(str(exc)) from exc # cli.main prints it and exits 2 + except NotSignedIn as exc: # the sign-in preflight: a missing credential, exit 2, no cell run + raise InputError(str(exc)) from exc except run_errors() as exc: print(f"✗ {exc}", file=sys.stderr) sys.exit(1) @@ -753,6 +759,7 @@ def register(repo_sub, eval_sub, positive_int, source_help: str, cache_help: str "per field what was met and what was not (host_match in result.json) instead of marking " "the cells unsupported; results carry the host fingerprint, so `repo report` groups them by it. " "Default: the manifest's label_host (off); --no-label-host overrides a manifest that sets it") + add_preflight_flag(run_p) run_p.set_defaults(func=cmd_repo_run) report_p = repo_sub.add_parser("report", help="Per (task, arm, model) table over a batch directory") From 5822096bc15fb212b7cc534a9ba6a4e1c3e31c2c Mon Sep 17 00:00:00 2001 From: sazid63 <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:43:27 +0000 Subject: [PATCH 03/11] fix(repo): harden task path regression coverage Cover dangling external links and in-tree task-file links, and split task-file handling out of workspace.py to satisfy the growth ratchet. Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- dokimi/dokimi/repos/task_files.py | 52 +++++++++++++++++++ dokimi/dokimi/repos/workspace.py | 47 ++--------------- .../tests/test_repo_run_task_link_escape.py | 32 ++++++++++++ 3 files changed, 88 insertions(+), 43 deletions(-) create mode 100644 dokimi/dokimi/repos/task_files.py diff --git a/dokimi/dokimi/repos/task_files.py b/dokimi/dokimi/repos/task_files.py new file mode 100644 index 000000000..4751a03a8 --- /dev/null +++ b/dokimi/dokimi/repos/task_files.py @@ -0,0 +1,52 @@ +# 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]]: + 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): + for candidate in (path, *path.parents): + if candidate == content_root: + break + if candidate.is_symlink(): + candidate.unlink() + break + 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 + 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 a4b77de6b..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 @@ -53,7 +52,7 @@ from .arms import ArmError, Skill, resolve_skills, tree_sha256 from .bases import _patch_paths -from .errors import PrepError, TaskPathEscapeError +from .errors import PrepError from .export_skips import refuse_skipped from .guidance_arms import GUIDANCE_SKILL_DESCRIPTION, _apply_as_skill, _apply_format # noqa: F401 from .guidance_format import FORMATS @@ -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 @@ -273,40 +273,9 @@ def load_tasks(content_dir: Path, manifest: RepoManifest, ids: list[str] | None if missing: raise PrepError(f"no such task(s) under {manifest.tasks}: {', '.join(missing)}") - content_root = content_dir.resolve() - wanted_set = set(wanted) - found: dict[str, tuple[Path, Path]] = {} - for task_id, path in found_paths.items(): - shown = f"{manifest.tasks}/{task_id}/task.json" - try: - # Non-strict resolution still reveals an escaping symlink whose target is missing. - resolved = path.resolve(strict=False) - except (OSError, RuntimeError) as exc: - # A broken or looping link in an unselected task must not block a selected task. - if task_id not in wanted_set: - continue - raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc - if not resolved.is_relative_to(content_root): - # Remove the escaping link from the exported artifacts as well. The - # candidate may be task.json itself or a symlinked task directory. - for candidate in (path, *path.parents): - if candidate == content_root: - break - if candidate.is_symlink(): - candidate.unlink() - break - raise TaskPathEscapeError( - f"{shown}: path escapes the repository (resolves outside the exported eval tree)" - ) - if task_id not in wanted_set: - continue - try: - resolved = path.resolve(strict=True) - except (OSError, RuntimeError) as exc: - raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc - found[task_id] = (path, resolved) + found = resolve_task_paths(found_paths, set(wanted), content_dir.resolve(), tasks) - raws = {task_id: _read_task_json(found[task_id][1], f"{manifest.tasks}/{task_id}/task.json") + 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"] @@ -315,14 +284,6 @@ def load_tasks(content_dir: Path, manifest: RepoManifest, ids: list[str] | None return [Task(task_id, raws[task_id], found[task_id][0].parent) for task_id in wanted] -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 - - def source_git_dir(source: RepoSource, tree: RepoTree, cache_dir: Path | None = None) -> Path: """A git directory with full history and blobs for ``source``: task bases are checked out from it. diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index 90ed0d0b1..497caa673 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -65,6 +65,38 @@ def test_unselected_external_task_link_is_still_refused(tmp_path: Path) -> None: assert not (content / "tasks/broken/task.json").exists() +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) + assert not (content / "tasks/broken/task.json").exists() + + +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_selected_dangling_task_link_is_still_refused(tmp_path: Path) -> None: root, _ = make_repo(tmp_path / "fixture") broken = root / ".agent-eval/tasks/broken" From e5de6a4981c85113a25d30f54ad8a7ca48ffd39f Mon Sep 17 00:00:00 2001 From: sazid63 <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:58:05 +0000 Subject: [PATCH 04/11] test(repo): cover task link edge cases Exercise task symlink loops and assert repo-run preflight surfaces task path escapes. Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- dokimi/docs/repo-evaluation-contract.md | 7 ++- .../tests/test_repo_run_task_link_escape.py | 43 +++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index 69c937850..659beef3c 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -372,8 +372,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 `