fix(subagents): authorize local file acceptance checks before metadata probes (#8595)

* fix(subagents): authorize local file acceptance checks before metadata probes

The local sandbox gate covered only JSON and CSV criteria, so file_exists, file_non_empty and file_written still resolved paths and probed metadata for callers without sandbox:execute. Run the same admission check for every local file family before path resolution, returning an UNVERIFIED leaf on denial.

Refs #8594

* fix(subagents): reclassify sandbox after a lazy local initialization

The provider-error branch reused the sandbox kind captured before the size probe. That probe can lazily acquire the parent's local sandbox, so a genuine Error:-prefixed report was rejected as a provider failure. Recheck is_local_sandbox after the read and cover the lazy-initialization path.

Refs #8594

* fix(subagents): decide file acceptance admission on the owning event loop

The worker-thread gate reconstructed the authorization provider synchronously. Providers that create loop-affine clients in __init__ fail that construction off-loop, so under fail_closed an authorized batch's missing-file and above-cap verdicts degraded to UNVERIFIED. The task and batch entry points now decide sandbox:execute on the event loop and carry the decision (plus the authorization-scope marker) into the offloaded checklist; the synchronous path keeps its live per-leaf gate.

Refs #8594
This commit is contained in:
Loveca 2026-11-26 08:11:22 +08:00 committed by GitHub
parent 3efa7804b4
commit 75b6f6ae65
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 636 additions and 30 deletions

View File

@ -62,6 +62,7 @@ the async caller offloads the whole check with ``asyncio.to_thread``.
from __future__ import annotations
import asyncio
import base64
import binascii
import csv
@ -570,8 +571,19 @@ _JSON_READ_INNER_SCRIPT = (
)
def _read_bounded_file_content(runtime: Any, resolved: str, thread_data: Mapping[str, Any] | None, *, deadline: float | None = None) -> bytes | None:
"""Read up to the cap plus one byte to detect growth; return None if completeness is uncertain."""
def _read_bounded_file_content(
runtime: Any,
resolved: str,
thread_data: Mapping[str, Any] | None,
*,
deadline: float | None = None,
admission_denied: bool | None = None,
) -> bytes | None:
"""Read up to the cap plus one byte to detect growth; return None if completeness is uncertain.
``admission_denied=False`` carries an admission decision already made on
the owning event loop; ``None`` rechecks the live grant here (sync path).
"""
from deerflow.authz.sandbox_authz import authorize_sandbox_execution, safe_app_config
from deerflow.sandbox.tools import _resolve_local_read_path, ensure_sandbox_initialized, is_local_sandbox
@ -599,7 +611,8 @@ def _read_bounded_file_content(runtime: Any, resolved: str, thread_data: Mapping
return None
return payload[:-4] if payload.endswith(b"\n000") else None
# Reuse live sandbox authorization; persisted local sandbox IDs cannot bypass revoked permissions.
authorize_sandbox_execution(context=getattr(runtime, "context", None) or {}, app_config=safe_app_config())
if admission_denied is None:
authorize_sandbox_execution(context=getattr(runtime, "context", None) or {}, app_config=safe_app_config())
host_path = _resolve_local_read_path(resolved, thread_data)
if host_path == resolved:
return None
@ -629,7 +642,7 @@ def _reject_json_constant(value: str) -> None:
raise _NonStandardJSONConstant(value)
def _check_json_file(base: AcceptanceLeaf, runtime: Any, resolved: str, thread_data: Mapping[str, Any] | None, probed_size: int) -> AcceptanceLeaf:
def _check_json_file(base: AcceptanceLeaf, runtime: Any, resolved: str, thread_data: Mapping[str, Any] | None, probed_size: int, *, admission_denied: bool | None = None) -> AcceptanceLeaf:
"""Check JSON syntax only for complete UTF-8 documents within the read cap."""
from deerflow.sandbox.exceptions import SandboxError, SandboxFileNotFoundError
@ -637,7 +650,7 @@ def _check_json_file(base: AcceptanceLeaf, runtime: Any, resolved: str, thread_d
base["detail"] = f"JSON file exceeds {_FILE_CONTENT_READ_CAP_BYTES}-byte read cap; content not read"
return base
try:
content = _read_bounded_file_content(runtime, resolved, thread_data)
content = _read_bounded_file_content(runtime, resolved, thread_data, admission_denied=admission_denied)
except (FileNotFoundError, SandboxFileNotFoundError):
base["checked"] = True
base["detail"] = "file does not exist"
@ -683,14 +696,14 @@ def _parse_csv_columns(criterion: str) -> list[str] | None:
return columns if len(set(columns)) == len(columns) else None
def _check_csv_header(base: AcceptanceLeaf, runtime: Any, resolved: str, thread_data: Mapping[str, Any] | None, probed_size: int, columns: list[str]) -> AcceptanceLeaf:
def _check_csv_header(base: AcceptanceLeaf, runtime: Any, resolved: str, thread_data: Mapping[str, Any] | None, probed_size: int, columns: list[str], *, admission_denied: bool | None = None) -> AcceptanceLeaf:
"""Check only the first CSV record from a bounded prefix, never the data rows."""
from deerflow.sandbox.exceptions import SandboxError, SandboxFileNotFoundError
from deerflow.sandbox.tools import is_local_sandbox
deadline = time.monotonic() + 5 if is_local_sandbox(runtime) else None
try:
content = _read_bounded_file_content(runtime, resolved, thread_data, deadline=deadline)
content = _read_bounded_file_content(runtime, resolved, thread_data, deadline=deadline, admission_denied=admission_denied)
except (FileNotFoundError, SandboxFileNotFoundError):
base["checked"] = True
base["detail"] = "file does not exist"
@ -771,7 +784,16 @@ def _check_file_leaf(
size_prober: Callable[[Any, str, Mapping[str, Any] | None], int | None],
readable_prober: Callable[[Any, str, Mapping[str, Any] | None], bool | None],
csv_columns: list[str] | None = None,
admission_denied: bool | None = None,
) -> AcceptanceLeaf:
"""Check one file criterion.
``admission_denied`` carries a ``sandbox:execute`` decision made by the
async entry point (``check_acceptance_criteria_async``): ``True`` denies
without probing, ``False`` means already authorized, and ``None`` (the
synchronous default) runs the live gate here — a persisted local sandbox
id never retains a grant.
"""
criterion_path = path.strip()
# Lazy imports: the sandbox helpers pull the provider stack, and this
# package is imported in cycles with deerflow.tools (same pattern as
@ -783,20 +805,28 @@ def _check_file_leaf(
if family == "file_csv_columns" and csv_columns is None:
base["detail"] = "csv-columns requires a nonempty JSON array of unique nonempty strings"
return base
if family in ("file_json_valid", "file_csv_columns") and is_local_sandbox(runtime):
from deerflow.authz.sandbox_authz import authorize_sandbox_execution, safe_app_config
# Authorize before canonicalization or metadata probes can disclose file existence.
try:
authorize_sandbox_execution(context=getattr(runtime, "context", None) or {}, app_config=safe_app_config())
except SandboxError:
local = is_local_sandbox(runtime)
if local:
if admission_denied is True:
# The async entry point already denied sandbox:execute on the
# event loop that owns loop-affine providers; do not reconstruct
# the provider in this worker thread.
base["detail"] = "sandbox access denied; file unverified"
return base
if admission_denied is None:
from deerflow.authz.sandbox_authz import authorize_sandbox_execution, safe_app_config
# Authorize before canonicalization or metadata probes can disclose file existence or size.
try:
authorize_sandbox_execution(context=getattr(runtime, "context", None) or {}, app_config=safe_app_config())
except SandboxError:
base["detail"] = "sandbox access denied; file unverified"
return base
# Symlink escapes are a local-sandbox concern (host-visible links); remote
# providers resolve paths inside the sandbox where the parent cannot
# canonicalize, so the check stays lexical there.
resolved = _resolve_scoped_path(criterion_path, thread_data, resolve_symlinks=is_local_sandbox(runtime))
resolved = _resolve_scoped_path(criterion_path, thread_data, resolve_symlinks=local)
if resolved is None:
base["detail"] = "path is outside the shared thread workspace" if thread_data else "shared thread workspace unavailable"
return base
@ -814,9 +844,9 @@ def _check_file_leaf(
base["detail"] = "file size could not be established by a bounded probe; content not read"
return base
if family == "file_csv_columns" and csv_columns is not None:
return _check_csv_header(base, runtime, resolved, thread_data, probed_size, csv_columns)
return _check_csv_header(base, runtime, resolved, thread_data, probed_size, csv_columns, admission_denied=admission_denied)
if family == "file_json_valid":
return _check_json_file(base, runtime, resolved, thread_data, probed_size)
return _check_json_file(base, runtime, resolved, thread_data, probed_size, admission_denied=admission_denied)
if probed_size > _FILE_CONTENT_READ_CAP_BYTES:
# Large deliverable: the size probe proved the file exists, is
# regular, and is non-empty (size > cap > 0) — answering the
@ -857,6 +887,10 @@ def _check_file_leaf(
except (OSError, SandboxError) as exc:
base["detail"] = _bound_detail(f"read failed: {exc}")
return base
# The probes above may have lazily initialized the parent's sandbox, so the
# earlier classification can be stale: recheck before interpreting the
# provider result. A local read returns genuine content even when it starts
# with ``Error:``; only a remote provider encodes failures as text.
if not is_local_sandbox(runtime) and content.startswith(_PROVIDER_ERROR_PREFIX):
# A missing/inaccessible file on a REMOTE provider comes back as an
# error string, not an exception — the check ran and the file cannot
@ -2161,6 +2195,7 @@ def check_acceptance_criteria(
content_reader: Callable[[Any, str], str] | None = None,
size_prober: Callable[[Any, str, Mapping[str, Any] | None], int | None] | None = None,
readable_prober: Callable[[Any, str, Mapping[str, Any] | None], bool | None] | None = None,
admission_denied: bool | None = None,
) -> AcceptanceVerdict | None:
"""Check each decidable criterion against recorded execution evidence.
@ -2168,6 +2203,12 @@ def check_acceptance_criteria(
Synchronous: the async call site offloads via ``asyncio.to_thread`` —
``content_reader`` performs sandbox IO. The shared normalizer keeps the
checked list identical to the persisted and delegated list.
``admission_denied`` carries a ``sandbox:execute`` decision already made
by an async entry point (``check_acceptance_criteria_async``): ``True``
denies every local file leaf without probing, ``False`` skips the worker
gate, and ``None`` (default) runs the live gate per leaf. The worker never
reconstructs a loop-affine authorization provider off the event loop.
"""
criteria = normalize_acceptance_criteria(acceptance_criteria)
if not criteria:
@ -2198,6 +2239,7 @@ def check_acceptance_criteria(
size_prober=size_prober,
readable_prober=readable_prober,
csv_columns=_parse_csv_columns(criterion) if family == "file_csv_columns" else None,
admission_denied=admission_denied,
)
elif tests_match is not None:
leaf = _check_tests_passed_leaf(tests_match.group("command"), bash_executions, thread_data)
@ -2216,6 +2258,70 @@ def check_acceptance_criteria(
)
async def check_acceptance_criteria_async(
acceptance_criteria: list[str] | None,
*,
runtime: Any = None,
thread_data: Mapping[str, Any] | None = None,
bash_executions: list[dict[str, Any]] | None = None,
) -> AcceptanceVerdict | None:
"""Async entry point: decide ``sandbox:execute`` on the owning event loop.
Custom authorization providers may create loop-affine clients in
``__init__``, so the admission decision must be made here — before the
checklist is offloaded to a worker — not reconstructed inside the worker.
A denied decision travels with the offloaded call and degrades every local
file leaf to UNVERIFIED without probing; the worker performs no second
provider construction.
"""
from deerflow.authz.sandbox_authz import authorize_sandbox_execution_async, safe_app_config_async
from deerflow.sandbox.exceptions import SandboxError
from deerflow.sandbox.tools import _SANDBOX_AUTHORIZATION_CHECKED, is_local_sandbox
criteria = normalize_acceptance_criteria(acceptance_criteria)
if not criteria:
return None
admission_denied: bool | None = None
if is_local_sandbox(runtime) and any(parse_file_criterion(criterion) is not None for criterion in criteria):
try:
await authorize_sandbox_execution_async(
context=getattr(runtime, "context", None) or {},
app_config=await safe_app_config_async(),
)
except SandboxError:
admission_denied = True
else:
admission_denied = False
if admission_denied is False:
# Carry the allow decision into the worker: the content read's own
# re-authorization (ensure_sandbox_initialized) must not reconstruct a
# loop-affine provider off the loop. Context variables propagate into
# asyncio.to_thread workers, same handoff as sandbox tool scopes.
token = _SANDBOX_AUTHORIZATION_CHECKED.set(True)
try:
return await asyncio.to_thread(
check_acceptance_criteria,
criteria,
runtime=runtime,
thread_data=thread_data,
bash_executions=bash_executions,
admission_denied=False,
)
finally:
_SANDBOX_AUTHORIZATION_CHECKED.reset(token)
return await asyncio.to_thread(
check_acceptance_criteria,
criteria,
runtime=runtime,
thread_data=thread_data,
bash_executions=bash_executions,
admission_denied=admission_denied,
)
def validate_acceptance_verdict(value: object) -> AcceptanceVerdict | None:
"""Structural check for a persisted verdict (read side trusts nothing)."""
if not isinstance(value, dict):

View File

@ -31,6 +31,7 @@ async def check_batch_acceptance(
from deerflow.authz.sandbox_authz import authorize_sandbox_execution_async
from deerflow.sandbox.lease import SANDBOX_LEASE_OWNER_CONTEXT_KEY, acquire_sandbox_client_lease, run_sync_lifecycle_operation
from deerflow.sandbox.sandbox_provider import get_sandbox_provider
from deerflow.sandbox.tools import _SANDBOX_AUTHORIZATION_CHECKED
criteria = await run_sync_lifecycle_operation(normalize_acceptance_criteria, criteria)
if not criteria:
@ -52,7 +53,15 @@ async def check_batch_acceptance(
runtime.state["sandbox"] = {"sandbox_id": lease.sandbox_id}
context[SANDBOX_LEASE_OWNER_CONTEXT_KEY] = lease.owner_id
# Drain blocking reads before releasing the holder, including shutdown.
return await run_sync_lifecycle_operation(check_acceptance_criteria, criteria, runtime=runtime, thread_data=thread_data, bash_executions=bash_executions)
# The sandbox:execute decision above was made on this event loop; carry
# it into the worker (context variables propagate into the offload) so
# neither the leaf gate nor the content read's re-authorization
# reconstructs a loop-affine provider off-loop.
token = _SANDBOX_AUTHORIZATION_CHECKED.set(True)
try:
return await run_sync_lifecycle_operation(check_acceptance_criteria, criteria, runtime=runtime, thread_data=thread_data, bash_executions=bash_executions, admission_denied=False)
finally:
_SANDBOX_AUTHORIZATION_CHECKED.reset(token)
finally:
if lease is not None:
await lease.release()

View File

@ -33,7 +33,7 @@ from deerflow.models.selection import authorize_selected_model
from deerflow.runtime.user_context import resolve_runtime_user_id
from deerflow.sandbox.security import LOCAL_BASH_SUBAGENT_DISABLED_MESSAGE, is_host_bash_allowed
from deerflow.subagents import SubagentExecutor, get_available_subagent_names, get_subagent_config
from deerflow.subagents.acceptance_checks import check_acceptance_criteria, render_acceptance_section
from deerflow.subagents.acceptance_checks import check_acceptance_criteria_async, render_acceptance_section
from deerflow.subagents.capacity import SubagentExecutionCapacity, configured_subagent_queue_timeout_seconds
from deerflow.subagents.config import resolve_subagent_model_name
from deerflow.subagents.context_snapshot import ParentContextSnapshot
@ -1322,8 +1322,10 @@ async def task_tool(
acceptance_verdict = None
if acceptance_criteria:
try:
acceptance_verdict = await asyncio.to_thread(
check_acceptance_criteria,
# The async entry point decides sandbox:execute on this
# event loop (loop-affine providers must be constructed
# here) and offloads the checklist itself.
acceptance_verdict = await check_acceptance_criteria_async(
acceptance_criteria,
runtime=runtime,
thread_data=thread_data,

View File

@ -186,6 +186,36 @@ async def test_json_acceptance_check_is_offloaded(monkeypatch, tmp_path, permitt
assert verdict["leaves"][0]["checked"] is permitted
@pytest.mark.parametrize("permitted", [True, False])
@pytest.mark.parametrize("exists", [True, False])
async def test_file_existence_acceptance_check_is_offloaded(monkeypatch, tmp_path, permitted, exists):
"""Ordinary delegation authorizes metadata probes in a worker thread and reports an unverified verdict on denial."""
from deerflow.authz.rbac import RbacAuthorizationProvider
from deerflow.config.authorization_config import AuthorizationConfig
runtime = _runtime(tmp_path)
(tmp_path / "probe.txt").write_text("probe body", encoding="utf-8")
provider = RbacAuthorizationProvider(roles={"user": {"sandbox": {"allow": "*" if permitted else []}}})
config = SimpleNamespace(authorization=AuthorizationConfig(enabled=True))
monkeypatch.setattr("deerflow.authz.sandbox_authz.resolve_authorization_provider", lambda config: provider)
monkeypatch.setattr("deerflow.config.get_app_config", lambda: config)
runtime.context.update(user_id="user-1", user_role="user")
if exists:
(tmp_path / "user-data" / "outputs" / "report.md").write_text("real body", encoding="utf-8")
_patch_task_tool_boundary(monkeypatch, tmp_path)
command = await task_tool_module.task_tool.coroutine(
runtime=runtime,
prompt="p",
subagent_type="general-purpose",
tool_call_id="tc-file-check",
acceptance_criteria=["file:../outputs/report.md exists"],
)
verdict = command.update["messages"][0].additional_kwargs["subagent_acceptance_verdict"]
assert verdict["all_hold"] is (permitted and exists)
assert verdict["leaves"][0]["family"] == "file_exists"
assert verdict["leaves"][0]["checked"] is permitted
async def test_blocking_probe_reader_actually_trips_the_gate(monkeypatch, tmp_path):
"""Meta-check: the same read on the event loop must raise BlockingError,
so the anchor above cannot go vacuously green. (The size probe is

View File

@ -7,11 +7,13 @@ import shlex
import subprocess
import sys
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
from deerflow.subagents.acceptance_checks import (
check_acceptance_criteria,
check_acceptance_criteria_async,
render_acceptance_section,
render_acceptance_segment,
validate_acceptance_verdict,
@ -52,6 +54,17 @@ def _prober(files: dict[str, str]):
return probe
@pytest.fixture
def no_sandbox_authz_config(monkeypatch):
"""Keep file-leaf tests from reading the developer's ``config.yaml``.
The local gate calls ``safe_app_config()`` for every file family, so a
developer's authorization-enabled config must not change these verdicts.
The real RBAC test patches the config itself and does not use this fixture.
"""
monkeypatch.setattr("deerflow.authz.sandbox_authz.safe_app_config", lambda: None)
def _bash_execution(command: str, *, status: str = "success", output_tail: str = "", shell_persistent: bool | None = False) -> dict:
return {
"tool_call_id": f"tc-{abs(hash(command)) % 10000}",
@ -185,7 +198,7 @@ class TestFileLeaves:
assert verdict["leaves"][0]["checked"] is False
@pytest.mark.skipif(os.name == "nt", reason="symlink creation needs privileges on Windows")
def test_symlink_escape_is_rejected_on_local_sandbox(self, tmp_path):
def test_symlink_escape_is_rejected_on_local_sandbox(self, no_sandbox_authz_config, tmp_path):
"""PR review: the scope check must follow symlinks on the local
sandbox — a workspace symlink into uploads must not satisfy a
workspace/outputs-scoped leaf with upload content."""
@ -215,7 +228,7 @@ class TestFileLeaves:
assert all(leaf["checked"] is False for leaf in verdict["leaves"])
assert verdict["unchecked"] == ["file:stolen.md exists", "file_written:stolen.md"]
def test_genuine_workspace_file_survives_symlink_resolution(self, tmp_path):
def test_genuine_workspace_file_survives_symlink_resolution(self, no_sandbox_authz_config, tmp_path):
workspace = tmp_path / "user-data" / "workspace"
outputs = tmp_path / "user-data" / "outputs"
workspace.mkdir(parents=True)
@ -254,7 +267,7 @@ class TestFileLeaves:
return SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}})
def test_error_prefixed_content_is_valid_on_local_sandbox(self):
def test_error_prefixed_content_is_valid_on_local_sandbox(self, no_sandbox_authz_config):
"""PR review: the local sandbox raises on missing files, so an
``Error:``-prefixed string from it is genuine content (a log or
report heading) — never a provider failure."""
@ -264,6 +277,29 @@ class TestFileLeaves:
verdict = check_acceptance_criteria([criterion], runtime=runtime, thread_data=THREAD_DATA, content_reader=_reader(files), size_prober=_prober(files))
assert verdict["leaves"][0]["holds"] is True, criterion
def test_error_prefixed_content_is_valid_after_lazy_local_init(self, no_sandbox_authz_config):
"""A task may start without a sandbox id; the size probe then acquires
the local sandbox. Reclassify after the probe so a genuine ``Error:``
report is not mistaken for a remote provider failure."""
runtime = SimpleNamespace(state={"sandbox": {}})
files = {"/mnt/user-data/outputs/error.log": "Error: summary of yesterday's incidents"}
def lazy_local_size_probe(*_args):
runtime.state["sandbox"]["sandbox_id"] = "local"
return len(files["/mnt/user-data/outputs/error.log"])
verdict = check_acceptance_criteria(
["file:../outputs/error.log exists"],
runtime=runtime,
thread_data=THREAD_DATA,
content_reader=_reader(files),
size_prober=lazy_local_size_probe,
)
leaf = verdict["leaves"][0]
assert (leaf["checked"], leaf["holds"]) == (True, True)
assert "exists" in leaf["detail"]
def test_binary_deliverable_holds_file_leaves(self):
"""PR review: a valid binary deliverable raises UnicodeDecodeError on
a text read — that proves existence and non-emptiness, not failure,
@ -304,6 +340,352 @@ class TestFileLeaves:
assert verdict["leaves"][0]["holds"] is True
class TestFileLeafAuthorization:
"""The local file families share the sandbox:execute admission gate with
JSON/CSV: a revoked grant must not reach a metadata probe."""
@pytest.mark.parametrize("sandbox_id", ["local", "local:user-1:thread-1"])
@pytest.mark.parametrize(
"criterion",
[
"file:../outputs/report.md exists",
"file:../outputs/report.md non-empty",
"file_written:../outputs/report.md",
"file:../outputs/report.json json-valid",
'file:../outputs/report.csv csv-columns:["id"]',
],
)
def test_local_file_families_authorize_before_metadata_probe(self, no_sandbox_authz_config, monkeypatch, sandbox_id, criterion):
from deerflow.sandbox.exceptions import SandboxError
authorize = Mock(side_effect=SandboxError("denied"))
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution", authorize)
size_prober = Mock(return_value=5)
content_reader = Mock(return_value="hello")
readable_prober = Mock(return_value=True)
runtime = SimpleNamespace(
state={"sandbox": {"sandbox_id": sandbox_id}},
context={"user_id": "user-1", "user_role": "user"},
)
verdict = check_acceptance_criteria(
[criterion],
runtime=runtime,
thread_data=THREAD_DATA,
content_reader=content_reader,
size_prober=size_prober,
readable_prober=readable_prober,
)
leaf = verdict["leaves"][0]
assert (leaf["checked"], leaf["holds"]) == (False, False)
assert leaf["detail"] == "sandbox access denied; file unverified"
assert verdict["unchecked"] == [criterion]
authorize.assert_called_once()
size_prober.assert_not_called()
content_reader.assert_not_called()
readable_prober.assert_not_called()
def test_local_file_family_still_runs_when_authorized(self, no_sandbox_authz_config, monkeypatch):
authorize = Mock(return_value=None)
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution", authorize)
files = {"/mnt/user-data/outputs/report.md": "hello"}
verdict = check_acceptance_criteria(
["file:../outputs/report.md exists"],
runtime=SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={}),
thread_data=THREAD_DATA,
content_reader=_reader(files),
size_prober=_prober(files),
)
assert verdict["leaves"][0]["holds"] is True
authorize.assert_called_once()
def test_large_file_written_authorizes_before_readable_probe(self, no_sandbox_authz_config, monkeypatch):
authorize = Mock(return_value=None)
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution", authorize)
readable = Mock(return_value=True)
verdict = check_acceptance_criteria(
["file_written:../outputs/big.bin"],
runtime=SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={}),
thread_data=THREAD_DATA,
content_reader=Mock(side_effect=AssertionError("content must not be read above the cap")),
size_prober=Mock(return_value=60_000),
readable_prober=readable,
)
leaf = verdict["leaves"][0]
assert (leaf["checked"], leaf["holds"]) == (True, True)
assert "read probe ok" in leaf["detail"]
authorize.assert_called_once()
readable.assert_called_once()
def test_large_file_written_does_not_open_when_denied(self, no_sandbox_authz_config, monkeypatch):
from deerflow.sandbox.exceptions import SandboxError
authorize = Mock(side_effect=SandboxError("denied"))
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution", authorize)
readable = Mock(return_value=True)
verdict = check_acceptance_criteria(
["file_written:../outputs/big.bin"],
runtime=SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={}),
thread_data=THREAD_DATA,
content_reader=Mock(side_effect=AssertionError("content must not be read")),
size_prober=Mock(return_value=60_000),
readable_prober=readable,
)
leaf = verdict["leaves"][0]
assert (leaf["checked"], leaf["holds"]) == (False, False)
assert leaf["detail"] == "sandbox access denied; file unverified"
authorize.assert_called_once()
readable.assert_not_called()
@pytest.mark.parametrize("sandbox_id", ["local", "local:user-1:thread-1"])
@pytest.mark.parametrize("content", [None, b"x" * 60_000], ids=["missing", "large"])
def test_revoked_grant_hides_exists_verdict(self, tmp_path, monkeypatch, sandbox_id, content):
"""A retained local sandbox id does not retain the grant: revocation
returns UNVERIFIED instead of revealing existence or size."""
from deerflow.authz.rbac import RbacAuthorizationProvider
from deerflow.config.authorization_config import AuthorizationConfig
from deerflow.subagents import acceptance_checks as checks
config = SimpleNamespace(authorization=AuthorizationConfig(enabled=True))
provider = RbacAuthorizationProvider(roles={"user": {"sandbox": {"allow": "*"}}})
monkeypatch.setattr("deerflow.config.get_app_config", lambda: config)
monkeypatch.setattr("deerflow.authz.sandbox_authz.resolve_authorization_provider", lambda config: provider)
runtime = SimpleNamespace(
state={"sandbox": {"sandbox_id": sandbox_id}},
context={"thread_id": "thread-1", "user_id": "user-1", "user_role": "user"},
)
if content is not None:
(tmp_path / "report.md").write_bytes(content)
criterion = "file:report.md exists"
def check():
return check_acceptance_criteria([criterion], runtime=runtime, thread_data={"workspace_path": str(tmp_path)})
allowed = check()["leaves"][0]
assert allowed["checked"] is True
assert allowed["holds"] == (content is not None)
if content is None:
assert allowed["detail"] == "file does not exist"
else:
assert "60000 bytes" in allowed["detail"]
provider = RbacAuthorizationProvider(roles={"user": {"sandbox": {"allow": []}}})
stat_spy = Mock(wraps=os.stat)
resolve_spy = Mock(wraps=checks._resolve_scoped_path)
with monkeypatch.context() as denied_patch:
denied_patch.setattr(os, "stat", stat_spy)
denied_patch.setattr(checks, "_resolve_scoped_path", resolve_spy)
revoked = check()["leaves"][0]
assert (revoked["checked"], revoked["holds"]) == (False, False)
assert revoked["detail"] == "sandbox access denied; file unverified"
stat_spy.assert_not_called()
resolve_spy.assert_not_called()
provider = RbacAuthorizationProvider(roles={"user": {"sandbox": {"allow": "*"}}})
restored = check()["leaves"][0]
assert restored["checked"] is True
assert restored["holds"] == (content is not None)
def test_local_out_of_scope_path_does_not_probe(self, no_sandbox_authz_config, monkeypatch):
authorize = Mock(return_value=None)
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution", authorize)
probe = Mock(side_effect=AssertionError("out-of-scope path must not be probed"))
verdict = check_acceptance_criteria(
["file:/etc/passwd exists"],
runtime=SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={}),
thread_data=THREAD_DATA,
size_prober=probe,
)
leaf = verdict["leaves"][0]
assert leaf["checked"] is False
assert "outside the shared thread workspace" in leaf["detail"]
authorize.assert_called_once()
probe.assert_not_called()
def test_local_missing_thread_data_does_not_probe(self, no_sandbox_authz_config, monkeypatch):
authorize = Mock(return_value=None)
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution", authorize)
probe = Mock(side_effect=AssertionError("missing workspace must not be probed"))
verdict = check_acceptance_criteria(
["file:report.md exists"],
runtime=SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={}),
thread_data=None,
size_prober=probe,
)
leaf = verdict["leaves"][0]
assert leaf["checked"] is False
assert "workspace unavailable" in leaf["detail"]
authorize.assert_called_once()
probe.assert_not_called()
def test_local_directory_is_unverified_through_the_leaf(self, no_sandbox_authz_config, monkeypatch, tmp_path):
authorize = Mock(return_value=None)
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution", authorize)
(tmp_path / "subdir").mkdir()
verdict = check_acceptance_criteria(
["file:subdir exists"],
runtime=SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={}),
thread_data={"workspace_path": str(tmp_path)},
)
leaf = verdict["leaves"][0]
assert leaf["checked"] is False
assert "file size could not be established" in leaf["detail"]
authorize.assert_called_once()
def test_invalid_csv_columns_is_a_syntax_error_without_probing(self, no_sandbox_authz_config):
probe = Mock(side_effect=AssertionError("invalid criteria must not probe"))
verdict = check_acceptance_criteria(
["file:report.csv csv-columns:[]"],
runtime=SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={}),
thread_data=THREAD_DATA,
size_prober=probe,
)
leaf = verdict["leaves"][0]
assert leaf["checked"] is False
assert "csv-columns requires" in leaf["detail"]
probe.assert_not_called()
class TestAsyncAdmission:
"""The async entry point decides sandbox:execute on the owning event loop;
a loop-affine provider must never be reconstructed in the checklist worker."""
@staticmethod
def _install_loop_affine_provider(monkeypatch, *, allow):
import asyncio
from types import ModuleType
from deerflow.authz.provider import AuthzDecision
from deerflow.config.authorization_config import AuthorizationConfig, AuthorizationProviderConfig
provider_module = ModuleType("loop_affine_acceptance_test_provider")
constructed_on = []
class LoopAffineProvider:
name = "loop-affine"
def __init__(self):
self.loop = asyncio.get_running_loop()
constructed_on.append(self.loop)
def authorize(self, request):
return AuthzDecision(allow=allow)
async def aauthorize(self, request):
assert asyncio.get_running_loop() is self.loop
return AuthzDecision(allow=allow)
def filter_resources(self, principal, resource_type, candidates):
return list(candidates)
provider_module.LoopAffineProvider = LoopAffineProvider
monkeypatch.setitem(sys.modules, provider_module.__name__, provider_module)
config = SimpleNamespace(
authorization=AuthorizationConfig(
enabled=True,
fail_closed=True,
default_role="user",
provider=AuthorizationProviderConfig(use=f"{provider_module.__name__}:LoopAffineProvider"),
)
)
monkeypatch.setattr("deerflow.config.get_app_config", lambda: config)
return constructed_on
@pytest.mark.parametrize("allow", [True, False])
@pytest.mark.parametrize("content", [None, b"x" * 60_000], ids=["missing", "large"])
def test_loop_affine_provider_decides_on_the_loop(self, tmp_path, monkeypatch, allow, content):
"""Metadata-only leaves keep their definitive verdicts under a provider
that can only be constructed on a running event loop."""
import asyncio
constructed_on = self._install_loop_affine_provider(monkeypatch, allow=allow)
if content is not None:
(tmp_path / "report.md").write_bytes(content)
runtime = SimpleNamespace(
state={"sandbox": {"sandbox_id": "local"}},
context={"thread_id": "thread-1", "user_id": "user-1", "user_role": "user"},
)
async def run():
loop = asyncio.get_running_loop()
verdict = await check_acceptance_criteria_async(
["file:report.md exists"],
runtime=runtime,
thread_data={"workspace_path": str(tmp_path)},
)
assert constructed_on == [loop]
return verdict
verdict = asyncio.run(run())
leaf = verdict["leaves"][0]
if allow:
assert leaf["checked"] is True
assert leaf["holds"] == (content is not None)
if content is None:
assert leaf["detail"] == "file does not exist"
else:
assert "60000 bytes" in leaf["detail"]
else:
assert (leaf["checked"], leaf["holds"]) == (False, False)
assert leaf["detail"] == "sandbox access denied; file unverified"
def test_denied_async_admission_does_not_probe(self, monkeypatch):
from deerflow.subagents import acceptance_checks as checks
self._install_loop_affine_provider(monkeypatch, allow=False)
probe = Mock(side_effect=AssertionError("denied admission must not probe"))
monkeypatch.setattr(checks, "_probe_file_size", probe)
monkeypatch.setattr(checks, "_resolve_scoped_path", Mock(side_effect=AssertionError("denied admission must not resolve")))
runtime = SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={"user_id": "user-1", "user_role": "user"})
import asyncio
verdict = asyncio.run(
check_acceptance_criteria_async(
["file:../outputs/report.md exists"],
runtime=runtime,
thread_data=THREAD_DATA,
)
)
leaf = verdict["leaves"][0]
assert (leaf["checked"], leaf["holds"]) == (False, False)
assert leaf["detail"] == "sandbox access denied; file unverified"
probe.assert_not_called()
def test_evidence_only_criteria_skip_admission(self, monkeypatch):
authorize = Mock(side_effect=AssertionError("evidence-only criteria need no sandbox admission"))
monkeypatch.setattr("deerflow.authz.sandbox_authz.authorize_sandbox_execution_async", authorize)
runtime = SimpleNamespace(state={"sandbox": {"sandbox_id": "local"}}, context={})
import asyncio
verdict = asyncio.run(
check_acceptance_criteria_async(
["tests_passed:pytest tests/check.py"],
runtime=runtime,
thread_data=THREAD_DATA,
bash_executions=[_bash_execution("pytest tests/check.py", output_tail="3 passed")],
)
)
assert verdict["leaves"][0]["holds"] is True
authorize.assert_not_called()
class TestFileLeafSizeProbe:
"""PR review: file leaves must never perform an unbounded read — large
deliverables are answered from a bounded size probe alone, and when the

View File

@ -434,3 +434,80 @@ async def test_only_effective_file_checks_request_sandbox_access(env, monkeypatc
assert all(leaf["family"] == "undecidable" for leaf in verdict["leaves"])
authorize.assert_not_awaited()
acquire.assert_not_called()
@pytest.mark.asyncio
@pytest.mark.parametrize("allow", [True, False])
@pytest.mark.parametrize("exists", [True, False])
async def test_loop_affine_provider_batch_verdicts(env, monkeypatch, tmp_path, allow, exists):
"""A provider constructible only on a running event loop must not turn
authorized metadata-only verdicts into UNVERIFIED (or leak them on deny):
the admission decision rides into the worker, which never reconstructs it."""
import sys
from types import ModuleType
from deerflow.authz.provider import AuthzDecision
from deerflow.config.authorization_config import AuthorizationConfig, AuthorizationProviderConfig
provider_module = ModuleType("loop_affine_batch_test_provider")
constructed_on = []
class LoopAffineProvider:
name = "loop-affine"
def __init__(self):
self.loop = asyncio.get_running_loop()
constructed_on.append(self.loop)
def authorize(self, request):
return AuthzDecision(allow=allow)
async def aauthorize(self, request):
assert asyncio.get_running_loop() is self.loop
return AuthzDecision(allow=allow)
def filter_resources(self, principal, resource_type, candidates):
return list(candidates)
provider_module.LoopAffineProvider = LoopAffineProvider
monkeypatch.setitem(sys.modules, provider_module.__name__, provider_module)
from deerflow.config.app_config import AppConfig, reset_app_config, set_app_config
from deerflow.config.model_config import ModelConfig
from deerflow.config.sandbox_config import SandboxConfig
from deerflow.config.skills_config import SkillsConfig
skills_root = tmp_path / "skills"
skills_root.mkdir()
config = AppConfig(
models=[ModelConfig(name="gpt-4", model="gpt-4", use="langchain_openai:ChatOpenAI")],
sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider"),
skills=SkillsConfig(path=str(skills_root)),
authorization=AuthorizationConfig(
enabled=True,
fail_closed=True,
default_role="user",
provider=AuthorizationProviderConfig(use=f"{provider_module.__name__}:LoopAffineProvider"),
),
)
set_app_config(config)
monkeypatch.setattr("deerflow.config.get_app_config", lambda: config)
env.service._app_config = config
if exists:
(env.paths.sandbox_outputs_dir("thread-1", user_id="user-1") / "report.md").write_text("Actual report", encoding="utf-8")
batch = await _submit(env, ["file:../outputs/report.md exists"])
await _execute(env)
item = (await env.repo.list_items(batch["id"], user_id="user-1"))[0]
assert item["status"] == "succeeded"
# The admission decision is constructed on the owning loop. (The local
# provider's skills projection may also touch the provider; that existing
# path swallows its own failures and is not the acceptance gate.)
assert asyncio.get_running_loop() in constructed_on
if allow:
leaf = item["acceptance_verdict"]["leaves"][0]
assert (leaf["checked"], leaf["holds"]) == (True, exists)
if not exists:
assert leaf["detail"] == "file does not exist"
else:
assert item["acceptance_verdict"] is None
reset_app_config()

View File

@ -3710,10 +3710,10 @@ def test_task_tool_completed_without_criteria_stamps_no_acceptance_verdict(monke
def test_task_tool_acceptance_check_failure_is_isolated(monkeypatch):
def exploding_check(*_args, **_kwargs):
async def exploding_check(*_args, **_kwargs):
raise RuntimeError("checker blew up")
monkeypatch.setattr(task_tool_module, "check_acceptance_criteria", exploding_check)
monkeypatch.setattr(task_tool_module, "check_acceptance_criteria_async", exploding_check)
class DummyExecutor:
def __init__(self, **kwargs):

View File

@ -264,7 +264,7 @@ summaries establish a hold only when at least one test ran without a reported
failure. Zero-test or all-skipped modules do not supply positive evidence;
failures in any module take precedence over passing counts.
For file acceptance criteria, an empty regular file in the shared workspace can satisfy `file:<path> exists` and `file_written:<path>`, including on remote sandboxes. It fails `file:<path> non-empty` with a deterministic empty-file result.
For file acceptance criteria, an empty regular file in the shared workspace can satisfy `file:<path> exists` and `file_written:<path>`, including on remote sandboxes. It fails `file:<path> non-empty` with a deterministic empty-file result. On the local sandbox, every file criterion that reaches path resolution authorizes `sandbox:execute` before resolving the path or probing metadata; a revoked permission returns `UNVERIFIED` without revealing whether the file exists or how large it is. The `task` and `batch_task` entry points make this admission decision on the event loop that owns the run, so authorization providers that must be constructed on a running loop keep working; the offloaded checklist carries the decision instead of reconstructing the provider in its worker.
To require CSV header columns, set a `task` or `batch_task` item's criterion to
`file:../outputs/report.csv csv-columns:["id","name"]`. The JSON array must contain
@ -296,12 +296,12 @@ Reads are capped at 50,001 bytes to detect oversize content. Remote results are
for a completion marker, the read exit code, and the probed size. Remote providers lacking
the required probe tools leave the result unverified rather than falling back to full-content
reads. Concurrent writes of the same size do not yield an atomic snapshot.
Local checks authorize sandbox access before resolving paths or probing metadata, and recheck
before reading content; revoked permissions return `UNVERIFIED` without revealing existence.
Local checks recheck sandbox authorization before reading content; revoked permissions return
`UNVERIFIED` without revealing existence.
Remote probes report missing files only with a searchable ancestor and in-scope canonical path;
inaccessible directories remain `UNVERIFIED`. UTF-8 BOMs are rejected. Top-level scalars,
duplicate keys, and syntactically valid large numbers can pass, without validating schemas,
fields, or business semantics. Other file criteria are unchanged, and `.json` files are not
fields, or business semantics. Other file criteria keep their syntax and scope, and `.json` files are not
checked automatically. This criterion standardizes verdicts, path boundaries, and read limits
instead of requiring ad hoc bash/Python checks, and makes insufficient evidence explicit.
Execution completion status and automatic retry policy are unchanged.