Path safety and sandboxing
Now that the agent can read and write files, what stops it from reading /etc/passwd or writing to /usr/bin? Nothing, unless we add a boundary. The safe_path() function resolves any path and checks it stays within the workspace directory. Path traversal attacks like ../../etc/passwd get caught.
WORKDIR = Path.cwd()
def safe_path(p: str) -> Path:
"""Resolve path and verify it stays within workspace."""
path = (WORKDIR / p).resolve()
if not path.is_relative_to(WORKDIR):
raise ValueError(f"Path escapes workspace: {p}")
return pathEvery file tool calls safe_path() before touching the filesystem. Three lines that prevent workspace escape.
Quiz: Quiz
Loading practice…