sandbox

package
v0.0.0-...-8acab51 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package sandbox provides a sandboxed execution environment for untrusted code.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrExecutionTimeout is returned when execution times out.
	ErrExecutionTimeout = errors.New("execution timeout")
	// ErrExecutionKilled is returned when execution is killed.
	ErrExecutionKilled = errors.New("execution killed")
	// ErrResourceLimitExceeded is returned when resource limits are exceeded.
	ErrResourceLimitExceeded = errors.New("resource limit exceeded")
	// ErrSandboxNotSupported is returned when sandboxing is not supported on the platform.
	ErrSandboxNotSupported = errors.New("sandbox not supported on this platform")
	// ErrExecutionNotFound is returned when an execution is not found.
	ErrExecutionNotFound = errors.New("execution not found")
)

Functions

This section is empty.

Types

type BaseExecutor

type BaseExecutor struct {
	// contains filtered or unexported fields
}

BaseExecutor provides common functionality for all executors.

func NewBaseExecutor

func NewBaseExecutor(config *Config) *BaseExecutor

NewBaseExecutor creates a new base executor.

func (*BaseExecutor) Cleanup

func (e *BaseExecutor) Cleanup() error

Cleanup cleans up resources.

func (*BaseExecutor) Execute

Execute executes a command with basic isolation.

func (*BaseExecutor) GetStatus

func (e *BaseExecutor) GetStatus(id string) (*ExecutionResult, error)

GetStatus returns the status of an execution.

func (*BaseExecutor) IsSupported

func (e *BaseExecutor) IsSupported() bool

IsSupported returns true (base executor is always supported).

func (*BaseExecutor) Kill

func (e *BaseExecutor) Kill(id string) error

Kill kills a running execution.

type CodexBinaryManager

type CodexBinaryManager struct {
	// contains filtered or unexported fields
}

CodexBinaryManager resolves or downloads the Windows Codex binary Blue uses for the strong sandbox tier.

func NewCodexBinaryManager

func NewCodexBinaryManager(config *Config, options CodexBinaryManagerOptions) *CodexBinaryManager

func (*CodexBinaryManager) AutoDownloadEnabled

func (m *CodexBinaryManager) AutoDownloadEnabled() bool

func (*CodexBinaryManager) Download

func (m *CodexBinaryManager) Download(ctx context.Context) (string, error)

func (*CodexBinaryManager) DownloadTimeout

func (m *CodexBinaryManager) DownloadTimeout() time.Duration

func (*CodexBinaryManager) Ensure

func (m *CodexBinaryManager) Ensure(ctx context.Context) (string, error)

func (*CodexBinaryManager) ReadyPath

func (m *CodexBinaryManager) ReadyPath() (string, bool, error)

type CodexBinaryManagerOptions

type CodexBinaryManagerOptions struct {
	HTTPClient      *http.Client
	LookPath        func(string) (string, error)
	UserCacheDir    func() (string, error)
	GOOS            string
	GOARCH          string
	DownloadSources []string
}

CodexBinaryManagerOptions allows test-time injection for managed Codex binary resolution and download.

type CodexSandboxExecutor

type CodexSandboxExecutor struct {
	*BaseExecutor
	// contains filtered or unexported fields
}

CodexSandboxExecutor wraps the local Codex CLI sandbox subcommands.

func NewCodexSandboxExecutor

func NewCodexSandboxExecutor(config *Config, options CodexSandboxExecutorOptions) (*CodexSandboxExecutor, error)

NewCodexSandboxExecutor creates a Codex-backed sandbox executor.

func (*CodexSandboxExecutor) Execute

Execute executes a command under the requested Codex sandbox subcommand.

func (*CodexSandboxExecutor) IsSupported

func (e *CodexSandboxExecutor) IsSupported() bool

IsSupported reports whether the Codex sandbox probe succeeded.

func (*CodexSandboxExecutor) SupportReason

func (e *CodexSandboxExecutor) SupportReason() string

SupportReason returns the cached unavailability reason.

func (*CodexSandboxExecutor) SupportsNetworkEnabled

func (e *CodexSandboxExecutor) SupportsNetworkEnabled() bool

SupportsNetworkEnabled reports whether the executor can honor Blue's unified network toggle. The current Codex integration is intentionally conservative.

type CodexSandboxExecutorOptions

type CodexSandboxExecutorOptions struct {
	Binary         string
	BinaryResolver codexBinaryResolver
	Subcommand     string
	ProbeTimeout   time.Duration
	LookPath       func(file string) (string, error)
	CommandContext func(ctx context.Context, name string, args ...string) *exec.Cmd
}

CodexSandboxExecutorOptions controls how a Codex-backed sandbox executor is created.

type Config

type Config struct {
	// DefaultTimeout is the default execution timeout.
	DefaultTimeout time.Duration
	// MaxTimeout is the maximum allowed timeout.
	MaxTimeout time.Duration
	// MemoryLimit is the memory limit in bytes.
	MemoryLimit int64
	// CPULimit is the CPU limit (1.0 = 1 core).
	CPULimit float64
	// ProcessLimit is the maximum number of processes.
	ProcessLimit int
	// NetworkEnabled allows network access.
	NetworkEnabled bool
	// LinuxLXCExecutable is the LXC CLI used for Linux strong isolation.
	LinuxLXCExecutable string
	// LinuxLXCInstance is the LXC instance name used for Linux strong isolation.
	LinuxLXCInstance string
	// WindowsCodexExecutable is the Codex CLI used for Windows strong isolation.
	WindowsCodexExecutable string
	// WindowsCodexAutoDownload controls whether Blue downloads a managed Codex
	// binary when no local executable is ready.
	WindowsCodexAutoDownload bool
	// WindowsCodexDownloadTimeout bounds background Windows Codex downloads.
	WindowsCodexDownloadTimeout time.Duration
	// WorkDir is the working directory for executions.
	WorkDir string
	// AllowedPaths are paths that can be accessed.
	AllowedPaths []string
	// DeniedPaths are paths that cannot be accessed.
	DeniedPaths []string

	// macOS Hypervisor.framework specific options
	// DarwinExecutorMode specifies which executor to use on macOS.
	// Valid values: "auto", "hypervisor", "sandbox-exec"
	// Default: "auto" (automatically selects the best available option)
	DarwinExecutorMode string
	// HypervisorVMImagePath is the path to the VM disk image for Hypervisor mode.
	HypervisorVMImagePath string
	// HypervisorMemoryMB is the VM memory in megabytes for Hypervisor mode.
	HypervisorMemoryMB int
	// HypervisorCPUCount is the number of virtual CPUs for Hypervisor mode.
	HypervisorCPUCount int
}

Config holds sandbox configuration.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default sandbox configuration.

type ExecuteRequest

type ExecuteRequest struct {
	Command     string            `json:"command" validate:"required"`
	Args        []string          `json:"args,omitempty"`
	Env         map[string]string `json:"env,omitempty"`
	WorkDir     string            `json:"work_dir,omitempty"`
	Stdin       string            `json:"stdin,omitempty"`
	TimeoutSecs int               `json:"timeout_secs,omitempty"`
	MemoryMB    int               `json:"memory_mb,omitempty"`
}

ExecuteRequest represents a request to execute code in the sandbox.

type ExecutionRequest

type ExecutionRequest struct {
	// ID is the unique execution identifier.
	ID string
	// Tier selects the sandbox isolation tier. Empty defaults to light.
	Tier Tier
	// Command is the command to execute.
	Command string
	// Args are the command arguments.
	Args []string
	// Env are environment variables.
	Env map[string]string
	// WorkDir is the working directory.
	WorkDir string
	// Timeout is the execution timeout.
	Timeout time.Duration
	// Stdin is the standard input.
	Stdin string
	// MemoryLimit overrides the default memory limit.
	MemoryLimit int64
	// CPULimit overrides the default CPU limit.
	CPULimit float64
}

ExecutionRequest represents a request to execute code in the sandbox.

func NewExecutionRequest

func NewExecutionRequest(command string, args ...string) *ExecutionRequest

NewExecutionRequest creates a new execution request.

type ExecutionResult

type ExecutionResult struct {
	// ID is the execution identifier.
	ID string `json:"id"`
	// Status is the execution status.
	Status ExecutionStatus `json:"status"`
	// ExitCode is the process exit code.
	ExitCode int `json:"exit_code"`
	// Stdout is the standard output.
	Stdout string `json:"stdout"`
	// Stderr is the standard error.
	Stderr string `json:"stderr"`
	// StartTime is when the execution started.
	StartTime time.Time `json:"start_time"`
	// EndTime is when the execution ended.
	EndTime time.Time `json:"end_time"`
	// Duration is the execution duration.
	Duration time.Duration `json:"duration"`
	// ResourceUsage contains resource usage statistics.
	ResourceUsage *ResourceUsage `json:"resource_usage,omitempty"`
	// Error contains any error message.
	Error string `json:"error,omitempty"`
}

ExecutionResult represents the result of an execution.

type ExecutionStatus

type ExecutionStatus string

ExecutionStatus represents the status of an execution.

const (
	// StatusPending indicates the execution is pending.
	StatusPending ExecutionStatus = "pending"
	// StatusRunning indicates the execution is running.
	StatusRunning ExecutionStatus = "running"
	// StatusCompleted indicates the execution completed successfully.
	StatusCompleted ExecutionStatus = "completed"
	// StatusFailed indicates the execution failed.
	StatusFailed ExecutionStatus = "failed"
	// StatusTimeout indicates the execution timed out.
	StatusTimeout ExecutionStatus = "timeout"
	// StatusKilled indicates the execution was killed.
	StatusKilled ExecutionStatus = "killed"
)

type Executor

type Executor interface {
	// Execute executes a command in the sandbox.
	Execute(ctx context.Context, req *ExecutionRequest) (*ExecutionResult, error)
	// GetStatus returns the status of an execution.
	GetStatus(id string) (*ExecutionResult, error)
	// Kill kills a running execution.
	Kill(id string) error
	// Cleanup cleans up resources.
	Cleanup() error
	// IsSupported returns true if the executor is supported on this platform.
	IsSupported() bool
}

Executor is the interface for sandbox executors.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler handles sandbox API endpoints.

func NewHandler

func NewHandler(manager *Manager) *Handler

NewHandler creates a new sandbox handler.

func (*Handler) Execute

func (h *Handler) Execute(c echo.Context) error

Execute handles POST /api/v1/sandbox/execute

func (*Handler) GetStatus

func (h *Handler) GetStatus(c echo.Context) error

GetStatus handles GET /api/v1/sandbox/status/:id

func (*Handler) Info

func (h *Handler) Info(c echo.Context) error

Info handles GET /api/v1/sandbox/info

func (*Handler) Kill

func (h *Handler) Kill(c echo.Context) error

Kill handles POST /api/v1/sandbox/kill/:id

func (*Handler) Manager

func (h *Handler) Manager() *Manager

Manager returns the underlying sandbox manager.

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers the sandbox routes.

func (*Handler) SetConfigStore

func (h *Handler) SetConfigStore(store *appconfig.ConfigStore)

SetConfigStore wires the kv-backed config store used for persistence.

func (*Handler) SetNetworkConfigHook

func (h *Handler) SetNetworkConfigHook(hook func(networkEnabled bool))

SetNetworkConfigHook wires an optional runtime update callback.

func (*Handler) UpdateConfig

func (h *Handler) UpdateConfig(c echo.Context) error

UpdateConfig handles PATCH /api/v1/sandbox/config

type LinuxExecutor

type LinuxExecutor struct {
	*BaseExecutor
	// contains filtered or unexported fields
}

LinuxExecutor provides sandboxed execution on Linux using namespaces and cgroups.

func (*LinuxExecutor) Cleanup

func (e *LinuxExecutor) Cleanup() error

Cleanup cleans up resources including cgroups.

func (*LinuxExecutor) Execute

Execute executes a command with Linux-specific isolation.

func (*LinuxExecutor) IsSupported

func (e *LinuxExecutor) IsSupported() bool

IsSupported returns true if Linux sandboxing is supported.

func (*LinuxExecutor) SupportsNetworkEnabled

func (e *LinuxExecutor) SupportsNetworkEnabled() bool

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager manages sandbox executions.

func NewManager

func NewManager(config *Config) (*Manager, error)

NewManager creates a new sandbox manager.

func (*Manager) Cleanup

func (m *Manager) Cleanup() error

Cleanup cleans up resources.

func (*Manager) Execute

func (m *Manager) Execute(ctx context.Context, req *ExecutionRequest) (*ExecutionResult, error)

Execute executes a command in the sandbox.

func (*Manager) GetConfig

func (m *Manager) GetConfig() *Config

GetConfig returns the sandbox configuration.

func (*Manager) GetStatus

func (m *Manager) GetStatus(id string) (*ExecutionResult, error)

GetStatus returns the status of an execution.

func (*Manager) IsSupported

func (m *Manager) IsSupported() bool

IsSupported returns true if sandboxing is supported on this platform.

func (*Manager) Kill

func (m *Manager) Kill(id string) error

Kill kills a running execution.

func (*Manager) SupportReason

func (m *Manager) SupportReason() string

SupportReason returns a human-readable reason when sandboxing is unavailable.

func (*Manager) SupportsNetworkEnabled

func (m *Manager) SupportsNetworkEnabled() bool

SupportsNetworkEnabled reports whether this sandbox backend can enforce the NetworkEnabled runtime toggle.

func (*Manager) SupportsTier

func (m *Manager) SupportsTier(tier Tier) bool

SupportsTier reports whether the requested sandbox tier is currently available.

type ResourceUsage

type ResourceUsage struct {
	// CPUTime is the CPU time used in nanoseconds.
	CPUTime int64 `json:"cpu_time_ns"`
	// MemoryPeak is the peak memory usage in bytes.
	MemoryPeak int64 `json:"memory_peak_bytes"`
	// IORead is the number of bytes read.
	IORead int64 `json:"io_read_bytes"`
	// IOWrite is the number of bytes written.
	IOWrite int64 `json:"io_write_bytes"`
}

ResourceUsage contains resource usage statistics.

type SeccompProfile

type SeccompProfile struct {
	DefaultAction string
	Syscalls      []SyscallRule
}

SeccompProfile represents a seccomp profile for syscall filtering.

func DefaultSeccompProfile

func DefaultSeccompProfile() *SeccompProfile

DefaultSeccompProfile returns a restrictive seccomp profile.

type SyscallRule

type SyscallRule struct {
	Names  []string
	Action string
}

SyscallRule represents a rule for a syscall.

type Tier

type Tier string

Tier identifies the sandbox isolation level requested by the caller.

const (
	// TierLight is the lightweight sandbox tier.
	TierLight Tier = "light"
	// TierStrong is the stronger isolation sandbox tier.
	TierStrong Tier = "strong"
)

type UpdateConfigRequest

type UpdateConfigRequest struct {
	NetworkEnabled *bool `json:"network_enabled,omitempty"`
}

UpdateConfigRequest represents supported sandbox runtime config updates.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL