Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### Security

- **Reject task files outside the evaluation tree** — repo run and eval check refuse a task.json whose resolved path escapes the exported evaluation tree, preventing unrelated host files from entering run artifacts.
7 changes: 5 additions & 2 deletions dokimi/docs/repo-evaluation-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,11 @@ The schema is `dokimi/schemas/suite_manifest.v1.json`; an example is

The framework interprets the **core** and **workspace** keys. Every other key
belongs to the repository's grader and is passed through unread, except `grader`, which the framework reads to tell a `dokimi:` name (§4.5) from a repository's.
`eval check --schema-only` reports a `task.json` that is not valid JSON, not a JSON object, or cannot be
read (a link that loops, names a directory or nothing, or leaves the repository, in a tree or at `<dir>@rev`) as an `error:` line, and exits 1.
`eval check --schema-only` reports a `task.json` that is not valid JSON, not a JSON
object, or cannot be read (a link that loops, names a directory or nothing, or
leaves the repository, in a tree or at `<dir>@rev`) as an `error:` line, and exits 1.
`repo run` also refuses task paths that escape the exported eval tree; an unrelated
dangling task link does not block a run that selects other tasks.

| Key | Required | Read by | Meaning |
|---|---|---|---|
Expand Down
6 changes: 6 additions & 0 deletions dokimi/dokimi/commands/repo_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,13 @@ def _suite_pin(suite) -> dict[str, Any]:
def _require_grade(content: Path, manifest: RepoManifest, ids: list[str] | None) -> None:
"""Refuse the selected tasks when one needs ``entry_points.grade`` and the manifest has none."""
from dokimi.repos.manifest import ManifestError, TaskSummary, grade_problems
from dokimi.repos.errors import TaskPathEscapeError
from dokimi.repos.workspace import PrepError, load_tasks

try:
tasks = load_tasks(content, manifest, ids)
except TaskPathEscapeError as exc:
raise InputError(str(exc)) from exc
except (OSError, ValueError, PrepError):
return # reported where the run loads its tasks
graders = [(t.id, str(t.raw.get("grader") or "") if isinstance(t.raw, dict) else "") for t in tasks]
Expand All @@ -173,10 +176,13 @@ def _require_grade(content: Path, manifest: RepoManifest, ids: list[str] | None)
def _uses_builtin_graders(content: Path, manifest: RepoManifest) -> bool:
"""Whether a task of the exported eval dir names a ``dokimi:`` grader; an unreadable task.json counts."""
from dokimi.repos.graders import builtin_name
from dokimi.repos.errors import TaskPathEscapeError
from dokimi.repos.workspace import PrepError, load_tasks

try:
tasks = load_tasks(content, manifest, check_keys=False)
except TaskPathEscapeError:
raise
except (OSError, ValueError, PrepError): # PrepError: a task.json that is not JSON or nested too deeply (#975)
return True
return any(isinstance(t.raw, dict) and builtin_name(t.raw.get("grader")) is not None for t in tasks)
Expand Down
4 changes: 4 additions & 0 deletions dokimi/dokimi/repos/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,9 @@ class PrepError(RuntimeError):
"""A workspace could not be prepared (a patch does not apply, a base is missing, ...)."""


class TaskPathEscapeError(PrepError):
"""A task file resolves outside the exported evaluation tree."""


class CodeIndexError(ValueError):
"""A SCIP code index cannot be read: empty, truncated, garbled, or not an index at all."""
55 changes: 55 additions & 0 deletions dokimi/dokimi/repos/task_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Copyright (C) 2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""Resolve and read task files from the exported eval tree."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from .errors import PrepError, TaskPathEscapeError


def resolve_task_paths(
paths: dict[str, Path], wanted: set[str], content_root: Path, task_root: str,
) -> dict[str, tuple[Path, Path]]:
"""Validate containment for every discovered task before resolving selected files.

This function deliberately does not unlink or otherwise clean up rejected paths:
an exported entry can resolve through a directory symlink into caller-owned files.
"""
found: dict[str, tuple[Path, Path]] = {}
for task_id, path in paths.items():
shown = f"{task_root}/{task_id}/task.json"
try:
resolved = path.resolve(strict=False)
except (OSError, RuntimeError) as exc:
if task_id not in wanted:
continue
raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc
if not resolved.is_relative_to(content_root):
raise TaskPathEscapeError(
f"{shown}: path escapes the repository (resolves outside the exported eval tree)"
)
if task_id not in wanted:
continue
try:
resolved = path.resolve(strict=True)
except (OSError, RuntimeError) as exc:
raise PrepError(f"{shown}: cannot resolve task.json: {exc}") from exc
if not resolved.is_relative_to(content_root):
raise TaskPathEscapeError(
f"{shown}: path escapes the repository (resolves outside the exported eval tree)"
)
found[task_id] = (path, resolved)
return found


def read_task_json(path: Path, shown: str) -> Any:
"""Parse task JSON and report malformed content with its repository path."""
try:
return json.loads(path.read_text(encoding="utf-8"))
except (ValueError, RecursionError) as exc:
raise PrepError(f"{shown}: cannot read task.json: {type(exc).__name__}: {str(exc)[:200]}") from exc

Check warning on line 55 in dokimi/dokimi/repos/task_files.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `200` -> `201`
31 changes: 14 additions & 17 deletions dokimi/dokimi/repos/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
from __future__ import annotations

import hashlib
import json
import os
import posixpath
import re
Expand All @@ -65,6 +64,7 @@
from .skill_dirs import only_empty_dirs
from .source import (GitTree, RepoSource, RepoTree, SourceError, cache_path, clone_once, default_cache_dir,
isolated_git_env, resolve_rev)
from .task_files import read_task_json, resolve_task_paths
from .uptake import MCP_CONFIG, base_servers, mcp_servers
from .useful_spec import Useful, parse_useful
from dokimi.treatments.specs import COMBINE, split_parts
Expand Down Expand Up @@ -264,27 +264,24 @@ def load_tasks(content_dir: Path, manifest: RepoManifest, ids: list[str] | None
No task at all is refused: a check or run over none would report 0/0 as a pass."""
eval_dir, tasks = manifest.run_paths()
tasks_dir = content_dir / PurePosixPath(tasks).relative_to(eval_dir)
found = {p.parent.name: p for p in sorted(tasks_dir.glob("*/task.json"))}
if not found:
paths = sorted(tasks_dir.glob("*/task.json"))
found_paths = {path.parent.name: path for path in paths}
if not found_paths:
raise PrepError(f"no task under {manifest.tasks} (no */task.json): nothing to check or run")
wanted = ids or sorted(found)
missing = [t for t in wanted if t not in found]
wanted = ids or sorted(found_paths)
missing = [task_id for task_id in wanted if task_id not in found_paths]
if missing:
raise PrepError(f"no such task(s) under {manifest.tasks}: {', '.join(missing)}")
raws = {t: _read_task_json(found[t], f"{manifest.tasks}/{t}/task.json") for t in wanted}
for t, raw in (raws.items() if check_keys else ()): # the checks of `eval check --schema-only`, before a cell depends on them (#1301)
problems = task_key_problems(raw, t) if isinstance(raw, dict) else ["must be a JSON object"]
if problems:
raise PrepError(f"{manifest.tasks}/{t}/task.json: {'; '.join(problems)}")
return [Task(t, raws[t], found[t].parent) for t in wanted]

found = resolve_task_paths(found_paths, set(wanted), content_dir.resolve(), tasks)

def _read_task_json(path: Path, shown: str) -> Any:
"""The parsed ``task.json``; one that is not JSON, not UTF-8 or nested too deeply is a ``PrepError`` naming it as ``shown``, its path in the repo (#975)."""
try:
return json.loads(path.read_text(encoding="utf-8"))
except (ValueError, RecursionError) as exc:
raise PrepError(f"{shown}: cannot read task.json: {type(exc).__name__}: {str(exc)[:200]}") from exc
raws = {task_id: read_task_json(found[task_id][1], f"{manifest.tasks}/{task_id}/task.json")
for task_id in wanted}
for task_id, raw in (raws.items() if check_keys else ()): # the checks of `eval check --schema-only`, before a cell depends on them (#1301)
problems = task_key_problems(raw, task_id) if isinstance(raw, dict) else ["must be a JSON object"]
if problems:
raise PrepError(f"{manifest.tasks}/{task_id}/task.json: {'; '.join(problems)}")
return [Task(task_id, raws[task_id], found[task_id][0].parent) for task_id in wanted]


def source_git_dir(source: RepoSource, tree: RepoTree, cache_dir: Path | None = None) -> Path:
Expand Down
Loading
Loading