From cb0aac1f9345d1bc1b60ed6de0ed3bfc06911d9b Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:42:55 +0600 Subject: [PATCH 01/24] Reject task.json symlinks that escape the repository Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/commands/repo_run.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 0fc3e3031..9fd20a679 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -84,6 +84,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.json symlinks 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") @@ -134,6 +135,24 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): return ctx, tree +def _check_task_json_links(tree, manifest) -> None: + """Refuse task.json links that resolve outside the source repository before exporting eval_dir. + + The export preserves symlinks. Reading task.json from the exported copy would otherwise follow + an absolute link on the host and could copy arbitrary local data into the batch artifacts. + """ + _eval_dir, tasks = manifest.run_paths() + for rel in tree.files(): + parent = rel.rpartition("/")[0] + if not rel.endswith("/task.json") or parent.rpartition("/")[0] != tasks: + continue + try: + tree.resolve(rel) + except SourceArgumentError as exc: + if str(exc).startswith("path escapes the repository:"): + raise InputError(str(exc)) from exc + + def _suite_bases(args: argparse.Namespace, tree, content: Path, manifest: RepoManifest, cache_dir: Path | None): """The base checkouts of ``--suite`` (contract §2.1), or None: every base is then in the eval source.""" if args.suite is None: From e5297d4175cbfe104ea7dad3af9f2029187700a9 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:43:09 +0600 Subject: [PATCH 02/24] Test repo run rejection of escaping task.json symlinks Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- .../tests/test_repo_run_task_link_escape.py | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 dokimi/tests/test_repo_run_task_link_escape.py 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..b933233db --- /dev/null +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -0,0 +1,70 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""repo run must refuse task.json symlinks that leave the source repository.""" + +import subprocess +import sys +from pathlib import Path + +import pytest + +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", ["", "@HEAD"]) +def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str) -> None: + 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 = tmp_path / "outside.json" + outside.write_text( + '{"id":"t1","base":"%s","instruction":"x","grader":"g"}' % base, + encoding="utf-8", + ) + (task_dir / "task.json").symlink_to(outside) + _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() From 3f7721577cf1ab63c2b18d054bdfd77c6eeebe87 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:58:21 +0600 Subject: [PATCH 03/24] Clarify repo run path refusal behavior Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/commands/repo_run.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 9fd20a679..31e2449a2 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -33,8 +33,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 task-file links that leave the tree. + Other paths supplied by the tree are checked by the operation that reads them.""" from dokimi.repos.source import check_pinned_root try: From e28b86ee7a1f425c5dd2f88e8ed4ed0d4f4a5bb9 Mon Sep 17 00:00:00 2001 From: sazid63 <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:06:31 +0000 Subject: [PATCH 04/24] Reject task directory links that escape the repository Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/commands/repo_run.py | 11 +++++------ dokimi/tests/test_repo_run_task_link_escape.py | 18 +++++++++++++----- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 31e2449a2..534801e75 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -84,7 +84,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.json symlinks that leave the source repository + _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") @@ -136,18 +136,17 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): def _check_task_json_links(tree, manifest) -> None: - """Refuse task.json links that resolve outside the source repository before exporting eval_dir. + """Refuse task paths that resolve outside the source repository before exporting eval_dir. The export preserves symlinks. Reading task.json from the exported copy would otherwise follow - an absolute link on the host and could copy arbitrary local data into the batch artifacts. + a link on the host and could copy arbitrary local data into the batch artifacts. """ _eval_dir, tasks = manifest.run_paths() for rel in tree.files(): - parent = rel.rpartition("/")[0] - if not rel.endswith("/task.json") or parent.rpartition("/")[0] != tasks: + if rel != tasks and not rel.startswith(f"{tasks}/"): continue try: - tree.resolve(rel) + tree.resolve(rel, dirs=True) except SourceArgumentError as exc: if str(exc).startswith("path escapes the repository:"): raise InputError(str(exc)) from exc diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index b933233db..5ce49875d 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -29,8 +29,11 @@ def _git(repo: Path, *args: str) -> str: ).stdout.strip() -@pytest.mark.parametrize("suffix", ["", "@HEAD"]) -def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str) -> None: +@pytest.mark.parametrize( + ("suffix", "link_kind"), + [("", "file"), ("@HEAD", "file"), ("", "directory")], +) +def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str, link_kind: str) -> None: repo = tmp_path / "fx" task_dir = repo / ".agent-eval" / "tasks" / "t1" task_dir.mkdir(parents=True) @@ -42,12 +45,17 @@ def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str) -> None _git(repo, "add", "-A") _git(repo, "commit", "-qm", "base") base = _git(repo, "rev-parse", "HEAD") - outside = tmp_path / "outside.json" - outside.write_text( + 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", ) - (task_dir / "task.json").symlink_to(outside) + if link_kind == "file": + (task_dir / "task.json").symlink_to(outside_task / "task.json") + else: + task_dir.rmdir() + task_dir.symlink_to(outside_task, target_is_directory=True) _git(repo, "add", "-A") _git(repo, "commit", "-qm", "link") From a2c5de9cfa074225a6c3666b94c3d793c3b9c9ee Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:38:33 +0600 Subject: [PATCH 05/24] Reject task links escaping the exported eval directory Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/commands/repo_run.py | 42 +++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 534801e75..971a259b3 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -93,6 +93,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) @@ -142,16 +143,49 @@ def _check_task_json_links(tree, manifest) -> None: a link on the host and could copy arbitrary local data into the batch artifacts. """ _eval_dir, tasks = manifest.run_paths() - for rel in tree.files(): - if rel != tasks and not rel.startswith(f"{tasks}/"): - continue + # files() does not enumerate children of a symlinked task directory. + # Derive task IDs from ordinary descendants and directory-link entries, + # then resolve each task file through the alias as load_tasks() will. + task_prefix = f"{tasks}/" + task_ids = { + rel[len(task_prefix):].split("/", 1)[0] + for rel in tree.files() + if rel.startswith(task_prefix) and rel[len(task_prefix):] + } + for task_id in sorted(task_ids): + rel = f"{tasks}/{task_id}/task.json" try: - tree.resolve(rel, dirs=True) + tree.resolve(rel) except SourceArgumentError as exc: if str(exc).startswith("path escapes the repository:"): raise InputError(str(exc)) from exc +def _check_exported_task_json_links(content: Path, manifest: RepoManifest) -> None: + """Refuse task files whose links leave the exported eval directory. + + Relative links can be safe in the source repository but escape after the eval + directory is relocated to the batch's content directory. Check the paths in + that final location, before any task JSON is read. + """ + eval_dir, tasks = manifest.run_paths() + tasks_dir = content / Path(tasks).relative_to(eval_dir) + root = content.resolve() + if not tasks_dir.is_dir(): + return + for task_dir in tasks_dir.iterdir(): + task_json = task_dir / "task.json" + if not task_json.is_file(): + continue + try: + target = task_json.resolve(strict=True) + target.relative_to(root) + except ValueError as exc: + raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc + except (OSError, RuntimeError) as exc: + raise InputError(f"cannot safely resolve task file {tasks}/{task_dir.name}/task.json: {exc}") from exc + + def _suite_bases(args: argparse.Namespace, tree, content: Path, manifest: RepoManifest, cache_dir: Path | None): """The base checkouts of ``--suite`` (contract §2.1), or None: every base is then in the eval source.""" if args.suite is None: From 34c0d61f57c6ba493403c8808a84a3d16bbe3e2b Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:38:46 +0600 Subject: [PATCH 06/24] Test task directory aliases and relocated link escapes Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- .../tests/test_repo_run_task_link_escape.py | 56 ++++++++++++++++++- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index 5ce49875d..2bc1c67ff 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -31,7 +31,7 @@ def _git(repo: Path, *args: str) -> str: @pytest.mark.parametrize( ("suffix", "link_kind"), - [("", "file"), ("@HEAD", "file"), ("", "directory")], + [("", "file"), ("@HEAD", "file"), ("", "directory"), ("", "directory_with_external_file")], ) def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str, link_kind: str) -> None: repo = tmp_path / "fx" @@ -53,9 +53,15 @@ def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str, link_ki ) if link_kind == "file": (task_dir / "task.json").symlink_to(outside_task / "task.json") - else: + 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") @@ -76,3 +82,49 @@ def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str, link_ki 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: + 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 = repo / "outside.json" + outside.write_text( + '{"id":"t1","base":"%s","instruction":"x","grader":"g"}' % base, + 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 "path escapes the repository" in out, out + assert run.returncode == 2, out +\n \ No newline at end of file From ec4cc2c6a20004c9f0a40e3b4fb6d8838106f275 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:39:01 +0600 Subject: [PATCH 07/24] Make relocated host target present in regression test Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- dokimi/tests/test_repo_run_task_link_escape.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index 2bc1c67ff..13c583b19 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -102,11 +102,10 @@ def test_run_refuses_task_link_that_escapes_after_eval_dir_relocation(tmp_path: _git(repo, "add", "-A") _git(repo, "commit", "-qm", "base") base = _git(repo, "rev-parse", "HEAD") - outside = repo / "outside.json" - outside.write_text( - '{"id":"t1","base":"%s","instruction":"x","grader":"g"}' % base, - encoding="utf-8", - ) + 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") From d32e54ef53e12607227c9da1cdd2f4d8d4653264 Mon Sep 17 00:00:00 2001 From: sazid63 <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:52:35 +0000 Subject: [PATCH 08/24] Harden repo run task JSON link validation Cover task-directory aliases and links that escape after eval-directory relocation; document the refusal contract and changelog entry. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Signed-off-by: sazid63 <322897530+sazid63@users.noreply.github.com> --- .../20261204_sazid63_repo_run_task_links.md | 8 ++++++++ dokimi/docs/repo-evaluation-contract.md | 3 +++ dokimi/dokimi/commands/repo_run.py | 4 +--- dokimi/tests/test_repo_run_task_link_escape.py | 11 +++++------ 4 files changed, 17 insertions(+), 9 deletions(-) create mode 100644 dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md 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..8b269ddc9 --- /dev/null +++ b/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md @@ -0,0 +1,8 @@ + + +### Security + +- **Reject escaping task links** — `repo run` refuses task JSON symlinks 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..998ff9069 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -375,6 +375,9 @@ 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. + | 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 971a259b3..1668eb28e 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -143,9 +143,7 @@ def _check_task_json_links(tree, manifest) -> None: a link on the host and could copy arbitrary local data into the batch artifacts. """ _eval_dir, tasks = manifest.run_paths() - # files() does not enumerate children of a symlinked task directory. - # Derive task IDs from ordinary descendants and directory-link entries, - # then resolve each task file through the alias as load_tasks() will. + # files() skips symlinked task-directory descendants; resolve task.json through each alias. task_prefix = f"{tasks}/" task_ids = { rel[len(task_prefix):].split("/", 1)[0] diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index 13c583b19..36037e40c 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -87,10 +87,10 @@ def test_run_refuses_task_link_that_escapes_after_eval_dir_relocation(tmp_path: 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") + (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") + (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") @@ -111,7 +111,7 @@ def test_run_refuses_task_link_that_escapes_after_eval_dir_relocation(tmp_path: _git(repo, "commit", "-qm", "relocated task link") docker = tmp_path / "fakedocker" - docker.write_text("#!/bin/sh\\nexit 0\\n", encoding="utf-8") + docker.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") docker.chmod(0o755) batch = tmp_path / "b" run = subprocess.run( @@ -125,5 +125,4 @@ def test_run_refuses_task_link_that_escapes_after_eval_dir_relocation(tmp_path: ) out = run.stdout + run.stderr assert "path escapes the repository" in out, out - assert run.returncode == 2, out -\n \ No newline at end of file + assert run.returncode == 2, out \ No newline at end of file From 420d2e26bebc1734da5b8d8978a928138f70ed1f Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Fri, 4 Dec 2026 18:10:11 +0000 Subject: [PATCH 09/24] Add direct coverage for task link guards Exercise source and exported-tree validation directly, including unresolved paths and checks around eval export. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Signed-off-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- dokimi/docs/repo-evaluation-contract.md | 1 + dokimi/dokimi/commands/repo_run.py | 8 +- .../tests/test_repo_run_task_link_escape.py | 138 +++++++++++++++++- 3 files changed, 141 insertions(+), 6 deletions(-) diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index 998ff9069..c5bb37939 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -377,6 +377,7 @@ read (a link that loops, names a directory or nothing, or leaves the repository, `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. +An exported task path that cannot be safely resolved is also refused before the task JSON is read. | Key | Required | Read by | Meaning | |---|---|---|---| diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 1668eb28e..db7b8947a 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -137,7 +137,7 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): def _check_task_json_links(tree, manifest) -> None: - """Refuse task paths that resolve outside the source repository before exporting eval_dir. + """Refuse task links that leave the source repository before export (contract §3). The export preserves symlinks. Reading task.json from the exported copy would otherwise follow a link on the host and could copy arbitrary local data into the batch artifacts. @@ -146,7 +146,7 @@ def _check_task_json_links(tree, manifest) -> None: # files() skips symlinked task-directory descendants; resolve task.json through each alias. task_prefix = f"{tasks}/" task_ids = { - rel[len(task_prefix):].split("/", 1)[0] + rel[len(task_prefix):].partition("/")[0] for rel in tree.files() if rel.startswith(task_prefix) and rel[len(task_prefix):] } @@ -160,7 +160,7 @@ def _check_task_json_links(tree, manifest) -> None: def _check_exported_task_json_links(content: Path, manifest: RepoManifest) -> None: - """Refuse task files whose links leave the exported eval directory. + """Refuse task links that leave exported eval_dir, as required by contract §3. Relative links can be safe in the source repository but escape after the eval directory is relocated to the batch's content directory. Check the paths in @@ -176,7 +176,7 @@ def _check_exported_task_json_links(content: Path, manifest: RepoManifest) -> No if not task_json.is_file(): continue try: - target = task_json.resolve(strict=True) + target = task_json.resolve(strict=True) # mutation-ok[flip-bool]: is_file() already checks existence; containment is unchanged. target.relative_to(root) except ValueError as exc: raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index 36037e40c..408f5fe17 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -1,14 +1,19 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""repo run must refuse task.json symlinks that leave the source repository.""" +"""repo run rejects escaping task.json links (repository evaluation contract §3).""" 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 WorkTree + ROOT = Path(__file__).resolve().parents[1] MANIFEST = """schema: repo_manifest.v1 @@ -34,6 +39,7 @@ def _git(repo: Path, *args: str) -> str: [("", "file"), ("@HEAD", "file"), ("", "directory"), ("", "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) @@ -83,7 +89,9 @@ def test_run_refuses_task_link_leaving_repo(tmp_path: Path, suffix: str, link_ki 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) @@ -125,4 +133,130 @@ def test_run_refuses_task_link_that_escapes_after_eval_dir_relocation(tmp_path: ) out = run.stdout + run.stderr assert "path escapes the repository" in out, out - assert run.returncode == 2, out \ No newline at end of file + assert run.returncode == 2, out + + +def test_task_file_paths_are_derived_from_task_tree_entries() -> None: + paths = [] + tree = SimpleNamespace( + files=lambda: ["tasks/t1/task.json", "tasks/t2/nested/data", "tasks/", "other/file"], + resolve=paths.append, + ) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", "tasks")) + + repo_run._check_task_json_links(tree, manifest) + + assert paths == ["tasks/t1/task.json", "tasks/t2/task.json"] + + +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( + 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="path escapes the repository"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_resolution_error_is_reported( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Contract §3: an exported task path that cannot be safely resolved is refused.""" + 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_is_file = Path.is_file + original_resolve = Path.resolve + + def is_file(path: Path, *args, **kwargs) -> bool: + return True if path == task_json else original_is_file(path, *args, **kwargs) + + 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, "is_file", is_file) + monkeypatch.setattr(Path, "resolve", resolve) + with pytest.raises(InputError, match="cannot safely resolve task file"): + 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 got_tree, got_manifest: calls.append( + ("source", got_tree, got_manifest))) + monkeypatch.setattr(repo_run, "_check_exported_task_json_links", lambda got_content, got_manifest: calls.append( + ("exported", got_content, got_manifest))) + monkeypatch.setattr(repo_run, "_check_cache_paths", lambda *_: None) + monkeypatch.setattr(repo_run, "_require_grade", lambda *_: None) + 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 *_: 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", tree, manifest), ("exported", content, manifest)] \ No newline at end of file From 4661cd9df1d370447e65d8331572d2776bba992f Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Fri, 4 Dec 2026 18:54:35 +0000 Subject: [PATCH 10/24] Validate exported task links before file-type filtering Refuse escaped FIFO targets and dangling task symlinks, and assert task loading follows both containment checks. Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/commands/repo_run.py | 4 +- .../tests/test_repo_run_task_link_escape.py | 44 ++++++++++++++----- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index db7b8947a..c8c26d496 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -173,10 +173,10 @@ def _check_exported_task_json_links(content: Path, manifest: RepoManifest) -> No return for task_dir in tasks_dir.iterdir(): task_json = task_dir / "task.json" - if not task_json.is_file(): + if not task_json.is_symlink() and not task_json.exists(): continue try: - target = task_json.resolve(strict=True) # mutation-ok[flip-bool]: is_file() already checks existence; containment is unchanged. + target = task_json.resolve(strict=True) target.relative_to(root) except ValueError as exc: raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index 408f5fe17..875b83da1 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -3,6 +3,7 @@ """repo run rejects escaping task.json links (repository evaluation contract §3).""" +import os import subprocess import sys from pathlib import Path @@ -193,6 +194,32 @@ def test_exported_task_link_check_refuses_external_target(tmp_path: Path) -> Non 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="path escapes the repository"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_check_refuses_dangling_symlink(tmp_path: Path) -> None: + 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")) + + with pytest.raises(InputError, match="cannot safely resolve task file"): + repo_run._check_exported_task_json_links(content, manifest) + + def test_exported_task_link_resolution_error_is_reported( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -202,18 +229,13 @@ def test_exported_task_link_resolution_error_is_reported( task_json.parent.mkdir(parents=True) task_json.write_text("{}", encoding="utf-8") manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) - original_is_file = Path.is_file original_resolve = Path.resolve - def is_file(path: Path, *args, **kwargs) -> bool: - return True if path == task_json else original_is_file(path, *args, **kwargs) - 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, "is_file", is_file) monkeypatch.setattr(Path, "resolve", resolve) with pytest.raises(InputError, match="cannot safely resolve task file"): repo_run._check_exported_task_json_links(content, manifest) @@ -245,18 +267,16 @@ def test_context_checks_task_links_before_and_after_export(tmp_path: Path, monke 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 got_tree, got_manifest: calls.append( - ("source", got_tree, got_manifest))) - monkeypatch.setattr(repo_run, "_check_exported_task_json_links", lambda got_content, got_manifest: calls.append( - ("exported", got_content, got_manifest))) + 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 *_: 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 *_: content) + 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", tree, manifest), ("exported", content, manifest)] \ No newline at end of file + assert calls == ["source", "export", "exported", "grade"] \ No newline at end of file From 909be2dfbd21cb3b2db86977236bd6326d86a0ec Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:19:26 +0600 Subject: [PATCH 11/24] Move task path checks out of repo_run Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/commands/repo_run.py | 52 +++--------------------------- 1 file changed, 4 insertions(+), 48 deletions(-) diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index c8c26d496..132cc871c 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 @@ -136,54 +140,6 @@ def _context(args: argparse.Namespace, out: Path, source, pin: bool = False): return ctx, tree -def _check_task_json_links(tree, manifest) -> None: - """Refuse task links that leave the source repository before export (contract §3). - - The export preserves symlinks. Reading task.json from the exported copy would otherwise follow - a link on the host and could copy arbitrary local data into the batch artifacts. - """ - _eval_dir, tasks = manifest.run_paths() - # files() skips symlinked task-directory descendants; resolve task.json through each alias. - task_prefix = f"{tasks}/" - task_ids = { - rel[len(task_prefix):].partition("/")[0] - for rel in tree.files() - if rel.startswith(task_prefix) and rel[len(task_prefix):] - } - for task_id in sorted(task_ids): - rel = f"{tasks}/{task_id}/task.json" - try: - tree.resolve(rel) - except SourceArgumentError as exc: - if str(exc).startswith("path escapes the repository:"): - raise InputError(str(exc)) from exc - - -def _check_exported_task_json_links(content: Path, manifest: RepoManifest) -> None: - """Refuse task links that leave exported eval_dir, as required by contract §3. - - Relative links can be safe in the source repository but escape after the eval - directory is relocated to the batch's content directory. Check the paths in - that final location, before any task JSON is read. - """ - eval_dir, tasks = manifest.run_paths() - tasks_dir = content / Path(tasks).relative_to(eval_dir) - root = content.resolve() - if not tasks_dir.is_dir(): - return - for task_dir in tasks_dir.iterdir(): - task_json = task_dir / "task.json" - if not task_json.is_symlink() and not task_json.exists(): - continue - try: - target = task_json.resolve(strict=True) - target.relative_to(root) - except ValueError as exc: - raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc - except (OSError, RuntimeError) as exc: - raise InputError(f"cannot safely resolve task file {tasks}/{task_dir.name}/task.json: {exc}") from exc - - def _suite_bases(args: argparse.Namespace, tree, content: Path, manifest: RepoManifest, cache_dir: Path | None): """The base checkouts of ``--suite`` (contract §2.1), or None: every base is then in the eval source.""" if args.suite is None: From dc961ca295241f36b5d8902acc524064f92ec9d9 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:19:29 +0600 Subject: [PATCH 12/24] Mark intentional must-not-raise smoke test Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/tests/test_repo_run_task_link_escape.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py index 875b83da1..485c67cad 100644 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ b/dokimi/tests/test_repo_run_task_link_escape.py @@ -167,7 +167,7 @@ def test_task_directory_alias_to_external_file_is_refused(tmp_path: Path) -> Non @pytest.mark.parametrize(("create_tasks", "create_task_file"), [(False, False), (True, False), (True, True)]) -def test_exported_task_link_check_skips_missing_tasks( +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" From ac25f53af9d08f25fc1706b37afcc1af4c59072e Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:19:54 +0600 Subject: [PATCH 13/24] Extract task path validation helpers Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/repos/task_source.py | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 dokimi/dokimi/repos/task_source.py diff --git a/dokimi/dokimi/repos/task_source.py b/dokimi/dokimi/repos/task_source.py new file mode 100644 index 000000000..b8832f555 --- /dev/null +++ b/dokimi/dokimi/repos/task_source.py @@ -0,0 +1,50 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Validate task JSON 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_task_json_links(tree, manifest) -> None: + """Refuse task links that leave the source repository before export (contract §3).""" + _eval_dir, tasks = manifest.run_paths() + # files() skips symlinked task-directory descendants; resolve task.json through each alias. + task_prefix = f"{tasks}/" + task_ids = { + rel[len(task_prefix):].partition("/")[0] + for rel in tree.files() + if rel.startswith(task_prefix) and rel[len(task_prefix):] + } + for task_id in sorted(task_ids): + rel = f"{tasks}/{task_id}/task.json" + try: + tree.resolve(rel) + except SourceArgumentError as exc: + if str(exc).startswith("path escapes the repository:"): + raise InputError(str(exc)) from exc + + +def check_exported_task_json_links(content: Path, manifest) -> None: + """Refuse task links that leave exported eval_dir, before any task JSON is read.""" + eval_dir, tasks = manifest.run_paths() + tasks_dir = content / Path(tasks).relative_to(eval_dir) + root = content.resolve() + if not tasks_dir.is_dir(): + return + for task_dir in tasks_dir.iterdir(): + task_json = task_dir / "task.json" + if not task_json.is_symlink() and not task_json.exists(): + continue + try: + target = task_json.resolve(strict=True) + target.relative_to(root) + except ValueError as exc: + raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc + except (OSError, RuntimeError) as exc: + raise InputError(f"cannot safely resolve task file {tasks}/{task_dir.name}/task.json: {exc}") from exc From b7ff336c72fc1e5538478ee7c43b695b2df41515 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:38:23 +0600 Subject: [PATCH 14/24] Separate source-tree task-link regressions from loader tests Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- .../test_repo_run_source_task_link_escape.py | 294 ++++++++++++++++++ 1 file changed, 294 insertions(+) create mode 100644 dokimi/tests/test_repo_run_source_task_link_escape.py 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..071066761 --- /dev/null +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -0,0 +1,294 @@ +# 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 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")], +) +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 "path escapes the repository" in out, out + assert run.returncode == 2, out + + +def test_task_file_paths_are_derived_from_task_tree_entries() -> None: + paths = [] + tree = SimpleNamespace( + files=lambda: ["tasks/t1/task.json", "tasks/t2/nested/data", "tasks/", "other/file"], + resolve=paths.append, + ) + manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", "tasks")) + + repo_run._check_task_json_links(tree, manifest) + + assert paths == ["tasks/t1/task.json", "tasks/t2/task.json"] + + +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="path escapes the repository"): + 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="path escapes the repository"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_check_defers_in_tree_dangling_symlink(tmp_path: Path) -> None: + 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="path escapes the repository"): + repo_run._check_exported_task_json_links(content, manifest) + + +def test_exported_task_link_resolution_error_is_deferred( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Contract §3: an exported task path that cannot be safely resolved is refused.""" + 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"] \ No newline at end of file From 502b0f3c1004ceff80ba3bbd58f38035aa58bfb7 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:38:26 +0600 Subject: [PATCH 15/24] Preserve task selection when exported links are unresolved Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/repos/task_source.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/repos/task_source.py b/dokimi/dokimi/repos/task_source.py index b8832f555..df7c389ac 100644 --- a/dokimi/dokimi/repos/task_source.py +++ b/dokimi/dokimi/repos/task_source.py @@ -31,7 +31,7 @@ def check_task_json_links(tree, manifest) -> None: def check_exported_task_json_links(content: Path, manifest) -> None: - """Refuse task links that leave exported eval_dir, before any task JSON is read.""" + """Reject exported links 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() @@ -42,9 +42,14 @@ def check_exported_task_json_links(content: Path, manifest) -> None: if not task_json.is_symlink() and not task_json.exists(): continue try: - target = task_json.resolve(strict=True) + # strict=False still resolves dangling symlinks, so an external missing target + # is rejected. In-tree dangling links and loops are left to load_tasks(), + # which knows whether the task was selected. + target = task_json.resolve(strict=False) target.relative_to(root) except ValueError as exc: raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc - except (OSError, RuntimeError) as exc: - raise InputError(f"cannot safely resolve task file {tasks}/{task_dir.name}/task.json: {exc}") from exc + except (OSError, RuntimeError): + # Do not let an unrelated broken link block a selected task; the loader + # reports unresolved paths only when that task is actually selected. + continue From 17c1f8213ed1f51ad9572aa9179f87d0ffc3d8cd Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:38:28 +0600 Subject: [PATCH 16/24] Move source-tree checks into a dedicated regression module Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- .../tests/test_repo_run_task_link_escape.py | 282 ------------------ 1 file changed, 282 deletions(-) delete mode 100644 dokimi/tests/test_repo_run_task_link_escape.py diff --git a/dokimi/tests/test_repo_run_task_link_escape.py b/dokimi/tests/test_repo_run_task_link_escape.py deleted file mode 100644 index 485c67cad..000000000 --- a/dokimi/tests/test_repo_run_task_link_escape.py +++ /dev/null @@ -1,282 +0,0 @@ -# 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 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")], -) -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 "path escapes the repository" in out, out - assert run.returncode == 2, out - - -def test_task_file_paths_are_derived_from_task_tree_entries() -> None: - paths = [] - tree = SimpleNamespace( - files=lambda: ["tasks/t1/task.json", "tasks/t2/nested/data", "tasks/", "other/file"], - resolve=paths.append, - ) - manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", "tasks")) - - repo_run._check_task_json_links(tree, manifest) - - assert paths == ["tasks/t1/task.json", "tasks/t2/task.json"] - - -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="path escapes the repository"): - 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="path escapes the repository"): - repo_run._check_exported_task_json_links(content, manifest) - - -def test_exported_task_link_check_refuses_dangling_symlink(tmp_path: Path) -> None: - 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")) - - with pytest.raises(InputError, match="cannot safely resolve task file"): - repo_run._check_exported_task_json_links(content, manifest) - - -def test_exported_task_link_resolution_error_is_reported( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Contract §3: an exported task path that cannot be safely resolved is refused.""" - 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) - with pytest.raises(InputError, match="cannot safely resolve task file"): - 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"] \ No newline at end of file From df00c9e9d3bd5b30a280f75a489f32483802f0a3 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:39:15 +0600 Subject: [PATCH 17/24] Clarify selection-aware handling of unresolved task links Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/docs/repo-evaluation-contract.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index c5bb37939..c1c8bafcc 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -377,7 +377,8 @@ read (a link that loops, names a directory or nothing, or leaves the repository, `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. -An exported task path that cannot be safely resolved is also refused before the task JSON is read. +After export, a 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 | |---|---|---|---| From cdf4c96ef6d56d76dc036930ccc7acea4e4c683e Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:39:17 +0600 Subject: [PATCH 18/24] Clarify deferred task-link resolution regression Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/tests/test_repo_run_source_task_link_escape.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/tests/test_repo_run_source_task_link_escape.py b/dokimi/tests/test_repo_run_source_task_link_escape.py index 071066761..d69e2a98d 100644 --- a/dokimi/tests/test_repo_run_source_task_link_escape.py +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -235,7 +235,7 @@ def test_exported_task_link_check_refuses_external_dangling_target(tmp_path: Pat def test_exported_task_link_resolution_error_is_deferred( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """Contract §3: an exported task path that cannot be safely resolved is refused.""" + """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) From c85636ab840137d1920c5c0b4598b996069ba928 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:39:58 +0600 Subject: [PATCH 19/24] Cover task-directory aliases in pinned Git trees Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/tests/test_repo_run_source_task_link_escape.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/tests/test_repo_run_source_task_link_escape.py b/dokimi/tests/test_repo_run_source_task_link_escape.py index d69e2a98d..dd6400619 100644 --- a/dokimi/tests/test_repo_run_source_task_link_escape.py +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -37,7 +37,7 @@ def _git(repo: Path, *args: str) -> str: @pytest.mark.parametrize( ("suffix", "link_kind"), - [("", "file"), ("@HEAD", "file"), ("", "directory"), ("", "directory_with_external_file")], + [("", "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.""" From d472aabf1687ca3041cb057f051b7fc9754fa29b Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:59:14 +0000 Subject: [PATCH 20/24] Fix CI quality checks for task link validation Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/repos/task_source.py | 5 ++--- dokimi/tests/test_repo_run_source_task_link_escape.py | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/dokimi/dokimi/repos/task_source.py b/dokimi/dokimi/repos/task_source.py index df7c389ac..5c35a250d 100644 --- a/dokimi/dokimi/repos/task_source.py +++ b/dokimi/dokimi/repos/task_source.py @@ -42,9 +42,8 @@ def check_exported_task_json_links(content: Path, manifest) -> None: if not task_json.is_symlink() and not task_json.exists(): continue try: - # strict=False still resolves dangling symlinks, so an external missing target - # is rejected. In-tree dangling links and loops are left to load_tasks(), - # which knows whether the task was selected. + # strict=False resolves dangling symlinks, rejecting external targets. + # In-tree unresolved links remain selection-aware in load_tasks(). target = task_json.resolve(strict=False) target.relative_to(root) except ValueError as exc: diff --git a/dokimi/tests/test_repo_run_source_task_link_escape.py b/dokimi/tests/test_repo_run_source_task_link_escape.py index dd6400619..42431db23 100644 --- a/dokimi/tests/test_repo_run_source_task_link_escape.py +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -209,7 +209,7 @@ def test_exported_task_link_check_refuses_external_fifo(tmp_path: Path) -> None: repo_run._check_exported_task_json_links(content, manifest) -def test_exported_task_link_check_defers_in_tree_dangling_symlink(tmp_path: Path) -> None: +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) @@ -232,7 +232,7 @@ def test_exported_task_link_check_refuses_external_dangling_target(tmp_path: Pat repo_run._check_exported_task_json_links(content, manifest) -def test_exported_task_link_resolution_error_is_deferred( +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.""" From b7043b7d382b6a9753fce0afab5445a9a6b44dff Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:47:02 +0600 Subject: [PATCH 21/24] Tighten task path validation comment Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/repos/task_source.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/repos/task_source.py b/dokimi/dokimi/repos/task_source.py index 5c35a250d..af0e815c4 100644 --- a/dokimi/dokimi/repos/task_source.py +++ b/dokimi/dokimi/repos/task_source.py @@ -42,13 +42,11 @@ def check_exported_task_json_links(content: Path, manifest) -> None: if not task_json.is_symlink() and not task_json.exists(): continue try: - # strict=False resolves dangling symlinks, rejecting external targets. - # In-tree unresolved links remain selection-aware in load_tasks(). + # Resolve dangling targets to reject escapes; defer in-tree broken links + # and loops to selection-aware load_tasks(). target = task_json.resolve(strict=False) target.relative_to(root) except ValueError as exc: raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc except (OSError, RuntimeError): - # Do not let an unrelated broken link block a selected task; the loader - # reports unresolved paths only when that task is actually selected. continue From 8d6ae2d46bdb0115171f1a9d00be9a0df399f1c6 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:27:12 +0600 Subject: [PATCH 22/24] test: cover exported task directory symlink escape and equivalent mutations Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- dokimi/dokimi/repos/task_source.py | 4 ++-- .../test_repo_run_source_task_link_escape.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/repos/task_source.py b/dokimi/dokimi/repos/task_source.py index af0e815c4..23f72dd55 100644 --- a/dokimi/dokimi/repos/task_source.py +++ b/dokimi/dokimi/repos/task_source.py @@ -40,7 +40,7 @@ def check_exported_task_json_links(content: Path, manifest) -> None: for task_dir in tasks_dir.iterdir(): task_json = task_dir / "task.json" if not task_json.is_symlink() and not task_json.exists(): - continue + continue # mutation-ok[delete-statement]: resolving an absent in-tree path is still contained try: # Resolve dangling targets to reject escapes; defer in-tree broken links # and loops to selection-aware load_tasks(). @@ -49,4 +49,4 @@ def check_exported_task_json_links(content: Path, manifest) -> None: except ValueError as exc: raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc except (OSError, RuntimeError): - continue + continue # mutation-ok[delete-statement]: end-of-loop naturally defers this path diff --git a/dokimi/tests/test_repo_run_source_task_link_escape.py b/dokimi/tests/test_repo_run_source_task_link_escape.py index 42431db23..51f55cbca 100644 --- a/dokimi/tests/test_repo_run_source_task_link_escape.py +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -194,6 +194,21 @@ def test_exported_task_link_check_refuses_external_target(tmp_path: Path) -> Non 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="path escapes the repository"): + 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") From 81b27c55a65ef32c37921c2d4298a13eb25da835 Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:34:46 +0600 Subject: [PATCH 23/24] Fix task directory containment boundaries Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- .../20261204_sazid63_repo_run_task_links.md | 2 +- dokimi/docs/repo-evaluation-contract.md | 2 +- dokimi/dokimi/commands/repo_run.py | 4 +- dokimi/dokimi/repos/task_source.py | 59 +++--- .../test_repo_run_source_task_link_escape.py | 172 +++++++++++++++++- 5 files changed, 204 insertions(+), 35 deletions(-) diff --git a/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md b/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md index 8b269ddc9..f6152bcf3 100644 --- a/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md +++ b/dokimi/changelog.d/20261204_sazid63_repo_run_task_links.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### Security -- **Reject escaping task links** — `repo run` refuses task JSON symlinks that leave the repository or escape the relocated eval directory. +- **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 c1c8bafcc..1b76a28e2 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -377,7 +377,7 @@ read (a link that loops, names a directory or nothing, or leaves the repository, `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 target that resolves outside the exported eval directory is refused before it is read. +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 | diff --git a/dokimi/dokimi/commands/repo_run.py b/dokimi/dokimi/commands/repo_run.py index 132cc871c..c025aa0a3 100644 --- a/dokimi/dokimi/commands/repo_run.py +++ b/dokimi/dokimi/commands/repo_run.py @@ -37,8 +37,8 @@ def refuse_typed(source, args: argparse.Namespace) -> None: - """Exit 2 for what the user typed and for task-file links that leave the tree. - Other paths supplied by the tree are checked by the operation that reads them.""" + """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: diff --git a/dokimi/dokimi/repos/task_source.py b/dokimi/dokimi/repos/task_source.py index 23f72dd55..816c56bc0 100644 --- a/dokimi/dokimi/repos/task_source.py +++ b/dokimi/dokimi/repos/task_source.py @@ -1,7 +1,7 @@ # Copyright (C) 2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 -"""Validate task JSON paths before and after exporting a repository evaluation tree.""" +"""Validate task paths before and after exporting a repository evaluation tree.""" from __future__ import annotations @@ -11,42 +11,59 @@ 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 links that leave the source repository before export (contract §3).""" + """Refuse task directories and task files that leave the source repository (contract §3).""" _eval_dir, tasks = manifest.run_paths() - # files() skips symlinked task-directory descendants; resolve task.json through each alias. + 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 tree.files() + for rel in files if rel.startswith(task_prefix) and rel[len(task_prefix):] } for task_id in sorted(task_ids): - rel = f"{tasks}/{task_id}/task.json" - try: - tree.resolve(rel) - except SourceArgumentError as exc: - if str(exc).startswith("path escapes the repository:"): - raise InputError(str(exc)) from exc + 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 links outside eval_dir without pre-empting selection-aware loading.""" + """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]: resolving an absent in-tree path is still contained - try: - # Resolve dangling targets to reject escapes; defer in-tree broken links - # and loops to selection-aware load_tasks(). - target = task_json.resolve(strict=False) - target.relative_to(root) - except ValueError as exc: - raise InputError(f"path escapes the repository: {tasks}/{task_dir.name}/task.json") from exc - except (OSError, RuntimeError): - continue # mutation-ok[delete-statement]: end-of-loop naturally defers this path + 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 index 51f55cbca..36b040d7a 100644 --- a/dokimi/tests/test_repo_run_source_task_link_escape.py +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -13,7 +13,7 @@ from dokimi.commands import repo_run from dokimi.files import InputError -from dokimi.repos.source import WorkTree +from dokimi.repos.source import SourceArgumentError, WorkTree ROOT = Path(__file__).resolve().parents[1] @@ -133,21 +133,29 @@ def test_run_refuses_task_link_that_escapes_after_eval_dir_relocation(tmp_path: capture_output=True, text=True, cwd=ROOT, ) out = run.stdout + run.stderr - assert "path escapes the repository" in out, out + assert "task link escapes the exported eval directory" in out, out assert run.returncode == 2, out -def test_task_file_paths_are_derived_from_task_tree_entries() -> None: +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=paths.append, + resolve=resolve, ) manifest = SimpleNamespace(run_paths=lambda: (".agent-eval", "tasks")) repo_run._check_task_json_links(tree, manifest) - assert paths == ["tasks/t1/task.json", "tasks/t2/task.json"] + 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: @@ -190,7 +198,7 @@ def test_exported_task_link_check_refuses_external_target(tmp_path: Path) -> Non (task_dir / "task.json").symlink_to(outside) manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) - with pytest.raises(InputError, match="path escapes the repository"): + with pytest.raises(InputError, match="task link escapes the exported eval directory"): repo_run._check_exported_task_json_links(content, manifest) @@ -205,7 +213,7 @@ def test_exported_task_link_check_refuses_external_task_directory_alias(tmp_path (tasks / "t1").symlink_to(outside_task, target_is_directory=True) manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) - with pytest.raises(InputError, match="path escapes the repository"): + with pytest.raises(InputError, match="task directory escapes the exported eval directory"): repo_run._check_exported_task_json_links(content, manifest) @@ -220,7 +228,7 @@ def test_exported_task_link_check_refuses_external_fifo(tmp_path: Path) -> None: (task_dir / "task.json").symlink_to(outside_fifo) manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) - with pytest.raises(InputError, match="path escapes the repository"): + with pytest.raises(InputError, match="task link escapes the exported eval directory"): repo_run._check_exported_task_json_links(content, manifest) @@ -243,7 +251,7 @@ def test_exported_task_link_check_refuses_external_dangling_target(tmp_path: Pat (task_dir / "task.json").symlink_to(outside) manifest = SimpleNamespace(run_paths=lambda: ("eval", "eval/tasks")) - with pytest.raises(InputError, match="path escapes the repository"): + with pytest.raises(InputError, match="task link escapes the exported eval directory"): repo_run._check_exported_task_json_links(content, manifest) @@ -306,4 +314,148 @@ def test_context_checks_task_links_before_and_after_export(tmp_path: Path, monke repo_run._context(args, tmp_path, SimpleNamespace()) - assert calls == ["source", "export", "exported", "grade"] \ No newline at end of file + 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), 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 From 0fbb7d2b8fce8ed4d6bff0be8f7ff9b0c0ef903a Mon Sep 17 00:00:00 2001 From: Sajid Hossain <322897530+sazid63@users.noreply.github.com> Date: Sun, 6 Dec 2026 00:37:34 +0600 Subject: [PATCH 24/24] Correct relocated directory-link regression fixture Signed-off-by: Sajid Hossain <322897530+sazid63@users.noreply.github.com> --- .../test_repo_run_source_task_link_escape.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/dokimi/tests/test_repo_run_source_task_link_escape.py b/dokimi/tests/test_repo_run_source_task_link_escape.py index 36b040d7a..03f13ad40 100644 --- a/dokimi/tests/test_repo_run_source_task_link_escape.py +++ b/dokimi/tests/test_repo_run_source_task_link_escape.py @@ -316,6 +316,8 @@ def test_context_checks_task_links_before_and_after_export(tmp_path: Path, monke 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" @@ -329,6 +331,7 @@ def test_source_task_directory_link_without_task_json_is_refused(tmp_path: Path) 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" @@ -347,6 +350,7 @@ def test_source_task_directory_link_cannot_hide_a_task_file_inside_repo(tmp_path 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" @@ -360,6 +364,7 @@ def test_source_tasks_root_link_without_children_is_refused(tmp_path: Path) -> N repo_run._check_task_json_links(WorkTree(root), manifest) + def test_source_non_escape_resolution_error_is_deferred() -> None: calls = [] @@ -377,6 +382,7 @@ def resolve(path: str, dirs: bool = False) -> str: 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" @@ -390,6 +396,7 @@ def test_exported_empty_external_task_directory_is_refused(tmp_path: Path) -> No 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" @@ -406,6 +413,7 @@ def test_exported_task_directory_is_refused_even_if_task_json_resolves_inside(tm 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() @@ -418,6 +426,7 @@ def test_exported_empty_tasks_root_link_is_refused(tmp_path: Path) -> None: 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: @@ -427,10 +436,10 @@ def test_run_refuses_task_directory_that_escapes_after_eval_dir_relocation_witho task_dir.parent.mkdir(parents=True) outside_task = repo / "outside-task" outside_task.mkdir() - (repo / "AGENTS.md").write_text("hi\\n", encoding="utf-8") + (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") + (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") @@ -438,12 +447,12 @@ def test_run_refuses_task_directory_that_escapes_after_eval_dir_relocation_witho .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), target_is_directory=True) + 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.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") docker.chmod(0o755) batch = tmp_path / "b" run = subprocess.run(