Metadata-Version: 2.4
Name: lasso-sandbox
Version: 0.4.0
Summary: LASSO — Layered Agent Sandbox Security Orchestrator
Author: LASSO Team
License: Apache-2.0
Project-URL: Homepage, http://100.90.210.83:8085/j1212/Lasso
Project-URL: Source, http://100.90.210.83:8085/j1212/Lasso
Project-URL: Documentation, http://100.90.210.83:8085/j1212/Lasso/src/branch/main/docs
Project-URL: Issues, http://100.90.210.83:8085/j1212/Lasso/issues
Project-URL: Changelog, http://100.90.210.83:8085/j1212/Lasso/src/branch/main/TODO.md
Keywords: sandbox,security,ai-agents,docker,container,audit,compliance
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Testing
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: typer>=0.9
Requires-Dist: rich>=13.0
Requires-Dist: pydantic>=2.0
Requires-Dist: tomli>=2.0
Requires-Dist: tomli_w>=1.0
Requires-Dist: docker>=7.0
Requires-Dist: flask>=3.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"

# LASSO -- Layered Agent Sandbox Security Orchestrator

LASSO provides sandboxed execution environments for AI coding agents using
containers (Docker/Podman). You define security profiles that enforce command
whitelists and blacklists, network access control, filesystem isolation, and
resource limits. Every action is recorded in a tamper-evident, HMAC-signed audit
log. LASSO is designed for security-conscious teams and compliance-ready for
regulated environments (DORA, EU AI Act, ISO 27001).

![LASSO Dashboard](docs/screenshots/dashboard.png)

## Quick Start

**Prerequisites**: Python 3.10+, [Podman](https://podman.io/) (recommended) or Docker

```bash
# Install LASSO
pip install .

# Verify your system and container runtime
lasso check

# Authenticate with GitHub (for Copilot Enterprise token injection)
lasso auth login

# Bootstrap a project directory with a security profile
lasso init --profile development --agent opencode

# Create and start a sandboxed container
lasso create development --dir .

# Or launch an interactive REPL session
lasso interactive development --dir .
```

## Zero-Config Agent Mode

Run any supported AI coding agent in a sandbox with a single command:

```bash
lasso run claude-code            # Claude Code with development profile
lasso run cursor --dir ./project # Cursor in specific directory
lasso run aider                  # Aider with development profile
lasso run codex                  # OpenAI Codex with development profile
lasso run goose                  # Goose with development profile
lasso run gemini                 # Gemini CLI with development profile
```

LASSO auto-selects the appropriate security profile and generates
agent-specific configuration files. You can override the profile:

```bash
lasso run claude-code --mode autonomous  # full access
lasso run cursor --env ANTHROPIC_API_KEY=sk-...  # pass credentials
lasso run claude-code --isolation gvisor  # enhanced isolation (requires runsc)
```

### Isolation Levels

LASSO supports three isolation levels, selectable per sandbox:

| Level | Runtime | Isolation | Platform | Use Case |
|-------|---------|-----------|----------|----------|
| `container` | Docker/Podman | Namespace + cgroup | All | Default, fast startup |
| `gvisor` | runsc | Syscall interception | Linux + Docker Desktop | Enhanced security, no direct kernel access |
| `kata` | Kata Containers | Full VM (separate kernel) | Linux only | Maximum isolation for regulated environments |

```bash
# Use gVisor for enhanced isolation (works with Docker Desktop on Windows/macOS)
lasso create development --isolation gvisor --dir .

# Use Kata for VM-level isolation (Linux only)
lasso create strict --isolation kata --dir .

# Set isolation in profile TOML (persistent)
# isolation = "gvisor"
```

Install gVisor: https://gvisor.dev/docs/user_guide/install/

## Authentication

LASSO uses GitHub OAuth Device Flow for authentication. This provides secure
token acquisition for GitHub Copilot Enterprise and dashboard access.

```bash
# Log in via browser-based device flow
lasso auth login

# Check authentication status
lasso auth status

# View the stored token (masked)
lasso auth token

# Log out and remove stored token
lasso auth logout
```

You can also set the `GITHUB_TOKEN` environment variable to skip the device
flow entirely. LASSO checks this variable first and uses it as an override.

When a sandbox profile has `agent_auth.github_token_env` configured, LASSO
injects the authenticated token into the container environment. This allows
agents like GitHub Copilot Enterprise and OpenCode to authenticate with their
LLM providers without exposing credentials on the host system.

## Multi-Sandbox Orchestration

LASSO is built around a `SandboxRegistry` that manages multiple concurrent
sandboxes. Each sandbox has its own security profile, command policy, network
rules, and audit trail. You can run several sandboxes at once -- one per
project, one per agent, or any combination -- and manage them from the CLI,
dashboard, SDK, MCP server, or REST API.

### CLI Workflow

```bash
# Create multiple sandboxes with different profiles
lasso create development --dir ./frontend --quiet    # prints sandbox-id-1
lasso create offline --dir ./ml-pipeline --quiet  # prints sandbox-id-2
lasso create minimal --dir ./scripts --quiet          # prints sandbox-id-3

# List all running sandboxes
lasso status              # or: lasso ps
lasso status --json       # machine-readable output

# Execute commands in specific sandboxes
lasso exec <id-1> -- npm test
lasso exec <id-2> -- python3 train.py
lasso exec <id-3> -- ./validate.sh

# Stop individual sandboxes or all at once
lasso stop <id-1>         # or: lasso rm <id-1>
lasso stop all
```

**Aliases**: `lasso ps` is `lasso status`, `lasso rm` is `lasso stop`,
`lasso run` is `lasso create`.

**Output modes**: Most commands accept `--quiet` (suppress decorative output,
print only IDs) and `--json` (machine-readable JSON output).

### Dashboard Workflow

```bash
lasso dashboard           # starts on http://localhost:8080
```

The web dashboard provides a real-time view of all sandboxes:

- Create sandboxes from any profile via the dashboard form
- Monitor all sandbox states with HTMX live auto-refresh
- Execute commands in any sandbox via the built-in terminal
- View per-sandbox audit logs with filtering and pagination
- Manage and inspect profiles with the tabbed editor
- Run system capability checks

Authentication is token-based with CSRF protection. On first launch, a login
token is generated and printed to the console. Set `LASSO_DASHBOARD_PUBLIC=1`
to disable authentication for local development.

![Sandbox Detail](docs/screenshots/sandbox-detail.png)

### SDK Workflow

```python
from lasso.sdk import LassoClient

# Local mode (default) -- uses SandboxRegistry directly
client = LassoClient()

# Create multiple sandboxes in parallel
frontend = client.create("development", "/projects/frontend")
backend = client.create("development", "/projects/backend")
analysis = client.create("offline", "/projects/data")

# Execute commands in each
frontend.exec("npm test")
backend.exec("python3 -m pytest")
analysis.exec("python3 analyze.py")

# Check status across all sandboxes
for sb in client.list():
    print(f"{sb['name']}: {sb['state']}")

# Context manager for automatic cleanup
with client.sandbox("development", "/my/project") as sb:
    result = sb.exec("ls -la")
    print(result.stdout)

# Gracefully stop all sandboxes and save state
client.shutdown()
```

The SDK also supports **remote mode** for connecting to a running LASSO server:

```python
client = LassoClient(
    api_url="http://localhost:8080",
    api_key="lasso_xxx",
)
```

Remote mode uses the REST API with automatic retry and exponential backoff on
transient failures.

### MCP Workflow

LASSO works as an MCP (Model Context Protocol) tool execution gateway. AI
agents connect via JSON-RPC 2.0 over stdio and all tool calls are routed
through sandboxed execution.

```bash
# Start the MCP server
lasso mcp --profile development --dir .

# Generate MCP client config (for Claude Desktop, VS Code, etc.)
lasso mcp config --profile development
```

Each MCP session can create and manage its own sandboxes. Multiple agents can
connect simultaneously, each receiving an isolated execution environment.

The server exposes 7 MCP tools: `sandbox_exec`, `sandbox_create`,
`sandbox_stop`, `sandbox_status`, `sandbox_list`, `file_read`, `file_write`.

### REST API Workflow

```bash
# Create multiple sandboxes via the API
curl -X POST http://localhost:8080/api/v1/sandboxes \
  -H "Content-Type: application/json" \
  -H "X-API-Key: lasso_xxx" \
  -d '{"profile":"development","working_dir":"/tmp/project1"}'

curl -X POST http://localhost:8080/api/v1/sandboxes \
  -H "Content-Type: application/json" \
  -H "X-API-Key: lasso_xxx" \
  -d '{"profile":"offline","working_dir":"/tmp/project2"}'

# List all sandboxes
curl http://localhost:8080/api/v1/sandboxes \
  -H "X-API-Key: lasso_xxx"

# Execute a command in a specific sandbox
curl -X POST http://localhost:8080/api/v1/sandboxes/<id>/exec \
  -H "Content-Type: application/json" \
  -H "X-API-Key: lasso_xxx" \
  -d '{"command":"python3 test.py"}'

# Stop a sandbox
curl -X POST http://localhost:8080/api/v1/sandboxes/<id>/stop \
  -H "X-API-Key: lasso_xxx"
```

### Warm Pool

For latency-sensitive workflows, the warm pool pre-creates standby containers
so that sandbox creation completes in sub-500ms instead of the full image-build
and container-create cycle.

The warm pool maintains N containers per profile (configurable, default 2),
replenishes automatically on background threads after a container is claimed,
and shuts down cleanly with the registry.

## Profiles

LASSO ships with five built-in profiles. You can create custom profiles as
TOML files and share them across your team.

| Profile | Commands | Network | Memory | Description |
|---------|----------|---------|--------|-------------|
| `minimal` | Whitelist: `ls`, `cat`, `grep`, `echo`, ... | None | 512 MB | Pure computation, untrusted agent evaluation. |
| `development` | Whitelist: `python3`, `git`, `npm`, `curl`, ... | Restricted (package registries, GitHub) | 4 GB | General coding, building, testing. |
| `offline` | Whitelist: `python3`, `R`, `jupyter`, ... | None | 8 GB | Data science and analytics with full audit trail. Compliance-ready. |

### Profile Sharing

```bash
# Export a profile for team sharing (includes integrity hash)
lasso profile export offline --output ./shared-profiles/analysis.toml

# Import a shared profile (validates integrity on import)
lasso profile import ./shared-profiles/analysis.toml --name our-analysis

# Compare two profiles side by side
lasso profile diff minimal development
```

Profiles support automatic versioning with history stored in
`~/.lasso/profiles/.history/`. Set the `LASSO_PROFILE_DIR` environment
variable to point at a shared directory (supports colon-separated paths for
multiple directories). Personal profiles in `~/.lasso/profiles/` are always
included as a fallback.

## Agent Support

LASSO auto-detects and configures sandboxes for 9 AI agent providers:

| Agent | Config Generated | Authentication |
|-------|-----------------|----------------|
| **OpenCode** | `opencode.json` + `AGENTS.md` + sandbox plugin | API key via `OPENCODE_API_KEY` env var |
| **Claude Code** | `CLAUDE.md` + `.claude/settings.json` | Built-in CLI auth |
| **GitHub Copilot** | `.github/copilot-instructions.md` + `copilot-settings.json` | GitHub token |
| **VS Code** | `.vscode/settings.json` + shell wrapper | Per-extension |
| **Cursor** | `.cursorrules` + `.cursor/rules/` | Built-in auth |
| **Aider** | `.aider.conf.yml` + `CONVENTIONS.md` | API key env var |
| **Goose** | `.goosehints` | Provider-specific |
| **Gemini CLI** | `GEMINI.md` + `.gemini/settings.json` | Google auth |
| **OpenAI Codex** | `AGENTS.md` + `codex.json` | OpenAI API key |

```bash
# Initialize with a specific agent
lasso init --profile development --agent copilot

# Preview agent config without writing files
lasso agent config copilot --profile offline

# List detected agents and their status
lasso agent list
```

LASSO translates its universal `SandboxProfile` into each agent's native
configuration format -- permissions, rules, tool access, and behavioral
guardrails. This is defense-in-depth: even if a command passes the agent's
own permission system, the container's command gate still blocks it.

## Security

LASSO uses a defense-in-depth approach with five layers:

1. **Command Gate** -- Multi-stage validation pipeline: null byte stripping, control
   character rejection, shell operator blocking, URL-encoded traversal
   detection, unicode lookalike detection, symlink resolution, dangerous
   argument patterns for 25+ commands, whitelist/blacklist enforcement.
   **Note:** The command gate validates command names and arguments as strings.
   It cannot analyze what interpreters (python3, node, etc.) do with their
   arguments. For interpreter-class commands, the container itself is the
   security boundary -- the command gate provides defense-in-depth.
2. **Container Isolation** -- Docker/Podman with all capabilities dropped,
   read-only root filesystem, non-root user (1000:1000), no-new-privileges
   flag, memory/CPU/PID cgroup limits, tmpfs for `/tmp`, custom image per
   profile. Supports three isolation levels:
   - `container` (default) -- standard OCI containers with Docker's default seccomp
   - `gvisor` -- syscall interception via Google's runsc runtime (no direct kernel access)
   - `kata` -- full VM isolation via Kata Containers (Linux only)
3. **Network Policy** -- iptables rules applied inside containers. Domain
   whitelisting, CIDR blocking, port restrictions, cloud metadata endpoint
   blocking (169.254.169.254).
4. **Guardrails Engine** -- Path escape detection, data exfiltration detection,
   agent instruction enforcement, behavioral rules.
5. **Audit Logging** -- HMAC-SHA256 signed, hash-chained JSONL entries for
   tamper-evident post-incident analysis. Webhook dispatch to SIEM/SOAR systems.

See [`docs/security/threat-model.md`](docs/security/threat-model.md) for the
full threat model.

## Dashboard

```bash
lasso dashboard
```

Opens a web UI on `http://localhost:8080` with:

- Real-time sandbox monitoring with HTMX live updates
- Terminal-style command execution in any sandbox
- Profile management with tabbed editor
- Audit log viewer with type filtering and pagination
- System capability checks
- Token-based authentication with CSRF protection
- Prometheus metrics at `/metrics`

Dark theme, zero external CSS dependencies (Pico CSS), mobile responsive.

![Audit Log](docs/screenshots/audit-log.png)

## REST API

LASSO exposes a full REST API with 19+ endpoints for programmatic control:

```
Sandboxes:
  POST   /api/v1/sandboxes              Create sandbox
  GET    /api/v1/sandboxes              List sandboxes (paginated)
  GET    /api/v1/sandboxes/<id>         Get sandbox detail
  POST   /api/v1/sandboxes/<id>/exec    Execute command
  POST   /api/v1/sandboxes/<id>/stop    Stop sandbox
  DELETE /api/v1/sandboxes/<id>         Remove sandbox

Profiles:
  GET    /api/v1/profiles               List profiles (paginated)
  GET    /api/v1/profiles/<name>        Get profile detail
  POST   /api/v1/profiles               Create/save profile
  DELETE /api/v1/profiles/<name>        Delete saved profile

Audit:
  GET    /api/v1/sandboxes/<id>/audit   Get audit entries (paginated)
  POST   /api/v1/audit/verify           Verify audit log integrity

Webhooks:
  POST   /api/v1/webhooks/test          Test webhook delivery
  GET    /api/v1/webhooks/events        List webhook event types

System:
  GET    /api/v1/health                 Health check with uptime
  GET    /api/v1/system/check           System capabilities
  GET    /api/v1/agents                 List agent providers
  GET    /api/v1/openapi.json           OpenAPI 3.0 spec
  GET    /api/v1/docs                   Swagger UI
```

Authentication via `X-API-Key` header. Rate limited to 100 requests/minute per
key with `X-RateLimit-*` headers on every response. Interactive Swagger UI
available at `/api/v1/docs`.

## Audit Logging

Every command executed inside a sandbox is recorded in a tamper-evident audit
log. Entries are HMAC-SHA256 signed and hash-chained in JSONL format, so any
modification or deletion is detectable.

```bash
# View the audit trail
lasso audit view ./audit/log.jsonl

# Verify log integrity (checks HMAC signatures and hash chain)
lasso audit verify ./audit/log.jsonl

# Export for compliance review
lasso audit export ./audit/log.jsonl --format csv --output report.csv
```

Webhooks can forward audit events to external systems (SIEM, SOAR) in
real-time. Configure webhooks in the profile's `audit.webhooks` section with
HMAC-signed payloads and automatic retry.

## Compliance

LASSO is designed for regulated environments:

- **DORA** -- Article-by-article mapping in `docs/compliance/DORA-mapping.md`
- **EU AI Act** -- High-risk system requirements in `docs/compliance/EU-AI-Act-mapping.md`
- **ISO 27001** -- A.12 operations security control alignment

EU AI Act high-risk provisions deadline: **August 2, 2026**.

## Platform Support

| Platform | Container Runtime | Notes |
|----------|------------------|-------|
| **Windows** (primary) | Podman Desktop (recommended), Docker Desktop | Platform-aware paths, PowerShell CLI |
| **Linux** | Podman, Docker | Native namespace fallback available |
| **macOS** | Docker Desktop, Podman | |

On Windows, [Podman Desktop](https://podman-desktop.io/) is recommended (free
for enterprise use, no license required).

## Testing

```bash
# Unit tests (813 tests, ~21s, no container runtime needed)
python3 -m pytest tests/ -m "not integration" -q

# All tests including Docker integration
python3 -m pytest tests/ -q
```

For development with test dependencies:

```bash
pip install -e ".[dev]"
```

## Architecture

```
lasso/
  agents/      AI agent providers (9 providers: OpenCode, Claude Code, Copilot, VS Code, Cursor, Aider, Goose, Gemini CLI, Codex)
  api/         REST API with auth, rate limiting, OpenAPI, Prometheus metrics
  auth/        GitHub OAuth device flow
  backends/    Pluggable container backends (Docker, Podman)
  cli/         Typer CLI interface with Rich output
  config/      Pydantic schemas, TOML profiles, sharing and versioning
  core/        Sandbox orchestrator, command gate, audit, network, state, warm pool
  dashboard/   Flask + HTMX web UI with auth
  mcp/         MCP server (JSON-RPC 2.0 tool execution gateway)
  sdk/         Python SDK client (local and remote modes)
  utils/       HMAC signing and file hashing
```

See [`docs/architecture.md`](docs/architecture.md) for the full architecture
documentation including request flows, defense-in-depth layer diagrams,
state management, and extension points.

## Presentation Materials

LASSO includes ready-to-use presentation materials in `presentation/`:

- `index.html` — English slide deck (10 slides, keyboard navigation)
- `index-no.html` — Norwegian (Bokmål) slide deck
- `dashboard-tour.html` — Interactive dashboard screenshot tour
- `demo-script.md` — Step-by-step live demo script
- `setup-guide.md` — 5-minute team setup guide

Open in a browser: `firefox presentation/index-no.html`

## License

Apache 2.0
