Skip to main content

A secure Python code execution sandbox

Project description

๐Ÿ”’ Python Sandbox Executor

A secure Python code execution library with dual-mode architecture: run code locally for fast development or connect to a remote API server for production workloads. Perfect for AI agents, code playgrounds, and educational platforms.

โœจ Key Features

  • ๐Ÿ  Local Execution: Direct subprocess execution for fast iteration and debugging
  • ๐ŸŒ Remote Execution: HTTP client for connecting to sandbox API servers
  • ๐Ÿ”„ Unified Interface: Same API works for both local and remote modes
  • ๐Ÿค– AI Agent Ready: Easy integration with LangChain, AutoGen, and custom agents
  • Multi-layered Security: AST validation, resource limits, network control
  • ๐Ÿ“ File I/O Support: Upload input files and retrieve output files
  • โšก Platform Agnostic: Works on Linux, Windows, macOS, Docker, Kubernetes, and serverless

๐Ÿš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/dinhhungitsoft/secure-python-sandbox.git
cd secure-python-sandbox

# Install the package (includes local + remote client)
pip install -e .

# Optional: Install with API server support
pip install -e ".[api]"

๐Ÿ’ก Usage Modes

Mode 1: Local Execution (Development)

Best for: Development, debugging, fast iteration, local AI agents

How it works: Executes code directly on your machine using subprocess isolation

Installation:

pip install -e .

Example:

from sandbox_executor import SandboxClient

# Create client without server_url = local execution
client = SandboxClient()

code = """
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

result = [fibonacci(i) for i in range(10)]
print("Fibonacci:", result)
"""

result = client.execute(code)
print(result.stdout)
# Output: Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Advantages:

  • โšก Fastest: No network overhead
  • ๐Ÿ› Easy debugging: Direct execution with full error messages
  • ๐Ÿ”ง Simple setup: No server required
  • ๐Ÿ’ป Offline capable: Works without internet

Use cases:

  • Local development and testing
  • AI agent prototyping
  • Educational tools
  • Code snippets execution
  • Quick scripts and automation

Mode 2: Remote Execution (Production)

Best for: Production, scaling, untrusted code, multi-tenant systems

How it works: Sends code to a remote API server via HTTP requests

Installation:

# Install package with remote support (already included in core)
pip install -e .

# Set up API server
pip install -e ".[api]"
docker-compose up -d  # Start the sandbox API server

Example:

from sandbox_executor import SandboxClient

# Create client with server_url = remote execution
client = SandboxClient(
    server_url="http://localhost:8000",
    timeout=30
)

code = """
import math

radius = 5
area = math.pi * radius ** 2
print(f"Circle area: {area:.2f}")
"""

result = client.execute(code)
print(result.stdout)
# Output: Circle area: 78.54

Advantages:

  • ๐Ÿ”’ Enhanced security: Code runs in isolated containers
  • ๐Ÿ“ˆ Scalable: Handle multiple concurrent executions
  • ๐ŸŒ Distributed: Execute code on powerful remote machines
  • ๐Ÿ›ก๏ธ Better isolation: Full container-level isolation

Use cases:

  • Production AI agents
  • Multi-tenant code execution platforms
  • Online code playgrounds
  • Serverless functions
  • Educational platforms with many users

๐ŸŽฏ Comparison: Local vs Remote

Feature Local Execution Remote Execution
Speed โšก Fastest (no network) ๐ŸŒ Network latency
Setup โœ… Zero config โš™๏ธ Needs API server
Security ๐Ÿ›ก๏ธ Process isolation ๐Ÿ”’ Container isolation
Scalability ๐Ÿ’ป Single machine ๐Ÿ“ˆ Distributed
Use Case ๐Ÿ› Development ๐Ÿš€ Production
Internet โŒ Not required โœ… Required

Configuration

Local Mode Configuration

from sandbox_executor import SandboxClient, ClientConfig, ExecutionMode

config = ClientConfig(
    server_url=None,  # None = local execution
    mode=ExecutionMode.SECURE,
    timeout=60,
    allow_network=False,
    max_memory_mb=256
)

client = SandboxClient.from_config(config)

Remote Mode Configuration

from sandbox_executor import SandboxClient, ClientConfig

config = ClientConfig(
    server_url="http://your-api-server.com",
    timeout=30,
    api_timeout=60,  # HTTP request timeout
    api_key="your-secret-key"  # Optional authentication
)

client = SandboxClient.from_config(config)

Environment Variables

Create a .env file:

SANDBOX_MODE=secure
SANDBOX_TIMEOUT=30
SANDBOX_ALLOW_NETWORK=false
SANDBOX_MAX_MEMORY_MB=128

Load automatically:

client = SandboxClient.from_env()

Advanced Examples

Working with Files

from sandbox_executor import SandboxClient

client = SandboxClient()

# Provide input files
input_files = {
    "data.csv": b"id,value\n1,100\n2,200\n3,300\n"
}

code = """
import csv

# Read CSV
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    data = list(reader)

# Calculate total
total = sum(int(row['value']) for row in data)
print(f"Total: {total}")

# Write output
with open('result.txt', 'w') as f:
    f.write(f"Sum: {total}\\n")
"""

result = client.execute(code, input_files=input_files)
print(result.stdout)  # Total: 600

# Get output file
output = result.get_file_content('result.txt')
print(output.decode())  # Sum: 600

AI Agent Integration

from sandbox_executor import SandboxClient

class PythonExecutorTool:
    """Tool for AI agents to execute Python code"""
    
    name = "python_executor"
    description = "Execute Python code safely in a sandbox"
    
    def __init__(self, use_remote=False):
        # Switch between local and remote based on environment
        server_url = "http://api.example.com" if use_remote else None
        self.client = SandboxClient(server_url=server_url)
    
    def run(self, code: str) -> str:
        """Execute code and return output"""
        result = self.client.execute(code)
        return result.stdout if result.success else f"Error: {result.stderr}"

# For development (local)
tool = PythonExecutorTool(use_remote=False)

# For production (remote)
tool = PythonExecutorTool(use_remote=True)

Error Handling

from sandbox_executor import SandboxClient, SandboxException

client = SandboxClient()

code = "print(1/0)"  # Will raise ZeroDivisionError

try:
    result = client.execute(code)
    if not result.success:
        print(f"Execution failed with code {result.return_code}")
        print(f"Error: {result.stderr}")
except SandboxException as e:
    print(f"Sandbox error: {e}")

๐Ÿณ Running the API Server (Remote Mode)

Using Docker Compose (Recommended)

# Start the server
docker-compose up -d

# Check logs
docker-compose logs -f

# Stop the server
docker-compose down

Using Docker

# Build image
docker build -t python-sandbox .

# Run container
docker run -d -p 8000:8000 \
  -e EXECUTION_MODE=secure \
  -e SANDBOX_TIMEOUT=30 \
  python-sandbox

Manual Setup

# Install with API dependencies
pip install -e ".[api]"

# Run server
uvicorn src.main:app --host 0.0.0.0 --port 8000

API Documentation

Once the server is running, visit:

API Endpoints

GET / - Health Check

curl http://localhost:8000/

POST /execute - Execute Code

curl -X POST http://localhost:8000/execute \
  -H "Content-Type: application/json" \
  -d '{
    "code": "print(\"Hello, World!\")",
    "timeout": 30,
    "allow_network": false
  }'

๐Ÿ—๏ธ Architecture

Security Layers

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   1. AST Validation                 โ”‚  Compile-time filtering
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   2. Import Restrictions            โ”‚  Module whitelist/blacklist
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   3. Resource Limits                โ”‚  CPU, Memory, Processes
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   4. Filesystem Isolation           โ”‚  Temporary directory sandbox
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   5. Network Blocking               โ”‚  Socket monkey-patching
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚   6. Execution Timeout              โ”‚  Hard timeout enforcement
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Execution Modes

Secure Mode (Default):

  • AST validation and restricted imports
  • Resource limits (CPU, memory, processes)
  • Filesystem isolation with temporary directories
  • Network blocking (configurable)
  • Execution timeout enforcement

Simple Mode:

  • Basic subprocess isolation
  • Timeout and output limits
  • Suitable for trusted code

๐Ÿ“š Examples

See the examples/ directory for complete examples:

  • basic_usage.py - Basic execution patterns
  • client_usage.py - Local vs Remote client usage
  • agent_integration.py - AI agent integration examples
  • with_files.py - Working with input/output files
  • security_tests.py - Security feature demonstrations

Run examples:

python examples/basic_usage.py
python examples/client_usage.py
python examples/agent_integration.py

โš™๏ธ Configuration

Environment Variables

Configure the sandbox behavior using environment variables (in .env):

Variable Default Description
SANDBOX_MODE secure Execution mode: secure or simple
SANDBOX_TIMEOUT 30 Default execution timeout (seconds)
SANDBOX_ALLOW_NETWORK false Allow network access by default
SANDBOX_MAX_MEMORY_MB 128 Maximum memory usage (MB)

Security Configuration

The secure executor includes configurable whitelists and blacklists:

Safe Modules (allowed by default):

  • math, random, datetime, json, base64, hashlib
  • collections, itertools, functools, re, string
  • decimal, fractions, statistics, uuid, secrets

Blocked Modules (always restricted):

  • os, sys, subprocess, multiprocessing, threading
  • socket, urllib, requests, http, ftplib, smtplib
  • importlib, eval, exec, compile

๐Ÿ›ก๏ธ Security Considerations

What's Protected

โœ… Import restrictions: Dangerous modules are blocked
โœ… Resource limits: CPU, memory, and process limits enforced
โœ… Filesystem isolation: Code runs in temporary directories
โœ… Network blocking: Optional socket-level blocking
โœ… Timeout enforcement: Hard timeout prevents infinite loops
โœ… AST validation: Compile-time code analysis

What's NOT Protected

โš ๏ธ DoS attacks: Malicious code can still consume allowed resources
โš ๏ธ Side-channel attacks: Timing and cache attacks are possible
โš ๏ธ Data exfiltration: If network is enabled, data can be sent out
โš ๏ธ Cryptographic operations: CPU-intensive operations within limits

Best Practices

  1. Always use secure mode in production
  2. Keep network access disabled unless required
  3. Set appropriate resource limits based on your use case
  4. Monitor resource usage and adjust limits accordingly
  5. Run in containers for additional isolation
  6. Keep dependencies updated for security patches
  7. Validate user input before sending to the sandbox
  8. Implement rate limiting to prevent abuse

๐Ÿงช Testing

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

# Run all tests
pytest

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

# Run specific test file
pytest tests/test_sandbox_executor.py

See tests/README.md for detailed testing documentation.

๐Ÿ”ง Development

Project Structure

python_sandbox/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.py                          # FastAPI application (API server)
โ”‚   โ”œโ”€โ”€ executor_factory.py              # Legacy factory pattern
โ”‚   โ””โ”€โ”€ sandbox_executor/                # Main package
โ”‚       โ”œโ”€โ”€ __init__.py                  # Package exports
โ”‚       โ”œโ”€โ”€ client.py                    # Unified client (local/remote)
โ”‚       โ”œโ”€โ”€ executor.py                  # Local executor
โ”‚       โ”œโ”€โ”€ config.py                    # Configuration classes
โ”‚       โ”œโ”€โ”€ exceptions.py                # Custom exceptions
โ”‚       โ””โ”€โ”€ executors/                   # Backend implementations
โ”‚           โ”œโ”€โ”€ sandbox_executor.py      # Simple mode
โ”‚           โ””โ”€โ”€ secure_sandbox_executor.py  # Secure mode
โ”œโ”€โ”€ examples/                            # Usage examples
โ”‚   โ”œโ”€โ”€ basic_usage.py                   # Basic patterns
โ”‚   โ”œโ”€โ”€ client_usage.py                  # Local vs Remote
โ”‚   โ”œโ”€โ”€ agent_integration.py             # AI agent examples
โ”‚   โ””โ”€โ”€ ...
โ”œโ”€โ”€ tests/                               # Test suite
โ”œโ”€โ”€ docker-compose.yml                   # Docker Compose config
โ”œโ”€โ”€ Dockerfile                           # Docker image
โ””โ”€โ”€ pyproject.toml                       # Package configuration

๐Ÿšข Deployment

Local Development

pip install -e .
python examples/basic_usage.py

API Server (Docker)

docker-compose up -d

Documentation

Cloud Platforms

The sandbox is compatible with:

  • AWS Fargate: Deploy as ECS task
  • Azure Container Apps: Deploy as container app
  • Google Cloud Run: Deploy as Cloud Run service
  • Heroku: Deploy as Docker container
  • DigitalOcean App Platform: Deploy as Docker app

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

๐Ÿ“ž Support

โญ Star History

If you find this project useful, please give it a star! โญ


Made with โค๏ธ for the Python & AI community

โš ๏ธ Security Note: While this sandbox provides multiple layers of security, no sandbox is 100% foolproof. Always run in isolated environments and implement additional security measures for production use with untrusted code.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sandbox_executor-0.1.0.tar.gz (37.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sandbox_executor-0.1.0-py3-none-any.whl (29.7 kB view details)

Uploaded Python 3

File details

Details for the file sandbox_executor-0.1.0.tar.gz.

File metadata

  • Download URL: sandbox_executor-0.1.0.tar.gz
  • Upload date:
  • Size: 37.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.1

File hashes

Hashes for sandbox_executor-0.1.0.tar.gz
Algorithm Hash digest
SHA256 9c03f03f38531b257db80e8e6456e610812e6388ecb6efbe007259cb43263cac
MD5 6ea79d3a03ecf6f6aabd7617b8c7541c
BLAKE2b-256 99dabc45f777f20b7843129eac9b555b732c842cf0887e8996efe7ffc4f5185f

See more details on using hashes here.

File details

Details for the file sandbox_executor-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for sandbox_executor-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b84e568b298699ad969660c0a023c251bd01423470b7ba56d6ed81983b36c274
MD5 917c56b824922368160546a7b6c3679a
BLAKE2b-256 6d076e3459987d72a676dc58c9df460eca25b63fb893ef47ba103a2b8eb7bdeb

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page