aperion-fsal 1.2.2
The Iron Vault - Secure Filesystem Agent Layer for Aperion
Requires Python: >=3.11
Keywords: atomic, fastapi, filesystem, sandbox, security

# The Iron Vault - Aperion FSAL

> **The absolute boundary between AI agents and the underlying operating system.**

[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.109+-green.svg)](https://fastapi.tiangolo.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Overview

The Iron Vault is a hardened filesystem access layer that enforces **Constitution B3 (Sandbox Boundaries)** and guarantees file integrity via atomic operations. It serves as the exclusive I/O gateway for AI agents in the Aperion system.

### Key Security Guarantees

- 🔒 **Sandbox Isolation**: All paths are rigidly constrained to `FSAL_ROOT`
- ⚛️ **Atomic Writes**: Write-temp-then-rename pattern with `fsync` prevents corruption
- 🚫 **Traversal Prevention**: `../`, null bytes, symlinks, and absolute paths are blocked
- 🔑 **Bearer Token Auth**: Production mode enforces authentication
- 📋 **Audit Ready**: Structured logging for all operations

## Quick Start

### Installation

```bash
pip install aperion-fsal

# From source
pip install -e .

# With dev dependencies
pip install -e ".[dev]"
```

### Running the Service

```bash
# Development mode (CWD fallback allowed)
APERION_ENV=dev aperion-fsal

# Production mode (FSAL_ROOT required)
FSAL_ROOT=/data/sandbox FSAL_TOKEN=secret aperion-fsal
```

### Docker

```bash
# Build
docker build -t aperion-fsal .

# Run
docker run -d -p 4848:4848 \
  -e FSAL_TOKEN=your-secret-token \
  -v /path/to/sandbox:/data \
  aperion-fsal
```

## API Reference

All endpoints require Bearer token authentication when `FSAL_TOKEN` is set.

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/healthz` | GET | Health check |
| `/metrics` | GET | Prometheus metrics |
| `/auth/status` | GET | Auth configuration (public) |
| `/v1/fs/list` | POST | List directory contents (supports recursive) |
| `/v1/fs/read` | POST | Read file content |
| `/v1/fs/write` | POST | Write file (base64 encoded) |
| `/v1/fs/move` | POST | Move/rename file or directory |
| `/v1/fs/copy` | POST | Copy file or directory |
| `/v1/fs/mkdir` | POST | Create directory |
| `/v1/fs/delete` | POST | Delete file or directory |
| `/v1/fs/hash` | POST | Calculate file hash |
| `/v1/fs/exists` | POST | Check if path exists |
| `/v1/fs/stat` | POST | Get detailed file/directory info |

### Example: Write a File

```bash
curl -X POST http://localhost:4848/v1/fs/write \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token" \
  -d '{
    "path": "hello.txt",
    "content_b64": "SGVsbG8sIFdvcmxkIQ==",
    "make_dirs": true
  }'
```

### Example: Read a File

```bash
curl -X POST http://localhost:4848/v1/fs/read \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token" \
  -d '{
    "path": "hello.txt",
    "as_text": true
  }'
```

## Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `FSAL_ROOT` | Yes (prod) | CWD (dev) | Sandbox root directory |
| `FSAL_TOKEN` | Recommended | None | Bearer token for authentication |
| `FSAL_HOST` | No | 127.0.0.1 | Host to bind to |
| `FSAL_PORT` | No | 4848 | Port to listen on |
| `APERION_ENV` | No | production | Set to `dev` for development mode |
| `FSAL_MAX_FILE_SIZE` | No | 104857600 | Max file size in bytes (100MB) |
| `FSAL_MIN_FREE_SPACE` | No | 104857600 | Min free disk space required (100MB) |
| `FSAL_REQUEST_TIMEOUT` | No | 30 | Request timeout in seconds |
| `FSAL_TRACING_ENABLED` | No | false | Enable OpenTelemetry tracing |

## Security Model

### Asymmetric Behavior (Constitution B)

- **Server**: Logs warning if `FSAL_TOKEN` not set, but allows startup in dev mode
- **Client/Scripts**: Must fail immediately if tokens are missing

### Sandbox Enforcement

1. All paths are normalized to relative paths
2. Absolute paths have their root stripped
3. `..` components are resolved BEFORE path construction
4. Symlinks are rejected by default
5. Null bytes in paths are always rejected
6. `FSAL_ROOT` MUST be set in production mode

### Atomic Write Guarantee

```
1. Write to temp file in SAME directory as target
2. fsync() to ensure data hits disk
3. Atomic rename() to move temp to target
4. Cleanup temp file in finally block
```

This guarantees that on power loss:
- Either the OLD content is preserved, OR
- The NEW content is fully written
- Never a partial/corrupt file

## Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=aperion_fsal --cov-report=html

# Run security tests only
pytest tests/security/

# Run unit tests only
pytest tests/unit/
```

## Development

```bash
# Install dev dependencies
pip install -e ".[dev]"

# Run linter
ruff check src/

# Run type checker
mypy src/

# Format code
ruff format src/
```

## Project Structure

```
aperion-fsal/
├── src/
│   └── aperion_fsal/
│       ├── __init__.py
│       ├── core/
│       │   ├── safeio.py      # The atomic I/O kernel
│       │   └── sandbox.py     # Path resolution & traversal prevention
│       ├── service/
│       │   ├── app.py         # FastAPI application
│       │   ├── models.py      # Pydantic schemas
│       │   └── auth.py        # Token validation logic
│       └── main.py            # Entry point
├── tests/
│   ├── conftest.py
│   ├── unit/
│   │   └── test_safeio.py
│   └── security/
│       └── test_traversal.py  # Red Team attacks
├── pyproject.toml
├── Dockerfile
├── README.md
└── ref/                       # Reference documentation
    ├── GAP_ANALYSIS.md        # Security gaps & improvements
    ├── SECURITY_BEST_PRACTICES.md
    ├── INTEGRATION_GUIDE.md   # Aperion integration
    ├── IMPLEMENTATION_ROADMAP.md
    └── KNOWN_ISSUES.md
```

## Reference Documentation

The `/ref` directory contains detailed documentation for development and integration:

| Document | Description |
|----------|-------------|
| [GAP_ANALYSIS.md](ref/GAP_ANALYSIS.md) | Security gaps and prioritized improvements |
| [SECURITY_BEST_PRACTICES.md](ref/SECURITY_BEST_PRACTICES.md) | Industry security guidance and citations |
| [INTEGRATION_GUIDE.md](ref/INTEGRATION_GUIDE.md) | How to integrate with Aperion Legendary AI |
| [IMPLEMENTATION_ROADMAP.md](ref/IMPLEMENTATION_ROADMAP.md) | Phased implementation plan with code samples |
| [KNOWN_ISSUES.md](ref/KNOWN_ISSUES.md) | Current bugs, edge cases, and limitations |

## License

MIT License - see [LICENSE](LICENSE) for details.

---

*"Trust but verify." - The Iron Vault*