userName20260323 236f66af24 fix(rpc): anchor the file viewer's state-dir fence on agent home, not the session workdir
## Summary

The web file viewer refused every file a sub-agent's DAG node writes, and said the
wrong thing about why. Clicking such a report answered `403`, which the page renders
as "Raven is confined to the working directory" -- while `restrict_to_workspace` was
off and the real refusal came from the state-directory fence.

`/file` resolves a request against the session's working directory when the page names
a session. It also handed that directory to `in_state_dir` in the role that function
reserves for agent home. The fence derives its two exemptions from that argument -- the
workspace itself, and the per-channel working-directory root beside it -- so with the
session's directory in home's place the exemptions covered `~/.raven/tmp/<channel>` and
a sibling that does not exist. Everything the DAG runner writes under
`~/.raven/workspace/sessions/` then read as raven's own state and was refused, which is
the same defect the workspace exemption exists to prevent, one directory over. A
node's report was drawn on the shelf as a delivery and would not open.

`resolve_readable` now keeps the two roles apart. The caller's workspace still anchors
relative paths and the `restrict_to_workspace` fence; the state-directory fence is
anchored on `cfg.workspace_path`, and the session's directory is passed alongside it
through a new variadic parameter that adds to what the fence exempts rather than
replacing what it derives. A session pinned to a directory under the state root
therefore keeps its files, and every exemption -- derived or added -- is held to the
same direction check, so the state root itself and its ancestors still earn none.
`serve.json` and `config.json` stay refused on every path tested.

`_resolve_inside`, which backs `fs.list` and `fs.read`, carried the same substitution.
Its containment check hid the symptom, so nothing had surfaced there yet; it is
anchored the same way now, because the fence's contract is that the viewer, the `fs.*`
panel and `fs.reveal` answer alike for a given file.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Commands and results, all at the branch head after rebasing onto `main`:

```console
$ uv run pytest tests/test_rpc_transport.py tests/test_rpc_console.py tests/test_rpc_knowledge.py -q
147 passed in 2.84s

$ uv run pytest tests/test_rpc_files.py tests/test_utils_office.py -q
33 passed in 2.70s

$ make lint-python          # ruff check + ruff format --check
exit 0

$ make lint-imports
Contracts: 9 kept, 0 broken.

$ make lint-ui
exit 0

$ make check-source-language
exit 0

$ uv run python scripts/check_commit_messages.py origin/main..HEAD
exit 0
```

Two regression tests were added next to the existing state-directory fence cases:

- the session-workdir call reads a node's report under the sessions tree and still
  refuses `serve.json`;
- a session pinned to a directory under the state root keeps serving its own files,
  while one pinned at the state root itself does not.

The first was proved load-bearing by reverting the fix and re-running it, which failed
with `PermissionError: ... is inside raven's state directory` on the report path. The
second is unchanged by the fix and is there to pin the behaviour the change must not
lose.

Behaviour was also checked against the running gateway's own files, on the real paths:
with the session's working directory supplied, a node's report resolves and both
`serve.json` and `config.json` raise `PermissionError`.

Known gaps, disclosed rather than worked around:

- `make lint-tui` and `make lint-bridge` do not pass in this environment. The first
  reports `src/i18n/messages.generated.ts` stale, the second `tsc: not found`. Both fail
  identically on a clean `main` worktree, and this change touches neither `ui-tui/` nor
  `bridge/`.
- No browser check. The refusal and the fix were exercised through the resolver and the
  gateway's own file paths, not through a rebuilt page bundle.

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

The fence's decisions are unchanged except for the one it was getting wrong. Nothing
that was refused before this change becomes readable, apart from the session-directory
subtree the fence was never meant to refuse: the added exemption is bounded by the same
direction check as the derived ones, so no ancestor of raven's state root and not the
root itself can ride it. The credential files were re-checked as refused on every path
the tests and the live probe cover.

`in_state_dir` gains a variadic parameter with no required argument, so existing calls
keep compiling and keep their previous meaning. Both in-tree callers were updated in
this change; there are no others.

Rollback is reverting the commit. The change is three files of resolver logic plus its
tests, with no migration, no stored state and no wire-format change.

## Related Issues

N/A
2026-09-11 03:26:57 +00:00

140 lines
4.9 KiB
Python

"""Factories for the tool face code-flow contributes (raven-plugin.toml names them).
Every factory reads the flow slice's ``tools`` section and declines (returns
None) when that section leaves the face off or the slice does not parse, so a
product that wants the host's own tools simply says so and gets them.
"""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from loguru import logger
from pydantic import ValidationError
from code_flow.config import FlowConfig, ToolsConfig
from code_flow.tools.exec import SPILL_SUBDIR, CodeExecTool, CodeExecutor
from code_flow.tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool
from code_flow.tools.read_state import owner_for
from code_flow.tools.search import GlobTool
from code_flow.tools.todo import STORES, TodoTool
if TYPE_CHECKING:
from raven.plugins.context import PluginContext
def _face(ctx: "PluginContext", seat: str) -> ToolsConfig | None:
"""The tool face's own section of the flow slice, or None to decline."""
try:
flow = FlowConfig.from_slice(dict(ctx.config or {}))
except ValidationError as exc:
logger.warning("code-flow: config slice is malformed; declining {}: {}", seat, exc)
return None
if not flow.tools.enabled:
return None
return flow.tools
def _fence(ctx: "PluginContext", cfg: ToolsConfig) -> tuple[Path, ...]:
"""The roots these tools may reach, mirroring what the host grants its own.
The host computes ``allowed_dirs = (workspace,) if restrict_to_workspace``
(raven/agent/loop/wiring.py) and an empty tuple means the fence is OFF --
which is what these replacements used to pass, whatever the product asked
for. The section carries the answer because a plugin factory cannot read
the host field; the launcher renders it in.
"""
return (Path(ctx.services.workspace),) if cfg.restrict_to_workspace else ()
def make_read_file(ctx: "PluginContext") -> ReadFileTool | None:
cfg = _face(ctx, "read_file")
if not cfg:
return None
return ReadFileTool(workspace=ctx.services.workspace, allowed_dirs=_fence(ctx, cfg), read_owner=owner_for(ctx))
def make_write_file(ctx: "PluginContext") -> WriteFileTool | None:
cfg = _face(ctx, "write_file")
if not cfg:
return None
return WriteFileTool(
workspace=ctx.services.workspace,
allowed_dirs=_fence(ctx, cfg),
syntax_note=cfg.python_syntax_note,
read_owner=owner_for(ctx),
)
def make_edit_file(ctx: "PluginContext") -> EditFileTool | None:
cfg = _face(ctx, "edit_file")
if not cfg:
return None
return EditFileTool(
workspace=ctx.services.workspace,
allowed_dirs=_fence(ctx, cfg),
syntax_note=cfg.python_syntax_note,
read_owner=owner_for(ctx),
require_read=cfg.require_read_before_edit,
)
def make_list_dir(ctx: "PluginContext") -> ListDirTool | None:
cfg = _face(ctx, "list_dir")
if not cfg:
return None
return ListDirTool(workspace=ctx.services.workspace, allowed_dirs=_fence(ctx, cfg))
def make_glob(ctx: "PluginContext") -> GlobTool | None:
cfg = _face(ctx, "glob")
if not cfg:
return None
return GlobTool(workspace=ctx.services.workspace, allowed_dirs=_fence(ctx, cfg))
def make_exec(ctx: "PluginContext") -> CodeExecTool | None:
"""The shell, with the clamped ceiling, partial output on timeout and the
30,000-character budget with spill. Served only where the host's own exec
would run on the host too (``tools.sandbox.backend == "none"``): the
replacement runs on the host, and a configured sandbox must not be
bypassed by a same-name tool -- so under any other backend this declines
and the host's exec keeps the shell."""
cfg = _face(ctx, "exec")
if not cfg:
return None
if cfg.exec.sandbox_backend != "none":
logger.info(
"code-flow: tools.sandbox.backend is {!r}; the host's exec keeps the shell", cfg.exec.sandbox_backend
)
return None
home = Path(ctx.services.workspace)
executor = CodeExecutor(max_timeout=cfg.exec.max_timeout, spill_dir=home / SPILL_SUBDIR)
return CodeExecTool(
timeout=cfg.exec.timeout,
working_dir=str(home),
restrict_to_workspace=cfg.restrict_to_workspace,
path_append=cfg.exec.path_append,
executor=executor,
extra_allowed_dirs=(home,),
max_timeout=cfg.exec.max_timeout,
)
def make_todo(ctx: "PluginContext") -> TodoTool | None:
"""The checklist, on the store the flow hook binds per session: one store
per Agent home, so the hook factory and this one meet on the same object."""
return TodoTool(STORES.for_home(ctx.services.workspace)) if _face(ctx, "todo") else None
__all__ = [
"make_edit_file",
"make_exec",
"make_glob",
"make_list_dir",
"make_read_file",
"make_todo",
"make_write_file",
]