|
| 1 | +"""A workspace whose file operations stay inside its working directory.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Sequence |
| 6 | + |
| 7 | +from pydantic_ai.workspaces import FileEntry, Workspace, WorkspaceError, WrapperWorkspace |
| 8 | + |
| 9 | + |
| 10 | +class WorkspacePathError(WorkspaceError, PermissionError): |
| 11 | + """A file operation named a path outside a confined workspace.""" |
| 12 | + |
| 13 | + |
| 14 | +class ConfinedWorkspace(WrapperWorkspace): |
| 15 | + """Keep file operations inside the wrapped workspace's working directory. |
| 16 | +
|
| 17 | + A path is checked where it really leads - resolved against the working |
| 18 | + directory, then through every symlink - so neither `..` nor a link reaches |
| 19 | + past the root. The console's `glob` and `grep` check their search root the |
| 20 | + same way. |
| 21 | +
|
| 22 | + **Commands are not confined.** A shell reaches any file its user can, and a |
| 23 | + string check of a command line is not a boundary; isolate commands with a |
| 24 | + sandboxed workspace such as `DockerWorkspace`. This keeps the file tools - |
| 25 | + which typically run without approval - where `LocalWorkspace` points them, |
| 26 | + as `LocalBackend(root_dir=...)` did before 0.2.30. |
| 27 | +
|
| 28 | + Example: |
| 29 | + ```python |
| 30 | + from pydantic_ai.workspaces import LocalWorkspaceBackend, Workspace |
| 31 | +
|
| 32 | + from pydantic_ai_backends.workspaces import ConfinedWorkspace |
| 33 | +
|
| 34 | + project = ConfinedWorkspace(Workspace(LocalWorkspaceBackend("./project"))) |
| 35 | + result = await agent.run(prompt, workspace=project) |
| 36 | + ``` |
| 37 | + """ |
| 38 | + |
| 39 | + def __init__(self, wrapped: Workspace) -> None: |
| 40 | + super().__init__(wrapped) |
| 41 | + self._root: str | None = None |
| 42 | + |
| 43 | + async def _confined_root(self) -> str: |
| 44 | + if self._root is None: |
| 45 | + self._root = await self.realpath(await self.working_dir()) |
| 46 | + return self._root |
| 47 | + |
| 48 | + async def contains(self, path: str) -> bool: |
| 49 | + """Whether `path`, relative to the working directory or absolute, leads inside it.""" |
| 50 | + root = await self._confined_root() |
| 51 | + target = await self.realpath(await self.resolve(path)) |
| 52 | + return target == root or target.startswith(root.rstrip("/") + "/") |
| 53 | + |
| 54 | + async def check(self, path: str) -> None: |
| 55 | + """Refuse `path` when it leads outside the working directory. |
| 56 | +
|
| 57 | + Raises: |
| 58 | + WorkspacePathError: It does. |
| 59 | + """ |
| 60 | + if not await self.contains(path): |
| 61 | + raise WorkspacePathError( |
| 62 | + f"{path!r} is outside the workspace ({await self._confined_root()})" |
| 63 | + ) |
| 64 | + |
| 65 | + async def read_bytes(self, path: str) -> bytes: |
| 66 | + await self.check(path) |
| 67 | + return await super().read_bytes(path) |
| 68 | + |
| 69 | + async def write_bytes(self, path: str, data: bytes) -> None: |
| 70 | + await self.check(path) |
| 71 | + await super().write_bytes(path, data) |
| 72 | + |
| 73 | + async def stat(self, path: str) -> FileEntry: |
| 74 | + await self.check(path) |
| 75 | + return await super().stat(path) |
| 76 | + |
| 77 | + async def list_dir(self, path: str) -> Sequence[FileEntry]: |
| 78 | + await self.check(path) |
| 79 | + return await super().list_dir(path) |
| 80 | + |
| 81 | + async def make_dir(self, path: str) -> None: |
| 82 | + await self.check(path) |
| 83 | + await super().make_dir(path) |
| 84 | + |
| 85 | + async def remove(self, path: str) -> None: |
| 86 | + await self.check(path) |
| 87 | + await super().remove(path) |
| 88 | + |
| 89 | + async def exists(self, path: str) -> bool: |
| 90 | + await self.check(path) |
| 91 | + return await super().exists(path) |
| 92 | + |
| 93 | + |
| 94 | +def confinement(workspace: Workspace) -> ConfinedWorkspace | None: |
| 95 | + """The `ConfinedWorkspace` among `workspace`'s layers, if there is one.""" |
| 96 | + layer: object = workspace |
| 97 | + while isinstance(layer, Workspace): |
| 98 | + if isinstance(layer, ConfinedWorkspace): |
| 99 | + return layer |
| 100 | + layer = layer._backend # pyright: ignore[reportPrivateUsage] |
| 101 | + return None |
0 commit comments