Skip to main content

Modularized and Stable Sandbox runtime environment.

Project description

ms-enclave

Modularized and Stable Sandbox runtime environment

Overview

ms-enclave is a modularized and stable sandbox runtime environment that provides secure isolated execution environments for applications. It supports multiple programming languages and frameworks, ensuring code runs safely in controlled environments with Docker-based containerization.

Features

  • 🔒 Secure Isolation: Complete isolation using Docker containers
  • 🧩 Modular Design: Plugin-based architecture with extensible tools
  • High Performance: Optimized runtime performance with resource monitoring
  • 🐍 Python Support: First-class Python code execution with persistent state
  • 📊 Resource Monitoring: Real-time CPU, memory, and resource usage tracking
  • 🛡️ Security Policies: Configurable security policies and permission control
  • 🌐 HTTP API: RESTful API for remote sandbox management
  • 🔧 Tool System: Extensible tool system for different execution environments

Requirements

  • Python >= 3.8
  • Docker >= 20.0.0
  • Operating System: Linux, macOS, or Windows with Docker support

Installation

Install from PyPI

pip install ms-enclave

Install from Source

git clone https://github.com/your-username/ms-enclave.git
cd ms-enclave
pip install -e .

Quick Start

Basic Usage

import asyncio
from ms_enclave.sandbox.boxes import SandboxFactory
from ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType

async def main():
    # Create Docker sandbox configuration
    config = DockerSandboxConfig(
        image='python:3.11-slim',
        timeout=30,
        memory_limit='512m',
        tools_config={'python_executor': {}}
    )

    # Create and use sandbox with context manager
    async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
        # Execute Python code
        result = await sandbox.execute_tool('python_executor', {
            'code': "print('Hello from sandbox!')\nresult = 2 + 2\nprint(f'2 + 2 = {result}')"
        })
        print(f'Result: {result.output}')

asyncio.run(main())

HTTP Server Usage

from ms_enclave.sandbox import create_server

# Start the sandbox server
server = create_server(cleanup_interval=300)
server.run(host='127.0.0.1', port=8000)

or

python -m ms_enclave.run_server

HTTP Manager Client

import asyncio
from ms_enclave.sandbox.manager import HttpSandboxManager
from ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType

async def main():

    async with HttpSandboxManager(base_url='http://127.0.0.1:8000') as manager:
        # Create sandbox
        config = DockerSandboxConfig(image='python:3.11-slim', tools_config={'python_executor': {}})
        sandbox_id = await manager.create_sandbox(SandboxType.DOCKER, config)

        # Execute code
        result = await manager.execute_tool(
            sandbox_id, 'python_executor',
            {'code': 'print("Hello from remote sandbox!")'}
        )
        print(result.model_dump())

asyncio.run(main())

API Reference

SandboxFactory

create_sandbox(sandbox_type, config)

Create a new sandbox instance.

sandbox = SandboxFactory.create_sandbox(SandboxType.DOCKER, config)

Sandbox Methods

execute_tool(tool_name, parameters)

Execute a tool within the sandbox.

result = await sandbox.execute_tool('python_executor', {
    'code': 'print("Hello World")',
    'timeout': 30
})

get_available_tools()

Get list of available tools.

tools = sandbox.get_available_tools()

start() / stop() / cleanup()

Manage sandbox lifecycle.

await sandbox.start()
await sandbox.stop()
await sandbox.cleanup()

HttpSandboxManager

Remote sandbox management via HTTP API.

create_sandbox(sandbox_type, config)

sandbox_id = await manager.create_sandbox(SandboxType.DOCKER, config)

execute_tool(sandbox_id, tool_name, parameters)

result = await manager.execute_tool(sandbox_id, 'python_executor', params)

list_sandboxes(status_filter=None)

sandboxes = await manager.list_sandboxes()

Examples

Advanced Python Execution

async def advanced_example():
    config = DockerSandboxConfig(
        image='python:3.11-slim',
        tools_config={'python_executor': {}},
        memory_limit='1g'
    )

    async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
        # Data processing example
        code = '''
import json
import statistics

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = {
    "mean": statistics.mean(data),
    "median": statistics.median(data),
    "stdev": statistics.stdev(data)
}
print(json.dumps(result, indent=2))
'''

        result = await sandbox.execute_tool('python_executor', {'code': code})
        print(result.output)

Error Handling

async def error_handling_example():
    config = DockerSandboxConfig(
        image='python:3.11-slim',
        tools_config={'python_executor': {}},
        timeout=5
    )

    async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
        # Handle syntax errors
        result = await sandbox.execute_tool('python_executor', {
            'code': 'print("Missing quote'
        })

        if result.error:
            print(f"Error: {result.error}")
        else:
            print(f"Output: {result.output}")

Development

Local Development Setup

# Clone the repository
git clone https://github.com/your-username/ms-enclave.git
cd ms-enclave

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

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

# Run tests
pytest

# Run examples
python examples/usage_examples.py
python examples/server_example.py

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=ms_enclave

# Run specific test file
pytest tests/test_sandbox.py

Tools

Python Executor

Execute Python code with persistent state across multiple calls.

result = await sandbox.execute_tool('python_executor', {
    'code': 'x = 42\nprint(f"Value: {x}")',
    'timeout': 30
})

Available Tools

  • python_executor: Execute Python code
  • bash: Execute bash commands
  • Custom tools can be added via the tool factory system

Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

Contributing Steps

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes and add tests
  4. Run tests: pytest
  5. Commit changes: git commit -m 'Add amazing feature'
  6. Push to branch: git push origin feature/amazing-feature
  7. Submit a Pull Request

License

This project is licensed under the MIT License. See LICENSE file for details.

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

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

ms_enclave-0.0.0-py3-none-any.whl (8.8 kB view details)

Uploaded Python 3

File details

Details for the file ms_enclave-0.0.0-py3-none-any.whl.

File metadata

  • Download URL: ms_enclave-0.0.0-py3-none-any.whl
  • Upload date:
  • Size: 8.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.18

File hashes

Hashes for ms_enclave-0.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3217f261800e7c465490e71c956b4e9ee6f2b9365b90ea34baf640366d4bdbcd
MD5 12e6afd9ddd49a79ae59adc86204ad53
BLAKE2b-256 6ac09cf87e5301dfb95e365d480569cf64042920072202339a6f36c2510b6e5f

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