# SafeCodeExecutor Documentation

## Overview

SafeCodeExecutor is a sandboxed code execution engine for AI agents in the DAARION stack. It allows agents like Sofiia to execute code safely for engineering tasks (parsing, transformation, calculations) without access to secrets, network, or host filesystem.

## Security Model

### Isolation
- **Subprocess-based**: Code runs in isolated subprocess
- **No network access**: All network operations blocked
- **No filesystem access**: Only temp directory for execution
- **Resource limits**: CPU time, memory, output size

### Blocked Imports (Python)
```
os, sys, subprocess, socket, requests, http, ftplib, smtplib,
pty, tty, termios, fcntl, importlib, pathlib, glob, shutil,
tempfile, cryptography, ssl, eval, exec, compile, open,
pickle, marshal, yaml, __import__, getattr, setattr
```

### Allowed Imports
```
json, math, re, datetime, time, calendar, collections,
functools, itertools, random, statistics, string, base64,
hashlib, hmac, secrets, urllib.parse, html, xml.etree.ElementTree,
typing, types, copy, pprint, textwrap
```

## Limits

| Limit | Default | Max |
|-------|---------|-----|
| Timeout | 5s | 30s |
| Memory | 256MB | 1GB |
| Stdout | 64KB | 1MB |
| Stderr | 8KB | 64KB |

## Usage

### Python

```python
from safe_code_executor import SafeCodeExecutor

executor = SafeCodeExecutor()

# Basic execution
result = executor.execute(
    language="python",
    code="""
import json
data = {"a": 1, "b": 2}
print(json.dumps({"sum": data["a"] + data["b"]}))
"""
)

print(result["status"])       # "succeeded"
print(result["stdout"])       # output
print(result["result_json"])  # parsed JSON
```

### JavaScript

```python
result = executor.execute(
    language="javascript",
    code="""
const data = {a: 1, b: 2};
console.log(JSON.stringify({sum: data.a + data.b}));
"""
)
```

## API

### POST /v1/tools/safe-exec

Execute code synchronously.

```json
{
  "language": "python",
  "code": "print('hello')",
  "limits": {
    "timeout_ms": 3000,
    "max_memory_mb": 256
  }
}
```

Response:
```json
{
  "status": "succeeded",
  "execution_id": "abc123",
  "stdout": "hello\n",
  "stderr": "",
  "result_json": null,
  "metrics": {
    "execution_time_ms": 45,
    "stdout_bytes": 6
  }
}
```

### POST /v1/tools/safe-exec/async

Execute code asynchronously, returns job_id.

### GET /v1/jobs/{job_id}

Get async job result.

## Integration with Sofiia

```python
# In Sofiia's tool registry
from safe_code_executor import SafeCodeExecutor

tools = {
    "safe_exec": SafeCodeExecutor()
}
```

## Threat Model

### What We Protect Against
- Agent escaping sandbox to access host
- Agent accessing secrets from environment
- Agent making network calls
- Agent reading sensitive files
- Resource exhaustion attacks

### What We Don't Protect Against
- Malicious code that doesn't try to escape
- Side-channel attacks
- Timing attacks on specific operations

## Running Locally

```bash
# Run unit tests
python tools/safe_code_executor/tests/test_unit.py

# Run security tests
python tools/safe_code_executor/tests/test_security.py
```

## Production Deployment

For production, consider:
1. **Docker sandbox**: Run each execution in ephemeral container
2. **gVisor**: Lightweight kernel isolation
3. **firejail/nsjail**: Process-level isolation
4. **Ephemeral VMs**: Kata Containers for stronger isolation
