Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

VFS and File Persistence

Eryx provides a Virtual Filesystem (VFS) that allows sandboxed Python code to read and write files without accessing the host filesystem. This is essential for applications that need file I/O while maintaining security isolation.

Overview

The VFS provides:

  • Isolated file storage - Files exist only within the VFS, not on the host
  • Persistence across executions - Files survive multiple execute() calls in a session
  • Shared storage - Multiple sessions can share the same VFS storage
  • Full filesystem API - Standard Python file operations work (open, read, write, mkdir, etc.)
  • SQLite support - SQLite databases can be stored in the VFS
  • Bounded size - Total size is capped (64 MB by default, counting file contents plus a small charge per file and directory) so scripts cannot exhaust host memory; see Virtual Filesystem Size

Creating a Session with VFS

To use the VFS, create a VfsStorage and attach it to a session:

import eryx

# Create VFS storage
storage = eryx.VfsStorage()

# Create a session with VFS enabled
session = eryx.Session(vfs=storage)

# Now you can read/write files in the sandbox
session.execute("""
with open('/data/hello.txt', 'w') as f:
    f.write('Hello, VFS!')
""")

result = session.execute("""
with open('/data/hello.txt', 'r') as f:
    print(f.read())
""")
print(result.stdout_text)  # "Hello, VFS!"

Default Mount Path

By default, the VFS is mounted at /data. You can customize this:

import eryx

storage = eryx.VfsStorage()

# Use default mount path (/data)
session1 = eryx.Session(vfs=storage)
print(session1.vfs_mount_path)  # "/data"

# Use custom mount path
session2 = eryx.Session(vfs=storage, vfs_mount_path="/myfiles")
print(session2.vfs_mount_path)  # "/myfiles"

session2.execute("open('/myfiles/test.txt', 'w').write('custom path')")

The same storage is also mounted at /tmp, so tempfile and code that writes to /tmp work. Files there are kept apart from the mount path’s, under their own /tmp/... paths, but count towards the same size limit. A volume mounted at /tmp replaces it.

File Operations

The VFS supports standard Python file operations:

Reading and Writing Files

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

# Write a file
session.execute("""
with open('/data/example.txt', 'w') as f:
    f.write('Line 1\\n')
    f.write('Line 2\\n')
""")

# Read the file
result = session.execute("""
with open('/data/example.txt', 'r') as f:
    content = f.read()
    print(content)
""")
print(result.stdout_text)
# Line 1
# Line 2

Appending to Files

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("open('/data/log.txt', 'w').write('Entry 1\\n')")
session.execute("open('/data/log.txt', 'a').write('Entry 2\\n')")
session.execute("open('/data/log.txt', 'a').write('Entry 3\\n')")

result = session.execute("print(open('/data/log.txt').read())")
print(result.stdout_text)
# Entry 1
# Entry 2
# Entry 3

Binary Files

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
# Write binary data
data = bytes([0, 1, 2, 255, 254, 253])
with open('/data/binary.bin', 'wb') as f:
    f.write(data)
""")

result = session.execute("""
with open('/data/binary.bin', 'rb') as f:
    data = f.read()
print(list(data))
""")
print(result.stdout_text)  # "[0, 1, 2, 255, 254, 253]"

Using pathlib

The VFS works with Python’s pathlib:

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
from pathlib import Path

# Write using pathlib
p = Path('/data/pathlib_test.txt')
p.write_text('Written with pathlib')
""")

result = session.execute("""
from pathlib import Path
print(Path('/data/pathlib_test.txt').read_text())
""")
print(result.stdout_text)  # "Written with pathlib"

Directory Operations

Creating Directories

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
import os
os.makedirs('/data/nested/deep/directory', exist_ok=True)

with open('/data/nested/deep/directory/file.txt', 'w') as f:
    f.write('Deep file')
""")

result = session.execute("print(open('/data/nested/deep/directory/file.txt').read())")
print(result.stdout_text)  # "Deep file"

Listing Directories

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
import os
open('/data/a.txt', 'w').write('a')
open('/data/b.txt', 'w').write('b')
open('/data/c.txt', 'w').write('c')
""")

result = session.execute("""
import os
files = sorted(os.listdir('/data'))
print(files)
""")
print(result.stdout_text)  # "['a.txt', 'b.txt', 'c.txt']"

Deleting Files and Directories

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

session.execute("""
import os

# Create file
open('/data/temp.txt', 'w').write('temporary')

# Delete file
os.remove('/data/temp.txt')

# Check if deleted
print(f"exists: {os.path.exists('/data/temp.txt')}")
""")

Sharing Storage Between Sessions

Multiple sessions can share the same VFS storage:

import eryx

# Create shared storage
storage = eryx.VfsStorage()

# Session 1 writes a file
session1 = eryx.Session(vfs=storage)
session1.execute("open('/data/shared.txt', 'w').write('from session 1')")

# Session 2 can read the same file
session2 = eryx.Session(vfs=storage)
result = session2.execute("print(open('/data/shared.txt').read())")
print(result.stdout_text)  # "from session 1"

Isolated Storage

Each VfsStorage instance is independent:

import eryx

# Two separate storage instances
storage1 = eryx.VfsStorage()
storage2 = eryx.VfsStorage()

session1 = eryx.Session(vfs=storage1)
session1.execute("open('/data/isolated.txt', 'w').write('only in storage1')")

session2 = eryx.Session(vfs=storage2)
result = session2.execute("""
import os
print(f"exists: {os.path.exists('/data/isolated.txt')}")
""")
print(result.stdout_text)  # "exists: False"

VFS Persistence Across Reset

VFS data persists even when you reset the session’s Python state:

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

# Write a file
session.execute("open('/data/persist.txt', 'w').write('before reset')")

# Reset Python state (clears variables, etc.)
session.reset()

# VFS data is still there
result = session.execute("print(open('/data/persist.txt').read())")
print(result.stdout_text)  # "before reset"

Bringing Your Own Storage (Rust)

With the unstable-vfs feature, a Rust caller can give a sandbox the storage for its next executions, for example to restore files saved from an earlier run and save them again afterwards. execute() and any InProcessSession created from the sandbox use it instead of a fresh, empty one:

use std::sync::Arc;
use eryx::Sandbox;
use eryx::vfs::{InMemoryStorage, VfsStorage};

let storage = Arc::new(InMemoryStorage::new());
storage.mkdir("/data").await?;
storage.write("/data/input.txt", b"saved earlier").await?;

let mut sandbox = Sandbox::embedded().build()?;
sandbox.set_vfs_storage(storage.clone());
sandbox.execute("open('/data/output.txt', 'w').write('new')").await?;

let saved = storage.snapshot().await; // e.g. to persist it

The storage keeps its own size and entry limits (InMemoryStorage::with_max_bytes and with_max_entries); max_vfs_bytes and max_vfs_entries only apply to storage eryx creates. On a pooled sandbox, use PooledSandbox::with_vfs_storage, which the pool clears when the sandbox goes back.

SQLite Databases in VFS

The VFS supports SQLite databases, allowing persistent structured data:

In-Memory Databases

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

result = session.execute("""
import sqlite3

conn = sqlite3.connect(':memory:')
cursor = conn.cursor()

cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
cursor.execute("INSERT INTO users (name) VALUES ('Bob')")

cursor.execute('SELECT name FROM users ORDER BY id')
names = [row[0] for row in cursor.fetchall()]
conn.close()

print(names)
""")
print(result.stdout_text)  # "['Alice', 'Bob']"

File-Based Databases

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

# Create database and insert data
session.execute("""
import sqlite3
conn = sqlite3.connect('/data/app.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price REAL)')
cursor.execute("INSERT INTO products (name, price) VALUES ('Widget', 9.99)")
cursor.execute("INSERT INTO products (name, price) VALUES ('Gadget', 19.99)")
conn.commit()
conn.close()
""")

# Query in a separate execution
result = session.execute("""
import sqlite3
conn = sqlite3.connect('/data/app.db')
cursor = conn.cursor()
cursor.execute('SELECT name, price FROM products')
for name, price in cursor.fetchall():
    print(f"{name}: ${price}")
conn.close()
""")
print(result.stdout_text)
# Widget: $9.99
# Gadget: $19.99

Database Persistence Across Sessions

import eryx

storage = eryx.VfsStorage()

# Session 1: Create database
session1 = eryx.Session(vfs=storage)
session1.execute("""
import sqlite3
conn = sqlite3.connect('/data/shared.db')
cursor = conn.cursor()
cursor.execute('CREATE TABLE messages (id INTEGER PRIMARY KEY, text TEXT)')
cursor.execute("INSERT INTO messages (text) VALUES ('Hello from session 1')")
conn.commit()
conn.close()
""")

# Session 2: Read from same database
session2 = eryx.Session(vfs=storage)
result = session2.execute("""
import sqlite3
conn = sqlite3.connect('/data/shared.db')
cursor = conn.cursor()
cursor.execute('SELECT text FROM messages')
print(cursor.fetchone()[0])
conn.close()
""")
print(result.stdout_text)  # "Hello from session 1"

Host Filesystem Isolation

The VFS is completely isolated from the host filesystem:

import eryx

storage = eryx.VfsStorage()
session = eryx.Session(vfs=storage)

result = session.execute("""
import os

# Try to access real /etc (should fail or be virtual)
try:
    files = os.listdir('/etc')
    has_passwd = 'passwd' in files
    print(f"has_real_passwd: {has_passwd}")
except Exception as e:
    print(f"access_denied: {type(e).__name__}")
""")
# Should show "has_real_passwd: False" or "access_denied: ..."

Host Volume Mounts

In addition to the in-memory VFS, Eryx supports mounting host filesystem directories into the sandbox. This allows sandboxed code to read and write real files on the host, with optional read-only enforcement.

Python API

Pass a list of (host_path, guest_path, read_only) tuples:

import eryx

# Read-write mount
sandbox = eryx.Sandbox(
    volumes=[("/home/user/data", "/mnt/data", False)],
)

# Read-only mount
sandbox = eryx.Sandbox(
    volumes=[("/home/user/data", "/mnt/data", True)],
)

# Multiple mounts
sandbox = eryx.Sandbox(
    volumes=[
        ("/home/user/input", "/input", True),
        ("/home/user/output", "/output", False),
    ],
)

Volume mounts also work with sessions:

session = eryx.Session(
    volumes=[("/home/user/data", "/mnt/data", False)],
)

Rust API

Use VolumeMount::new() for read-write or VolumeMount::read_only() for read-only:

use eryx::{Sandbox, VolumeMount};

let sandbox = Sandbox::embedded()
    .with_volume(VolumeMount::new("/home/user/data", "/mnt/data"))
    .with_volume(VolumeMount::read_only("/home/user/config", "/config"))
    .build()?;

CLI

Use Docker-style -v syntax:

# Read-write
python -m eryx -v /host/path:/sandbox/path script.py

# Read-only (append :ro)
python -m eryx -v /host/path:/sandbox/path:ro script.py

# Multiple mounts
python -m eryx -v ./input:/input:ro -v ./output:/output script.py

How It Works

Volume mounts use capability-based security (cap-std) to provide controlled access to host directories. The sandbox can only access the specific directories that were explicitly mounted — it cannot traverse outside the mount point or access other host paths.

Read-only mounts enforce that sandboxed code cannot modify any files in the mounted directory.

A few more rules apply to volumes:

  • Single files - Mounting a host file (rather than a directory) exposes just that file. The script can read, write, replace or delete it, as the mount allows, but can’t list, open or create anything else next to it on the host.
  • No symlinks - Scripts can’t create symbolic links in a volume, just as in the VFS.
  • Open files - A sandbox holds at most 256 host files and directories open at once (across the stdlib, packages and volumes); opening more fails with EDQUOT until some are closed. Set max_open_host_files in resource limits to change it. All sandboxes in the process also share one total, by default half the soft RLIMIT_NOFILE (at least 256).
  • Size - Volumes are the place for large trees: max_vfs_bytes and max_vfs_entries (see resource limits) only apply to in-memory storage, and a volume keeps its contents on the host disk rather than in host memory.
  • File size - max_vfs_bytes doesn’t apply to volumes, so by default a writable volume can fill the host disk. Give the mount a max_file_size to cap how large any one file in it may grow; writes past it fail. The cap is per file, not a total for the volume.
import eryx

# (host_path, guest_path, read_only, max_file_size)
sandbox = eryx.Sandbox(volumes=[("/home/user/out", "/mnt/out", False, 16 * 1024 * 1024)])

The eryx CLI takes --volume-max-file-size BYTES, applied to every --volume.

Storage Volumes

A volume can also be served from any VfsStorage instead of the host filesystem: an InMemoryStorage you fill and read back, or your own implementation (one backed by object storage, a database, or a remote client). Files are at their full guest paths in the storage, so the volume at /mnt/repo reads /mnt/repo/src/main.py from it.

use std::sync::Arc;
use eryx::VolumeMount;
use eryx::vfs::InMemoryStorage;

let repo = Arc::new(InMemoryStorage::new());
let sandbox = Sandbox::embedded()
    .with_volume(VolumeMount::read_only_storage("/mnt/repo", repo.clone()))
    .build()?;

The storage’s own limits apply, not max_vfs_bytes or max_file_size, and files written to it aren’t scrubbed of secrets, as with storage given to set_vfs_storage. A writable volume’s directory is created in the storage if it’s missing; a read-only volume’s storage is never changed, so it should already contain the directory. Renaming a file between a storage volume and another mount fails with EXDEV, as a rename between filesystems does (Python’s shutil.move copies instead).

Volumes can also be added for a single request, alongside the built ones: with Sandbox::add_volume, or PooledSandbox::with_volume on a pooled sandbox, which removes them when the sandbox goes back to the pool. An InProcessSession created from the sandbox mounts them too. Two mounts at the same guest path (including /data) fail the execution.

Best Practices

  1. Use shared storage for multi-session workflows - When sessions need to share data
  2. Use separate storage for isolation - When sessions should be independent
  3. Prefer file-based SQLite over in-memory - For data that needs to persist
  4. Use appropriate mount paths - Customize for your application’s needs
  5. Handle file errors gracefully - Files may not exist or paths may be invalid
  6. Use read-only mounts for input data - Prevent sandboxed code from modifying source files
  7. Prefer VFS for ephemeral data - Use volume mounts when you need access to real host files, or for large trees (see resource limits)

Next Steps