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:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
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 patternsclient_usage.py- Local vs Remote client usageagent_integration.py- AI agent integration exampleswith_files.py- Working with input/output filessecurity_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,hashlibcollections,itertools,functools,re,stringdecimal,fractions,statistics,uuid,secrets
Blocked Modules (always restricted):
os,sys,subprocess,multiprocessing,threadingsocket,urllib,requests,http,ftplib,smtplibimportlib,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
- Always use secure mode in production
- Keep network access disabled unless required
- Set appropriate resource limits based on your use case
- Monitor resource usage and adjust limits accordingly
- Run in containers for additional isolation
- Keep dependencies updated for security patches
- Validate user input before sending to the sandbox
- 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
- examples/ - Code examples
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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
๐ Support
- GitHub Issues: Report bugs or request features
- Examples: Check the examples/ directory
- API Docs: Visit http://localhost:8000/docs when running the server
โญ 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sandbox_executor-0.1.2.tar.gz.
File metadata
- Download URL: sandbox_executor-0.1.2.tar.gz
- Upload date:
- Size: 38.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b18006281c670c969cd818ffb4db04bdc9ba5f8befd4c0a97b2e07298cbf2ce5
|
|
| MD5 |
69c8fb66b0bfc9d7dae74f1ba544cf4a
|
|
| BLAKE2b-256 |
6b5674b25815918c2c971f5f226b6cff83c3e16786557660af659f5f2e89b385
|
Provenance
The following attestation bundles were made for sandbox_executor-0.1.2.tar.gz:
Publisher:
publish.yml on dinhhungitsoft/secure-python-sandbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sandbox_executor-0.1.2.tar.gz -
Subject digest:
b18006281c670c969cd818ffb4db04bdc9ba5f8befd4c0a97b2e07298cbf2ce5 - Sigstore transparency entry: 702382065
- Sigstore integration time:
-
Permalink:
dinhhungitsoft/secure-python-sandbox@f26b9fece60c20da97313a68d5c9ed76ea7bb08f -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/dinhhungitsoft
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@f26b9fece60c20da97313a68d5c9ed76ea7bb08f -
Trigger Event:
release
-
Statement type:
File details
Details for the file sandbox_executor-0.1.2-py3-none-any.whl.
File metadata
- Download URL: sandbox_executor-0.1.2-py3-none-any.whl
- Upload date:
- Size: 29.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fcb263a3bb46347ee1fbb3e5b7209c91759b0c12aec38eb387095a8b152ccb3d
|
|
| MD5 |
1340046ced53bf78c9e459ecc0448c13
|
|
| BLAKE2b-256 |
2165b2a77abf4d2c2d9be8beeba7d3fcb4db86c8aca77e6a32e08ba6812918f5
|
Provenance
The following attestation bundles were made for sandbox_executor-0.1.2-py3-none-any.whl:
Publisher:
publish.yml on dinhhungitsoft/secure-python-sandbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sandbox_executor-0.1.2-py3-none-any.whl -
Subject digest:
fcb263a3bb46347ee1fbb3e5b7209c91759b0c12aec38eb387095a8b152ccb3d - Sigstore transparency entry: 702382067
- Sigstore integration time:
-
Permalink:
dinhhungitsoft/secure-python-sandbox@f26b9fece60c20da97313a68d5c9ed76ea7bb08f -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/dinhhungitsoft
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@f26b9fece60c20da97313a68d5c9ed76ea7bb08f -
Trigger Event:
release
-
Statement type: