---
title: "File System and Disk I/O Tools: Safe Workspace Isolation for Agents"
date: "2026-11-28T10:45:00+07:00"
description: "Build ADK file tools that stay inside a per-session workspace: path confinement, traversal defense, artifact-backed storage, quotas, and an auditable cleanup policy."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/file-system-tools-workspace-isolation.jpg"
alt: "Documents routed into separate locked filing cabinets"
tags: ['google-adk', 'adk-tools', 'file-io', 'workspace-isolation', 'security']
---

A `read_file(path: str)` tool is an open invitation: `../../../etc/passwd`, an absolute path to your `.env`, or a symlink that quietly points outside the directory you inspected. The model will happily pass through whatever string it was nudged toward by a document it just read — indirect prompt injection turns any path-taking tool into a directory-browsing exploit. The fix is architectural: give every session a workspace it cannot leave, make paths *relative names inside that workspace*, and keep durable files in a service that already namespaces by user.

This tutorial covers workspace layout and path confinement, traversal and symlink defenses with runnable code, separating read from write capability, moving large files to artifacts, and the quota/audit rules that keep a file tool survivable in production.

## Workspace layout: derive it, never accept it

The workspace root must be computed from trusted identifiers — app, user, and session — and never from a model argument. Two sessions under the same user get separate directories; a guest cannot name another tenant's folder because the tenant is not a parameter at all:

```python
from pathlib import Path

BASE = Path('/var/agent-workspaces')          # on a dedicated volume, not your app root

def sanitize(value: str) -> str:
    return ''.join(c if c.isalnum() or c in '-_' else '_' for c in value)

def workspace_for(session) -> Path:
    token = '_'.join(sanitize(v) for v in (session.app_name, session.user_id, session.id))
    root = (BASE / token).resolve()
    root.mkdir(parents=True, exist_ok=True)
    return root
```

Note the sanitization of identifiers before they touch the filesystem — `session_id` values come from outside, and `user_id = '../../etc'` is a classic trick. Resolve the root once, then treat it as immutable for the whole call.

## Confine every path you resolve

The rule: join the model's relative name to the workspace, resolve the result **including symlinks**, and verify it still sits under the root. `Path.resolve()` on Python 3.9+ does not raise for non-existent paths, so you can validate before opening:

```python
def safe_path(workspace: Path, name: str) -> Path:
    if not name or name.startswith(('/', '\\')) or '..' in Path(name).parts:
        raise ValueError('Only plain relative names inside the workspace are allowed.')
    target = (workspace / name).resolve()
    if target != workspace and workspace not in target.parents:
        raise ValueError(f'Path escapes the workspace: {name}')
    return target
```

This single helper defends against `../` traversal, absolute paths, and symlinks that resolve elsewhere — but only if **every** tool calls it, including the ones you write quickly for debugging. Two more assumptions worth breaking: on Windows, reserved names and drive letters (`C:`) need their own rejection, and a hard link created inside the workspace still points at an inode outside it, so untrusted code that can create links belongs in a [sandbox](/blog/sandboxed-python-execution-e2b-docker), not in a bare directory.

## Separate the capabilities

Do not ship one god-tool with `mode=read|write|delete`. Split them, so you can grant read-only agents access without the write path existing in their schema at all, and so a prompt injection that reaches `write_file` still cannot call `delete`:

```python
def list_files(ctx: ToolContext) -> dict:
    """List files in the current session workspace. Takes no arguments."""
    ws = workspace_for(ctx.session)
    names = sorted(p.name for p in ws.iterdir() if p.is_file())
    return {'status': 'success', 'files': names, 'summary': f'Workspace holds {len(names)} files.'}

def write_file(name: str, content: str, ctx: ToolContext) -> dict:
    """Create or overwrite a text file in the session workspace.

    Args:
        name (str): Relative filename, e.g. 'report.md'. No directories or '..'.
        content (str): Full text content of the file.
    """
    ws = workspace_for(ctx.session)
    try:
        target = safe_path(ws, name)
    except ValueError as e:
        return {'status': 'error', 'error_message': str(e), 'retryable': False}
    if len(content.encode()) > MAX_BYTES:
        return {'status': 'error', 'error_message': f'File exceeds the {MAX_BYTES}-byte limit.'}
    target.write_text(content, encoding='utf-8')
    return {'status': 'success', 'name': target.name, 'bytes': target.stat().st_size}
```

Also worth knowing: tools are the wrong place for large binary payloads. If the artifact service is configured on the `Runner`, use `await ctx.save_artifact(filename, part)` and `await ctx.load_artifact(filename)` — they give you automatic **versioning**, a `user:` filename prefix for cross-session user files, and storage that is already namespaced by app, user, and session. Calling them without an artifact service raises, so wire the service at startup, not at first use.

## Storage choices, and what goes where

| Store | Scope | Persistence | Good for |
|---|---|---|---|
| session `state` | session / `user:` / `app:` | depends on session service | small serializable values, flags, IDs |
| artifacts (`save_artifact`) | session, or `user:` prefix | per artifact service (memory/GCS) | versioned binary, generated reports |
| session workspace (this post) | one directory per session | wipe policy you define | scratch files the agent edits and re-reads |
| external bucket / DB | your schema | durable | anything a second system must see |

Mixing these is the common failure: byte blobs stuffed in `state` bloat every future turn, while scratch files persisted forever leak one session's data into the next — which is exactly the cross-user exfiltration the ADK safety guidance tells sandboxed execution to avoid.

## Quotas, lifecycle, and audit

Three operational rules make file tools survivable:

- **Bound before writing.** Cap file count, total bytes per workspace, and single-file size; return a precise error (the model can delete or summarize instead) rather than letting `ENOSPC` surface as a stack trace.
- **Wipe deliberately.** Ephemeral workspaces are created at invocation start and deleted on session end; use the `temp:` state only as a *pointer* to cleanup tasks, since temp keys vanish with the invocation while directories do not.
- **Log every operation.** Append `{session, user, op, path, bytes}` to your audit log — path operations are the events a compliance review will ask for, and they are also your earliest signal of an injection probing the filesystem ([audit trails](/blog/audit-trails-regulated-industries)).

## Takeaways

- Derive the workspace root from trusted app/user/session identifiers; never accept a root or an absolute path from the model.
- Conjoin, `resolve()`, and check containment on **every** path — that one check defeats `../`, absolute paths, and escaping symlinks.
- Ship separate read/write/delete tools so capability can be scoped, and keep the argument a bare relative name.
- Use artifacts (versioned, `user:`-namespaced) for durable and binary data; keep `state` for small values; wipe scratch dirs on a schedule.
- Enforce quotas before writing, delete on session end, and audit every path operation.

## Further reading

- [Sandboxed Python execution with E2B or Docker](/blog/sandboxed-python-execution-e2b-docker)
- [Injecting session and context into tools](/blog/inject-session-context-into-adk-tools)
- [Tool authorization and permission gates](/blog/tool-authorization-permission-gates-adk)
- [Handling tool errors and recoverable exceptions](/blog/adk-tool-errors-recoverable-exceptions)
- [ADK docs — Artifacts](https://adk.dev/artifacts/)
