feat: support agent skills
feat:support agent skills
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DockerSandbox implements the Sandbox interface using Docker containers
|
||||
type DockerSandbox struct {
|
||||
config *Config
|
||||
}
|
||||
|
||||
// NewDockerSandbox creates a new Docker-based sandbox
|
||||
func NewDockerSandbox(config *Config) *DockerSandbox {
|
||||
if config == nil {
|
||||
config = DefaultConfig()
|
||||
}
|
||||
if config.DockerImage == "" {
|
||||
config.DockerImage = "python:3.11-slim"
|
||||
}
|
||||
return &DockerSandbox{
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// Type returns the sandbox type
|
||||
func (s *DockerSandbox) Type() SandboxType {
|
||||
return SandboxTypeDocker
|
||||
}
|
||||
|
||||
// IsAvailable checks if Docker is available
|
||||
func (s *DockerSandbox) IsAvailable(ctx context.Context) bool {
|
||||
cmd := exec.CommandContext(ctx, "docker", "version")
|
||||
if err := cmd.Run(); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Execute runs a script in a Docker container
|
||||
func (s *DockerSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {
|
||||
if config == nil {
|
||||
return nil, ErrInvalidScript
|
||||
}
|
||||
|
||||
// Set default timeout
|
||||
timeout := config.Timeout
|
||||
if timeout == 0 {
|
||||
timeout = s.config.DefaultTimeout
|
||||
}
|
||||
if timeout == 0 {
|
||||
timeout = DefaultTimeout
|
||||
}
|
||||
|
||||
// Create context with timeout
|
||||
execCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
// Build docker run command
|
||||
args := s.buildDockerArgs(config)
|
||||
|
||||
startTime := time.Now()
|
||||
cmd := exec.CommandContext(execCtx, "docker", args...)
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
if config.Stdin != "" {
|
||||
cmd.Stdin = strings.NewReader(config.Stdin)
|
||||
}
|
||||
|
||||
err := cmd.Run()
|
||||
duration := time.Since(startTime)
|
||||
|
||||
result := &ExecuteResult{
|
||||
Stdout: stdout.String(),
|
||||
Stderr: stderr.String(),
|
||||
Duration: duration,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if execCtx.Err() == context.DeadlineExceeded {
|
||||
result.Killed = true
|
||||
result.Error = ErrTimeout.Error()
|
||||
result.ExitCode = -1
|
||||
} else if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
result.ExitCode = exitErr.ExitCode()
|
||||
} else {
|
||||
result.Error = err.Error()
|
||||
result.ExitCode = -1
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// buildDockerArgs constructs the docker run command arguments
|
||||
func (s *DockerSandbox) buildDockerArgs(config *ExecuteConfig) []string {
|
||||
args := []string{"run", "--rm"}
|
||||
|
||||
// Security: run as non-root user
|
||||
args = append(args, "--user", "1000:1000")
|
||||
|
||||
// Security: drop all capabilities
|
||||
args = append(args, "--cap-drop", "ALL")
|
||||
|
||||
// Security: read-only root filesystem (optional)
|
||||
if config.ReadOnlyRootfs {
|
||||
args = append(args, "--read-only")
|
||||
// Add writable tmp directory
|
||||
args = append(args, "--tmpfs", "/tmp:rw,noexec,nosuid,size=64m")
|
||||
}
|
||||
|
||||
// Resource limits
|
||||
memLimit := config.MemoryLimit
|
||||
if memLimit == 0 {
|
||||
memLimit = s.config.MaxMemory
|
||||
}
|
||||
if memLimit > 0 {
|
||||
args = append(args, "--memory", fmt.Sprintf("%d", memLimit))
|
||||
args = append(args, "--memory-swap", fmt.Sprintf("%d", memLimit)) // Disable swap
|
||||
}
|
||||
|
||||
cpuLimit := config.CPULimit
|
||||
if cpuLimit == 0 {
|
||||
cpuLimit = s.config.MaxCPU
|
||||
}
|
||||
if cpuLimit > 0 {
|
||||
args = append(args, "--cpus", fmt.Sprintf("%.2f", cpuLimit))
|
||||
}
|
||||
|
||||
// Network isolation
|
||||
if !config.AllowNetwork {
|
||||
args = append(args, "--network", "none")
|
||||
}
|
||||
|
||||
// Security: disable privileged mode and limit PIDs
|
||||
args = append(args, "--pids-limit", "100")
|
||||
args = append(args, "--security-opt", "no-new-privileges")
|
||||
|
||||
// Mount the script and working directory as read-only
|
||||
scriptDir := filepath.Dir(config.Script)
|
||||
args = append(args, "-v", fmt.Sprintf("%s:/workspace:ro", scriptDir))
|
||||
|
||||
// Working directory
|
||||
args = append(args, "-w", "/workspace")
|
||||
|
||||
// Environment variables
|
||||
for key, value := range config.Env {
|
||||
args = append(args, "-e", fmt.Sprintf("%s=%s", key, value))
|
||||
}
|
||||
|
||||
// Image
|
||||
args = append(args, s.config.DockerImage)
|
||||
|
||||
// Script execution command
|
||||
scriptName := filepath.Base(config.Script)
|
||||
interpreter := getInterpreter(scriptName)
|
||||
|
||||
args = append(args, interpreter, scriptName)
|
||||
args = append(args, config.Args...)
|
||||
|
||||
return args
|
||||
}
|
||||
|
||||
// getInterpreter returns the appropriate interpreter for a script
|
||||
func getInterpreter(scriptName string) string {
|
||||
ext := strings.ToLower(filepath.Ext(scriptName))
|
||||
switch ext {
|
||||
case ".py":
|
||||
return "python3"
|
||||
case ".sh", ".bash":
|
||||
return "bash"
|
||||
case ".js":
|
||||
return "node"
|
||||
case ".rb":
|
||||
return "ruby"
|
||||
case ".pl":
|
||||
return "perl"
|
||||
default:
|
||||
return "sh"
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup removes any lingering resources
|
||||
func (s *DockerSandbox) Cleanup(ctx context.Context) error {
|
||||
// Docker --rm flag should handle container cleanup
|
||||
// This is here for any additional cleanup if needed
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LocalSandbox implements the Sandbox interface using local process isolation
|
||||
// This is a fallback option when Docker is not available
|
||||
// It provides basic isolation through:
|
||||
// - Command whitelist validation
|
||||
// - Working directory restriction
|
||||
// - Timeout enforcement
|
||||
// - Environment variable filtering
|
||||
type LocalSandbox struct {
|
||||
config *Config
|
||||
}
|
||||
|
||||
// NewLocalSandbox creates a new local process-based sandbox
|
||||
func NewLocalSandbox(config *Config) *LocalSandbox {
|
||||
if config == nil {
|
||||
config = DefaultConfig()
|
||||
}
|
||||
return &LocalSandbox{
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// Type returns the sandbox type
|
||||
func (s *LocalSandbox) Type() SandboxType {
|
||||
return SandboxTypeLocal
|
||||
}
|
||||
|
||||
// IsAvailable checks if local sandbox is available
|
||||
func (s *LocalSandbox) IsAvailable(ctx context.Context) bool {
|
||||
// Local sandbox is always available
|
||||
return true
|
||||
}
|
||||
|
||||
// Execute runs a script locally with basic isolation
|
||||
func (s *LocalSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {
|
||||
if config == nil {
|
||||
return nil, ErrInvalidScript
|
||||
}
|
||||
|
||||
// Validate the script path
|
||||
if err := s.validateScript(config.Script); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Determine interpreter
|
||||
interpreter := s.getInterpreter(config.Script)
|
||||
if !s.isAllowedCommand(interpreter) {
|
||||
return nil, fmt.Errorf("interpreter not allowed: %s", interpreter)
|
||||
}
|
||||
|
||||
// Set default timeout
|
||||
timeout := config.Timeout
|
||||
if timeout == 0 {
|
||||
timeout = s.config.DefaultTimeout
|
||||
}
|
||||
if timeout == 0 {
|
||||
timeout = DefaultTimeout
|
||||
}
|
||||
|
||||
// Create context with timeout
|
||||
execCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
// Build command
|
||||
args := append([]string{config.Script}, config.Args...)
|
||||
cmd := exec.CommandContext(execCtx, interpreter, args...)
|
||||
|
||||
// Set working directory
|
||||
if config.WorkDir != "" {
|
||||
cmd.Dir = config.WorkDir
|
||||
} else {
|
||||
cmd.Dir = filepath.Dir(config.Script)
|
||||
}
|
||||
|
||||
// Setup minimal environment
|
||||
cmd.Env = s.buildEnvironment(config.Env)
|
||||
|
||||
// Setup process group for cleanup
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
Setpgid: true,
|
||||
}
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
if config.Stdin != "" {
|
||||
cmd.Stdin = strings.NewReader(config.Stdin)
|
||||
}
|
||||
|
||||
startTime := time.Now()
|
||||
err := cmd.Run()
|
||||
duration := time.Since(startTime)
|
||||
|
||||
result := &ExecuteResult{
|
||||
Stdout: stdout.String(),
|
||||
Stderr: stderr.String(),
|
||||
Duration: duration,
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if execCtx.Err() == context.DeadlineExceeded {
|
||||
// Kill the process group
|
||||
if cmd.Process != nil {
|
||||
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
result.Killed = true
|
||||
result.Error = ErrTimeout.Error()
|
||||
result.ExitCode = -1
|
||||
} else if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
result.ExitCode = exitErr.ExitCode()
|
||||
} else {
|
||||
result.Error = err.Error()
|
||||
result.ExitCode = -1
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// validateScript checks if the script path is valid and safe
|
||||
func (s *LocalSandbox) validateScript(scriptPath string) error {
|
||||
// Check if script exists
|
||||
info, err := os.Stat(scriptPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return ErrScriptNotFound
|
||||
}
|
||||
return fmt.Errorf("failed to access script: %w", err)
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
return ErrInvalidScript
|
||||
}
|
||||
|
||||
// Check path is absolute
|
||||
if !filepath.IsAbs(scriptPath) {
|
||||
return fmt.Errorf("script path must be absolute: %s", scriptPath)
|
||||
}
|
||||
|
||||
// Validate against allowed paths if configured
|
||||
if len(s.config.AllowedPaths) > 0 {
|
||||
allowed := false
|
||||
absPath, _ := filepath.Abs(scriptPath)
|
||||
for _, allowedPath := range s.config.AllowedPaths {
|
||||
absAllowed, _ := filepath.Abs(allowedPath)
|
||||
if strings.HasPrefix(absPath, absAllowed) {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return fmt.Errorf("script path not in allowed paths: %s", scriptPath)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getInterpreter returns the appropriate interpreter for a script
|
||||
func (s *LocalSandbox) getInterpreter(scriptPath string) string {
|
||||
ext := strings.ToLower(filepath.Ext(scriptPath))
|
||||
switch ext {
|
||||
case ".py":
|
||||
return "python3"
|
||||
case ".sh", ".bash":
|
||||
return "bash"
|
||||
case ".js":
|
||||
return "node"
|
||||
case ".rb":
|
||||
return "ruby"
|
||||
case ".pl":
|
||||
return "perl"
|
||||
case ".php":
|
||||
return "php"
|
||||
default:
|
||||
return "sh"
|
||||
}
|
||||
}
|
||||
|
||||
// isAllowedCommand checks if a command is in the allowed list
|
||||
func (s *LocalSandbox) isAllowedCommand(cmd string) bool {
|
||||
if len(s.config.AllowedCommands) == 0 {
|
||||
// Use default allowed commands
|
||||
defaults := defaultAllowedCommands()
|
||||
for _, allowed := range defaults {
|
||||
if cmd == allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
for _, allowed := range s.config.AllowedCommands {
|
||||
if cmd == allowed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// buildEnvironment creates a safe environment for script execution
|
||||
func (s *LocalSandbox) buildEnvironment(extra map[string]string) []string {
|
||||
// Start with minimal environment
|
||||
env := []string{
|
||||
"PATH=/usr/local/bin:/usr/bin:/bin",
|
||||
"HOME=/tmp",
|
||||
"LANG=en_US.UTF-8",
|
||||
"LC_ALL=en_US.UTF-8",
|
||||
}
|
||||
|
||||
// Dangerous environment variables to exclude
|
||||
dangerous := map[string]bool{
|
||||
"LD_PRELOAD": true,
|
||||
"LD_LIBRARY_PATH": true,
|
||||
"PYTHONPATH": true,
|
||||
"NODE_OPTIONS": true,
|
||||
"BASH_ENV": true,
|
||||
"ENV": true,
|
||||
"SHELL": true,
|
||||
}
|
||||
|
||||
// Add extra environment variables (filtered)
|
||||
for key, value := range extra {
|
||||
upperKey := strings.ToUpper(key)
|
||||
if dangerous[upperKey] {
|
||||
continue
|
||||
}
|
||||
env = append(env, fmt.Sprintf("%s=%s", key, value))
|
||||
}
|
||||
|
||||
return env
|
||||
}
|
||||
|
||||
// Cleanup releases any resources
|
||||
func (s *LocalSandbox) Cleanup(ctx context.Context) error {
|
||||
// Local sandbox doesn't need cleanup
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// DefaultManager implements the Manager interface
|
||||
// It handles sandbox selection and fallback logic
|
||||
type DefaultManager struct {
|
||||
config *Config
|
||||
sandbox Sandbox
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewManager creates a new sandbox manager with the given configuration
|
||||
func NewManager(config *Config) (Manager, error) {
|
||||
if config == nil {
|
||||
config = DefaultConfig()
|
||||
}
|
||||
|
||||
if err := ValidateConfig(config); err != nil {
|
||||
return nil, fmt.Errorf("invalid sandbox config: %w", err)
|
||||
}
|
||||
|
||||
manager := &DefaultManager{
|
||||
config: config,
|
||||
}
|
||||
|
||||
// Initialize the appropriate sandbox
|
||||
if err := manager.initializeSandbox(context.Background()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return manager, nil
|
||||
}
|
||||
|
||||
// initializeSandbox creates and configures the sandbox based on configuration
|
||||
func (m *DefaultManager) initializeSandbox(ctx context.Context) error {
|
||||
switch m.config.Type {
|
||||
case SandboxTypeDisabled:
|
||||
m.sandbox = &disabledSandbox{}
|
||||
return nil
|
||||
|
||||
case SandboxTypeDocker:
|
||||
dockerSandbox := NewDockerSandbox(m.config)
|
||||
if dockerSandbox.IsAvailable(ctx) {
|
||||
m.sandbox = dockerSandbox
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fallback to local if enabled
|
||||
if m.config.FallbackEnabled {
|
||||
m.sandbox = NewLocalSandbox(m.config)
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("docker is not available and fallback is disabled")
|
||||
|
||||
case SandboxTypeLocal:
|
||||
m.sandbox = NewLocalSandbox(m.config)
|
||||
return nil
|
||||
|
||||
default:
|
||||
return fmt.Errorf("unknown sandbox type: %s", m.config.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// Execute runs a script using the configured sandbox
|
||||
func (m *DefaultManager) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {
|
||||
m.mu.RLock()
|
||||
sandbox := m.sandbox
|
||||
m.mu.RUnlock()
|
||||
|
||||
if sandbox == nil {
|
||||
return nil, ErrSandboxDisabled
|
||||
}
|
||||
|
||||
return sandbox.Execute(ctx, config)
|
||||
}
|
||||
|
||||
// Cleanup releases all sandbox resources
|
||||
func (m *DefaultManager) Cleanup(ctx context.Context) error {
|
||||
m.mu.RLock()
|
||||
sandbox := m.sandbox
|
||||
m.mu.RUnlock()
|
||||
|
||||
if sandbox != nil {
|
||||
return sandbox.Cleanup(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSandbox returns the active sandbox
|
||||
func (m *DefaultManager) GetSandbox() Sandbox {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return m.sandbox
|
||||
}
|
||||
|
||||
// GetType returns the current sandbox type
|
||||
func (m *DefaultManager) GetType() SandboxType {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
if m.sandbox != nil {
|
||||
return m.sandbox.Type()
|
||||
}
|
||||
return SandboxTypeDisabled
|
||||
}
|
||||
|
||||
// disabledSandbox is a no-op sandbox that rejects all execution requests
|
||||
type disabledSandbox struct{}
|
||||
|
||||
func (s *disabledSandbox) Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error) {
|
||||
return nil, ErrSandboxDisabled
|
||||
}
|
||||
|
||||
func (s *disabledSandbox) Cleanup(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *disabledSandbox) Type() SandboxType {
|
||||
return SandboxTypeDisabled
|
||||
}
|
||||
|
||||
func (s *disabledSandbox) IsAvailable(ctx context.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// NewManagerFromType creates a sandbox manager with the specified type
|
||||
func NewManagerFromType(sandboxType string, fallbackEnabled bool) (Manager, error) {
|
||||
var sType SandboxType
|
||||
switch sandboxType {
|
||||
case "docker":
|
||||
sType = SandboxTypeDocker
|
||||
case "local":
|
||||
sType = SandboxTypeLocal
|
||||
case "disabled", "":
|
||||
sType = SandboxTypeDisabled
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown sandbox type: %s", sandboxType)
|
||||
}
|
||||
|
||||
config := DefaultConfig()
|
||||
config.Type = sType
|
||||
config.FallbackEnabled = fallbackEnabled
|
||||
|
||||
return NewManager(config)
|
||||
}
|
||||
|
||||
// NewDisabledManager creates a manager that rejects all execution requests
|
||||
func NewDisabledManager() Manager {
|
||||
return &DefaultManager{
|
||||
config: DefaultConfig(),
|
||||
sandbox: &disabledSandbox{},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// Package sandbox provides isolated execution environments for running untrusted scripts.
|
||||
// It supports multiple backends including Docker containers and local process isolation.
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SandboxType represents the type of sandbox environment
|
||||
type SandboxType string
|
||||
|
||||
const (
|
||||
// SandboxTypeDocker uses Docker containers for isolation
|
||||
SandboxTypeDocker SandboxType = "docker"
|
||||
// SandboxTypeLocal uses local process with restrictions
|
||||
SandboxTypeLocal SandboxType = "local"
|
||||
// SandboxTypeDisabled means script execution is disabled
|
||||
SandboxTypeDisabled SandboxType = "disabled"
|
||||
)
|
||||
|
||||
// Default configuration values
|
||||
const (
|
||||
DefaultTimeout = 60 * time.Second
|
||||
DefaultMemoryLimit = 256 * 1024 * 1024 // 256MB
|
||||
DefaultCPULimit = 1.0 // 1 CPU core
|
||||
)
|
||||
|
||||
// Common errors
|
||||
var (
|
||||
ErrSandboxDisabled = errors.New("sandbox is disabled")
|
||||
ErrTimeout = errors.New("execution timed out")
|
||||
ErrScriptNotFound = errors.New("script not found")
|
||||
ErrInvalidScript = errors.New("invalid script")
|
||||
ErrExecutionFailed = errors.New("script execution failed")
|
||||
)
|
||||
|
||||
// Sandbox defines the interface for isolated script execution
|
||||
type Sandbox interface {
|
||||
// Execute runs a script in an isolated environment
|
||||
Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error)
|
||||
|
||||
// Cleanup releases sandbox resources
|
||||
Cleanup(ctx context.Context) error
|
||||
|
||||
// Type returns the sandbox type
|
||||
Type() SandboxType
|
||||
|
||||
// IsAvailable checks if the sandbox is available for use
|
||||
IsAvailable(ctx context.Context) bool
|
||||
}
|
||||
|
||||
// Manager provides a unified interface for sandbox operations
|
||||
// It handles sandbox selection and fallback logic
|
||||
type Manager interface {
|
||||
// Execute runs a script using the configured sandbox
|
||||
Execute(ctx context.Context, config *ExecuteConfig) (*ExecuteResult, error)
|
||||
|
||||
// Cleanup releases all sandbox resources
|
||||
Cleanup(ctx context.Context) error
|
||||
|
||||
// GetSandbox returns the active sandbox
|
||||
GetSandbox() Sandbox
|
||||
|
||||
// GetType returns the current sandbox type
|
||||
GetType() SandboxType
|
||||
}
|
||||
|
||||
// ExecuteConfig contains configuration for script execution
|
||||
type ExecuteConfig struct {
|
||||
// Script is the absolute path to the script file
|
||||
Script string
|
||||
|
||||
// Args are command-line arguments to pass to the script
|
||||
Args []string
|
||||
|
||||
// WorkDir is the working directory for script execution
|
||||
WorkDir string
|
||||
|
||||
// Timeout is the maximum execution time (0 = use default)
|
||||
Timeout time.Duration
|
||||
|
||||
// Env is additional environment variables
|
||||
Env map[string]string
|
||||
|
||||
// AllowedCmds is a whitelist of commands that can be executed
|
||||
// If empty, a default safe list is used
|
||||
AllowedCmds []string
|
||||
|
||||
// AllowNetwork enables network access (Docker only)
|
||||
AllowNetwork bool
|
||||
|
||||
// MemoryLimit is the maximum memory in bytes (Docker only)
|
||||
MemoryLimit int64
|
||||
|
||||
// CPULimit is the maximum CPU cores (Docker only)
|
||||
CPULimit float64
|
||||
|
||||
// ReadOnlyRootfs makes the root filesystem read-only (Docker only)
|
||||
ReadOnlyRootfs bool
|
||||
|
||||
// Stdin provides input to the script
|
||||
Stdin string
|
||||
}
|
||||
|
||||
// ExecuteResult contains the result of script execution
|
||||
type ExecuteResult struct {
|
||||
// Stdout is the standard output from the script
|
||||
Stdout string
|
||||
|
||||
// Stderr is the standard error from the script
|
||||
Stderr string
|
||||
|
||||
// ExitCode is the process exit code
|
||||
ExitCode int
|
||||
|
||||
// Duration is the actual execution time
|
||||
Duration time.Duration
|
||||
|
||||
// Killed indicates if the process was killed (e.g., timeout)
|
||||
Killed bool
|
||||
|
||||
// Error contains any execution error
|
||||
Error string
|
||||
}
|
||||
|
||||
// IsSuccess returns true if the script executed successfully
|
||||
func (r *ExecuteResult) IsSuccess() bool {
|
||||
return r.ExitCode == 0 && !r.Killed && r.Error == ""
|
||||
}
|
||||
|
||||
// GetOutput returns the combined stdout and stderr, preferring stdout
|
||||
func (r *ExecuteResult) GetOutput() string {
|
||||
if r.Stdout != "" {
|
||||
return r.Stdout
|
||||
}
|
||||
return r.Stderr
|
||||
}
|
||||
|
||||
// Config holds sandbox manager configuration
|
||||
type Config struct {
|
||||
// Type is the preferred sandbox type
|
||||
Type SandboxType
|
||||
|
||||
// FallbackEnabled allows falling back to local sandbox if Docker is unavailable
|
||||
FallbackEnabled bool
|
||||
|
||||
// DefaultTimeout is the default execution timeout
|
||||
DefaultTimeout time.Duration
|
||||
|
||||
// DockerImage is the Docker image to use (Docker sandbox only)
|
||||
DockerImage string
|
||||
|
||||
// AllowedCommands is the default list of allowed commands
|
||||
AllowedCommands []string
|
||||
|
||||
// AllowedPaths is the list of paths that can be accessed
|
||||
AllowedPaths []string
|
||||
|
||||
// MaxMemory is the maximum memory limit in bytes
|
||||
MaxMemory int64
|
||||
|
||||
// MaxCPU is the maximum CPU cores
|
||||
MaxCPU float64
|
||||
}
|
||||
|
||||
// DefaultConfig returns a default sandbox configuration
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
Type: SandboxTypeLocal,
|
||||
FallbackEnabled: true,
|
||||
DefaultTimeout: DefaultTimeout,
|
||||
DockerImage: "python:3.11-slim",
|
||||
AllowedCommands: defaultAllowedCommands(),
|
||||
MaxMemory: DefaultMemoryLimit,
|
||||
MaxCPU: DefaultCPULimit,
|
||||
}
|
||||
}
|
||||
|
||||
// defaultAllowedCommands returns the default list of safe commands
|
||||
func defaultAllowedCommands() []string {
|
||||
return []string{
|
||||
"python",
|
||||
"python3",
|
||||
"node",
|
||||
"bash",
|
||||
"sh",
|
||||
"cat",
|
||||
"echo",
|
||||
"head",
|
||||
"tail",
|
||||
"grep",
|
||||
"sed",
|
||||
"awk",
|
||||
"sort",
|
||||
"uniq",
|
||||
"wc",
|
||||
"cut",
|
||||
"tr",
|
||||
"ls",
|
||||
"pwd",
|
||||
"date",
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateConfig validates sandbox configuration
|
||||
func ValidateConfig(config *Config) error {
|
||||
if config == nil {
|
||||
return errors.New("config is nil")
|
||||
}
|
||||
|
||||
switch config.Type {
|
||||
case SandboxTypeDocker, SandboxTypeLocal, SandboxTypeDisabled:
|
||||
// Valid types
|
||||
default:
|
||||
return errors.New("invalid sandbox type")
|
||||
}
|
||||
|
||||
if config.DefaultTimeout < 0 {
|
||||
return errors.New("timeout cannot be negative")
|
||||
}
|
||||
|
||||
if config.MaxMemory < 0 {
|
||||
return errors.New("memory limit cannot be negative")
|
||||
}
|
||||
|
||||
if config.MaxCPU < 0 {
|
||||
return errors.New("CPU limit cannot be negative")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDefaultConfig(t *testing.T) {
|
||||
config := DefaultConfig()
|
||||
|
||||
if config.Type != SandboxTypeLocal {
|
||||
t.Errorf("Expected default type to be local, got %s", config.Type)
|
||||
}
|
||||
|
||||
if config.DefaultTimeout != DefaultTimeout {
|
||||
t.Errorf("Expected default timeout %v, got %v", DefaultTimeout, config.DefaultTimeout)
|
||||
}
|
||||
|
||||
if !config.FallbackEnabled {
|
||||
t.Error("Expected fallback to be enabled by default")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
config *Config
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "nil config",
|
||||
config: nil,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "valid config",
|
||||
config: &Config{
|
||||
Type: SandboxTypeLocal,
|
||||
DefaultTimeout: 30 * time.Second,
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
{
|
||||
name: "invalid type",
|
||||
config: &Config{
|
||||
Type: "invalid",
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "negative timeout",
|
||||
config: &Config{
|
||||
Type: SandboxTypeLocal,
|
||||
DefaultTimeout: -1 * time.Second,
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ValidateConfig(tt.config)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("ValidateConfig() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalSandboxExecute(t *testing.T) {
|
||||
// Create a temporary script
|
||||
tmpDir, err := os.MkdirTemp("", "sandbox-test")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
// Write a simple test script
|
||||
scriptPath := filepath.Join(tmpDir, "test.sh")
|
||||
scriptContent := `#!/bin/bash
|
||||
echo "Hello from sandbox"
|
||||
echo "Args: $@"
|
||||
`
|
||||
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {
|
||||
t.Fatalf("Failed to write script: %v", err)
|
||||
}
|
||||
|
||||
// Create local sandbox
|
||||
config := DefaultConfig()
|
||||
config.Type = SandboxTypeLocal
|
||||
sandbox := NewLocalSandbox(config)
|
||||
|
||||
// Check availability
|
||||
ctx := context.Background()
|
||||
if !sandbox.IsAvailable(ctx) {
|
||||
t.Error("Local sandbox should always be available")
|
||||
}
|
||||
|
||||
// Execute script
|
||||
result, err := sandbox.Execute(ctx, &ExecuteConfig{
|
||||
Script: scriptPath,
|
||||
Args: []string{"arg1", "arg2"},
|
||||
Timeout: 10 * time.Second,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to execute script: %v", err)
|
||||
}
|
||||
|
||||
if result.ExitCode != 0 {
|
||||
t.Errorf("Expected exit code 0, got %d", result.ExitCode)
|
||||
}
|
||||
|
||||
if result.Stdout == "" {
|
||||
t.Error("Expected stdout to be non-empty")
|
||||
}
|
||||
|
||||
t.Logf("Script output: %s", result.Stdout)
|
||||
t.Logf("Duration: %v", result.Duration)
|
||||
}
|
||||
|
||||
func TestLocalSandboxTimeout(t *testing.T) {
|
||||
// Create a temporary script that sleeps
|
||||
tmpDir, err := os.MkdirTemp("", "sandbox-test")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
// Write a script that sleeps
|
||||
scriptPath := filepath.Join(tmpDir, "sleep.sh")
|
||||
scriptContent := `#!/bin/bash
|
||||
sleep 10
|
||||
echo "Done"
|
||||
`
|
||||
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {
|
||||
t.Fatalf("Failed to write script: %v", err)
|
||||
}
|
||||
|
||||
// Create local sandbox
|
||||
config := DefaultConfig()
|
||||
config.Type = SandboxTypeLocal
|
||||
sandbox := NewLocalSandbox(config)
|
||||
|
||||
// Execute with short timeout
|
||||
ctx := context.Background()
|
||||
result, err := sandbox.Execute(ctx, &ExecuteConfig{
|
||||
Script: scriptPath,
|
||||
Timeout: 1 * time.Second,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Execute should not return error, got: %v", err)
|
||||
}
|
||||
|
||||
if !result.Killed {
|
||||
t.Error("Expected script to be killed due to timeout")
|
||||
}
|
||||
|
||||
t.Logf("Script was killed: %v, Duration: %v", result.Killed, result.Duration)
|
||||
}
|
||||
|
||||
func TestNewManager(t *testing.T) {
|
||||
config := DefaultConfig()
|
||||
config.Type = SandboxTypeLocal
|
||||
|
||||
manager, err := NewManager(config)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create manager: %v", err)
|
||||
}
|
||||
|
||||
if manager.GetType() != SandboxTypeLocal {
|
||||
t.Errorf("Expected type local, got %s", manager.GetType())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDisabledManager(t *testing.T) {
|
||||
manager := NewDisabledManager()
|
||||
|
||||
if manager.GetType() != SandboxTypeDisabled {
|
||||
t.Errorf("Expected type disabled, got %s", manager.GetType())
|
||||
}
|
||||
|
||||
// Execute should fail
|
||||
ctx := context.Background()
|
||||
_, err := manager.Execute(ctx, &ExecuteConfig{
|
||||
Script: "/some/script.sh",
|
||||
})
|
||||
|
||||
if err != ErrSandboxDisabled {
|
||||
t.Errorf("Expected ErrSandboxDisabled, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteResultHelpers(t *testing.T) {
|
||||
// Test IsSuccess
|
||||
successResult := &ExecuteResult{
|
||||
ExitCode: 0,
|
||||
Stdout: "output",
|
||||
}
|
||||
if !successResult.IsSuccess() {
|
||||
t.Error("Expected IsSuccess() to return true for exit code 0")
|
||||
}
|
||||
|
||||
failResult := &ExecuteResult{
|
||||
ExitCode: 1,
|
||||
Stderr: "error",
|
||||
}
|
||||
if failResult.IsSuccess() {
|
||||
t.Error("Expected IsSuccess() to return false for exit code 1")
|
||||
}
|
||||
|
||||
killedResult := &ExecuteResult{
|
||||
ExitCode: 0,
|
||||
Killed: true,
|
||||
}
|
||||
if killedResult.IsSuccess() {
|
||||
t.Error("Expected IsSuccess() to return false when killed")
|
||||
}
|
||||
|
||||
// Test GetOutput
|
||||
if successResult.GetOutput() != "output" {
|
||||
t.Errorf("Expected GetOutput() to return stdout, got %s", successResult.GetOutput())
|
||||
}
|
||||
|
||||
if failResult.GetOutput() != "error" {
|
||||
t.Errorf("Expected GetOutput() to return stderr when stdout is empty, got %s", failResult.GetOutput())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPythonScriptExecution(t *testing.T) {
|
||||
// Create a temporary Python script
|
||||
tmpDir, err := os.MkdirTemp("", "sandbox-test")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
// Write a Python script
|
||||
scriptPath := filepath.Join(tmpDir, "test.py")
|
||||
scriptContent := `#!/usr/bin/env python3
|
||||
import sys
|
||||
print("Hello from Python")
|
||||
print(f"Arguments: {sys.argv[1:]}")
|
||||
`
|
||||
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {
|
||||
t.Fatalf("Failed to write script: %v", err)
|
||||
}
|
||||
|
||||
// Create local sandbox
|
||||
config := DefaultConfig()
|
||||
config.Type = SandboxTypeLocal
|
||||
sandbox := NewLocalSandbox(config)
|
||||
|
||||
// Execute Python script
|
||||
ctx := context.Background()
|
||||
result, err := sandbox.Execute(ctx, &ExecuteConfig{
|
||||
Script: scriptPath,
|
||||
Args: []string{"test", "args"},
|
||||
Timeout: 10 * time.Second,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to execute Python script: %v", err)
|
||||
}
|
||||
|
||||
if result.ExitCode != 0 {
|
||||
t.Errorf("Expected exit code 0, got %d. Stderr: %s", result.ExitCode, result.Stderr)
|
||||
}
|
||||
|
||||
t.Logf("Python script output: %s", result.Stdout)
|
||||
}
|
||||
Reference in New Issue
Block a user