sandbox

package
v0.0.0-...-1a28f28 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package sandbox provides isolated execution environments for Deputy.

The sandbox package enables secure execution of plugins, AI agents, remediation commands, and user-specified commands (`deputy exec`) in isolated environments. It supports multiple runtime backends and integrates with Deputy's policy engine for fine-grained control.

Architecture

The sandbox system consists of three main components:

  • Runtime interface: Abstract interface that sandbox backends implement
  • Manager: Coordinates runtime discovery, policy evaluation, and execution
  • Runtimes: Concrete implementations (Docker, gVisor, None, plugins)

Supported Runtimes

Built-in runtimes:

  • Docker: Container isolation via Docker Engine/Desktop (cross-platform)
  • gVisor: Application-level sandboxing with user-space kernel (Linux)
  • sandbox-exec: macOS seatbelt sandbox (deprecated, best-effort)
  • None: No sandboxing for trusted execution

External plugin runtimes can be added via executables named `deputy-sandbox-*` that implement the SandboxRuntimeService proto interface.

Usage

Create a sandbox manager and execute commands:

mgr, err := sandbox.NewManager(ctx)
if err != nil {
    log.Fatal(err)
}

req := &sandboxv1.ExecuteRequest{
    Command:      []string{"npm", "install"},
    WorkspaceDir: "/path/to/project",
    Config: &sandboxv1.SandboxConfig{
        Mode:        sandboxv1.Mode_MODE_WORKSPACE_WRITE,
        NetworkMode: sandboxv1.NetworkMode_NETWORK_MODE_BRIDGE,
    },
}

for event, err := range mgr.Execute(ctx, req) {
    if err != nil {
        log.Printf("error: %v", err)
        break
    }
    // Handle event (output, completion, etc.)
}

Policy Integration

The sandbox manager evaluates policies at three entrypoints:

  • sandbox_execution: Before any sandbox execution begins
  • sandbox_command: For each command within a sandbox session
  • sandbox_network: When the sandbox requests network access

Policies can deny execution, warn, or override sandbox configuration:

policies:
  - name: require-container-for-agents
    entrypoints: ["sandbox_execution"]
    rules:
      - action: deny
        when: |
          context.source == 2 &&
          requested_config.runtime == 1
        reason: "AI agents must run in container isolation"

Configuration

Sandbox behavior is configured via `.deputy.yaml`:

sandbox:
  default_runtime: docker
  default_mode: workspace-write
  default_network_mode: none
  default_limits:
    memory: 512m
    cpu: "1.0"

Security Considerations

The sandbox system provides defense-in-depth but is not a complete security boundary. Container escapes are possible with sufficient privileges or vulnerabilities. For maximum isolation, use gVisor or Firecracker (future). macOS sandbox-exec is deprecated by Apple and should be treated as best-effort isolation only.

Key security features:

  • Network isolation by default (NETWORK_MODE_NONE)
  • Filesystem isolation (workspace-only writes by default)
  • Resource limits (memory, CPU, PIDs)
  • Capability dropping (all capabilities dropped by default)
  • Policy-driven access control

Index

Constants

View Source
const (
	// EnvDockerCLI specifies the path to a Docker-compatible CLI.
	// Supports docker, nerdctl, finch, podman, or any compatible CLI.
	// Used by container-based runtimes (Docker, gVisor in Docker mode).
	// Default: "docker"
	//
	// Example:
	//   DEPUTY_DOCKER_CLI=/usr/local/bin/nerdctl deputy exec -- ls
	//   DEPUTY_DOCKER_CLI=finch deputy exec -- ls
	EnvDockerCLI = "DEPUTY_DOCKER_CLI"

	// EnvDockerHost specifies the Docker daemon socket.
	// This is passed through to the Docker client via DOCKER_HOST.
	// Useful for remote Docker daemons or custom socket paths.
	// Default: Uses Docker's default socket detection
	//
	// Example:
	//   DEPUTY_DOCKER_HOST=unix:///var/run/docker.sock deputy exec -- ls
	//   DEPUTY_DOCKER_HOST=tcp://192.168.1.100:2375 deputy exec -- ls
	EnvDockerHost = "DEPUTY_DOCKER_HOST"

	// EnvRunscPath specifies the path to the runsc (gVisor) binary.
	// Used by the gVisor runtime for standalone mode.
	// Default: "runsc"
	//
	// Example:
	//   DEPUTY_RUNSC_PATH=/opt/gvisor/runsc deputy exec --runtime gvisor -- ls
	EnvRunscPath = "DEPUTY_RUNSC_PATH"
)

Environment variable names for sandbox configuration. These allow users to customize sandbox runtime behavior without modifying code or configuration files.

Variables

View Source
var BlockedEnvVars = DangerousEnvVars

BlockedEnvVars is a deprecated alias for DangerousEnvVars.

View Source
var DangerousBinaries = map[string]bool{

	"mount":      true,
	"umount":     true,
	"nsenter":    true,
	"unshare":    true,
	"chroot":     true,
	"pivot_root": true,

	"strace":   true,
	"ltrace":   true,
	"ptrace":   true,
	"gdb":      true,
	"lldb":     true,
	"debugfs":  true,
	"perf":     true,
	"bpftrace": true,

	"insmod":   true,
	"rmmod":    true,
	"modprobe": true,
	"depmod":   true,

	"kexec":   true,
	"dmsetup": true,
	"losetup": true,

	"docker":     true,
	"podman":     true,
	"containerd": true,
	"ctr":        true,
	"crictl":     true,
	"kubectl":    true,
	"runc":       true,

	"init":      true,
	"systemctl": true,
	"service":   true,
	"reboot":    true,
	"shutdown":  true,
	"halt":      true,
	"poweroff":  true,
}

DangerousBinaries contains binaries that should not be executed in a sandbox. These can be used for privilege escalation, container escape, or other attacks.

View Source
var DangerousCapabilities = []string{
	"CAP_SYS_ADMIN",
	"CAP_SYS_PTRACE",
	"CAP_SYS_MODULE",
	"CAP_SYS_RAWIO",
	"CAP_SYS_BOOT",
	"CAP_DAC_READ_SEARCH",
	"CAP_DAC_OVERRIDE",
	"CAP_SYS_CHROOT",
	"CAP_SETPCAP",
	"CAP_SETFCAP",
}

DangerousCapabilities that should never be granted in a sandbox.

View Source
var DangerousEnvVars = map[string]bool{

	"LD_PRELOAD":      true,
	"LD_LIBRARY_PATH": true,
	"LD_AUDIT":        true,
	"LD_DEBUG":        true,
	"LD_PROFILE":      true,

	"DYLD_INSERT_LIBRARIES": true,
	"DYLD_LIBRARY_PATH":     true,
	"DYLD_FRAMEWORK_PATH":   true,

	"PYTHONPATH":        true,
	"PYTHONSTARTUP":     true,
	"RUBYOPT":           true,
	"RUBYLIB":           true,
	"PERL5LIB":          true,
	"PERL5OPT":          true,
	"NODE_OPTIONS":      true,
	"NODE_PATH":         true,
	"JAVA_TOOL_OPTIONS": true,

	"BASH_ENV":       true,
	"ENV":            true,
	"CDPATH":         true,
	"GLOBIGNORE":     true,
	"PROMPT_COMMAND": true,

	"AWS_SECRET_ACCESS_KEY":          true,
	"AWS_ACCESS_KEY_ID":              true,
	"AWS_SESSION_TOKEN":              true,
	"GITHUB_TOKEN":                   true,
	"GH_TOKEN":                       true,
	"GITLAB_TOKEN":                   true,
	"ANTHROPIC_API_KEY":              true,
	"OPENAI_API_KEY":                 true,
	"GOOGLE_API_KEY":                 true,
	"AZURE_CLIENT_SECRET":            true,
	"AZURE_TENANT_ID":                true,
	"NPM_TOKEN":                      true,
	"PYPI_TOKEN":                     true,
	"DOCKER_PASSWORD":                true,
	"DOCKER_AUTH_CONFIG":             true,
	"REGISTRY_AUTH":                  true,
	"SSH_AUTH_SOCK":                  true,
	"GPG_TTY":                        true,
	"SLACK_TOKEN":                    true,
	"SLACK_WEBHOOK_URL":              true,
	"TWILIO_AUTH_TOKEN":              true,
	"SENDGRID_API_KEY":               true,
	"STRIPE_SECRET_KEY":              true,
	"DATABASE_URL":                   true,
	"DATABASE_PASSWORD":              true,
	"DB_PASSWORD":                    true,
	"MYSQL_PASSWORD":                 true,
	"POSTGRES_PASSWORD":              true,
	"REDIS_PASSWORD":                 true,
	"MONGODB_URI":                    true,
	"JWT_SECRET":                     true,
	"SECRET_KEY":                     true,
	"ENCRYPTION_KEY":                 true,
	"API_KEY":                        true,
	"API_SECRET":                     true,
	"PRIVATE_KEY":                    true,
	"SERVICE_ACCOUNT_KEY":            true,
	"GOOGLE_APPLICATION_CREDENTIALS": true,
}

DangerousEnvVars contains environment variables that should never be passed to sandboxed processes as they can be used for code injection or privilege escalation.

View Source
var SafeHostEnvVars = map[string]bool{
	"PATH": true,
	"TERM": true,
	"HOME": true,
	"LANG": true,
	"TZ":   true,
}

SafeHostEnvVars contains environment variables that are considered safe to inherit from the host environment. All other host variables will be stripped unless explicitly provided by the user.

Functions

func CommandSafetyReason

func CommandSafetyReason(cmd []string) string

CommandSafetyReason returns a human-readable explanation for why a command was classified.

func DefaultCapabilities

func DefaultCapabilities() []string

DefaultCapabilities returns the default set of Linux capabilities. This is more permissive than MinimalCapabilities but still removes the most dangerous ones.

func FilterEnvVars

func FilterEnvVars(env map[string]string) (filtered map[string]string, removed []string)

FilterEnvVars removes dangerous environment variables from the provided map. Returns the filtered map and a list of removed variables for audit logging.

func GenerateExecutionID

func GenerateExecutionID(prefix string) string

GenerateExecutionID creates a cryptographically random execution ID. This prevents prediction attacks on container IDs.

func GetDockerCLI

func GetDockerCLI() string

GetDockerCLI returns the Docker CLI path from environment or default.

func GetDockerHost

func GetDockerHost() string

GetDockerHost returns the Docker host from DEPUTY_DOCKER_HOST or DOCKER_HOST. DEPUTY_DOCKER_HOST takes precedence to allow Deputy-specific configuration.

func GetRunscPath

func GetRunscPath() string

GetRunscPath returns the runsc path from environment or default.

func IsDangerousCommand

func IsDangerousCommand(cmd []string) bool

IsDangerousCommand is a convenience function that returns true if the command is classified as dangerous.

func IsSafeCommand

func IsSafeCommand(cmd []string) bool

IsSafeCommand is a convenience function that returns true if the command is classified as safe.

func MinimalCapabilities

func MinimalCapabilities() []string

MinimalCapabilities returns a minimal set of Linux capabilities suitable for most sandboxed workloads.

func SanitizeEnvironment

func SanitizeEnvironment(hostEnv []string, userEnv map[string]string) (finalEnv []string, removed []string)

SanitizeEnvironment constructs a safe environment for a sandboxed process.

It strictly limits inherited host variables to SafeHostEnvVars, then applies user-provided variables. Finally, it ensures no DangerousEnvVars are present in the final result.

Returns:

  • finalEnv: The safe list of "KEY=VALUE" strings
  • removed: List of keys that were blocked/removed (for auditing)

func ShouldWrapWithIsolation

func ShouldWrapWithIsolation(runtime sandboxv1.Runtime) bool

ShouldWrapWithIsolation returns true if the runtime should be wrapped. Container runtimes (Docker, Podman) handle isolation internally. Host-native runtimes need the wrapper.

func SupportedModes

func SupportedModes(caps *sandboxv1.RuntimeCapabilities) []sandboxv1.Mode

SupportedModes returns the filesystem modes a runtime supports. This is a helper for implementations to use in their Info() method.

func ValidateCommand

func ValidateCommand(cmd []string) error

ValidateCommand checks if a command is safe to execute. Returns an error if the command contains suspicious patterns. This validates both absolute paths and bare command names.

func ValidatePath

func ValidatePath(path string) error

ValidatePath checks if a path is safe for use in sandbox operations. It returns an error if the path contains suspicious patterns.

Types

type AuditEvent

type AuditEvent struct {
	// Timestamp when the event occurred
	Timestamp time.Time `json:"timestamp"`

	// EventType categorizes the audit event
	EventType AuditEventType `json:"event_type"`

	// ExecutionID is the unique identifier for the sandbox execution
	ExecutionID string `json:"execution_id"`

	// Runtime is the sandbox runtime used
	Runtime sandboxv1.Runtime `json:"runtime"`

	// Command being executed (first element only for security)
	Command string `json:"command,omitempty"`

	// CommandArgs is the number of arguments (not the args themselves)
	CommandArgCount int `json:"command_arg_count,omitempty"`

	// WorkspaceDir is the workspace directory if specified
	WorkspaceDir string `json:"workspace_dir,omitempty"`

	// NetworkMode indicates the network configuration
	NetworkMode string `json:"network_mode,omitempty"`

	// FilesystemMode indicates the filesystem access mode
	FilesystemMode string `json:"filesystem_mode,omitempty"`

	// User running the sandbox (UID:GID)
	User string `json:"user,omitempty"`

	// ExitCode if the execution completed
	ExitCode *int32 `json:"exit_code,omitempty"`

	// Duration of the execution
	DurationMs int64 `json:"duration_ms,omitempty"`

	// Error message if the event represents a failure
	Error string `json:"error,omitempty"`

	// SecurityEvent indicates if this is a security-relevant event
	SecurityEvent bool `json:"security_event,omitempty"`

	// FilteredEnvVars lists environment variables that were filtered
	FilteredEnvVars []string `json:"filtered_env_vars,omitempty"`

	// PolicyDenied indicates if a policy denied the operation
	PolicyDenied bool `json:"policy_denied,omitempty"`

	// PolicyName is the name of the policy that denied the operation
	PolicyName string `json:"policy_name,omitempty"`
}

AuditEvent represents a sandbox audit log entry.

type AuditEventType

type AuditEventType string

AuditEventType categorizes audit events.

const (
	// AuditEventExecutionRequested is logged when execution is requested
	AuditEventExecutionRequested AuditEventType = "execution_requested"

	// AuditEventExecutionStarted is logged when execution begins
	AuditEventExecutionStarted AuditEventType = "execution_started"

	// AuditEventExecutionCompleted is logged when execution finishes
	AuditEventExecutionCompleted AuditEventType = "execution_completed"

	// AuditEventExecutionFailed is logged when execution fails
	AuditEventExecutionFailed AuditEventType = "execution_failed"

	// AuditEventPolicyDenied is logged when a policy blocks execution
	AuditEventPolicyDenied AuditEventType = "policy_denied"

	// AuditEventEnvFiltered is logged when environment variables are filtered
	AuditEventEnvFiltered AuditEventType = "env_filtered"

	// AuditEventPathBlocked is logged when a path access is blocked
	AuditEventPathBlocked AuditEventType = "path_blocked"

	// AuditEventCommandBlocked is logged when a command is blocked
	AuditEventCommandBlocked AuditEventType = "command_blocked"

	// AuditEventResourceLimitExceeded is logged when resource limits are hit
	AuditEventResourceLimitExceeded AuditEventType = "resource_limit_exceeded"

	// AuditEventCleanupFailed is logged when cleanup fails
	AuditEventCleanupFailed AuditEventType = "cleanup_failed"
)

type Auditor

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

Auditor handles sandbox audit logging.

func NewAuditor

func NewAuditor(logger *slog.Logger) *Auditor

NewAuditor creates a new auditor with the given logger. If logger is nil, uses the default slog logger.

func (*Auditor) Log

func (a *Auditor) Log(ctx context.Context, event AuditEvent)

Log records an audit event.

func (*Auditor) LogCleanupFailed

func (a *Auditor) LogCleanupFailed(ctx context.Context, executionID string, runtime sandboxv1.Runtime, err error)

LogCleanupFailed logs when sandbox cleanup fails.

func (*Auditor) LogCommandBlocked

func (a *Auditor) LogCommandBlocked(ctx context.Context, executionID string, runtime sandboxv1.Runtime, command, reason string)

LogCommandBlocked logs when a command is blocked.

func (*Auditor) LogEnvFiltered

func (a *Auditor) LogEnvFiltered(ctx context.Context, executionID string, runtime sandboxv1.Runtime, filtered []string)

LogEnvFiltered logs when environment variables are filtered.

func (*Auditor) LogExecutionCompleted

func (a *Auditor) LogExecutionCompleted(ctx context.Context, executionID string, runtime sandboxv1.Runtime, exitCode int32, durationMs int64)

LogExecutionCompleted logs when a sandbox execution completes.

func (*Auditor) LogExecutionFailed

func (a *Auditor) LogExecutionFailed(ctx context.Context, executionID string, runtime sandboxv1.Runtime, err error)

LogExecutionFailed logs when a sandbox execution fails.

func (*Auditor) LogExecutionRequested

func (a *Auditor) LogExecutionRequested(ctx context.Context, executionID string, runtime sandboxv1.Runtime, req *sandboxv1.ExecuteRequest)

LogExecutionRequested logs when a sandbox execution is requested.

func (*Auditor) LogExecutionStarted

func (a *Auditor) LogExecutionStarted(ctx context.Context, executionID string, runtime sandboxv1.Runtime)

LogExecutionStarted logs when a sandbox execution actually starts.

func (*Auditor) LogPathBlocked

func (a *Auditor) LogPathBlocked(ctx context.Context, executionID string, runtime sandboxv1.Runtime, path, reason string)

LogPathBlocked logs when a path access is blocked.

func (*Auditor) LogPolicyDenied

func (a *Auditor) LogPolicyDenied(ctx context.Context, executionID string, runtime sandboxv1.Runtime, policyName, reason string)

LogPolicyDenied logs when a policy denies a sandbox operation.

type CommandSafety

type CommandSafety int

CommandSafety represents the safety classification of a command.

const (
	// CommandSafe means the command is read-only or benign.
	// No confirmation needed.
	CommandSafe CommandSafety = iota

	// CommandNormal means the command may modify files but is not inherently dangerous.
	// Confirmation based on sandbox mode.
	CommandNormal

	// CommandDangerous means the command is potentially destructive.
	// Always requires confirmation unless explicitly skipped.
	CommandDangerous
)

func ClassifyCommand

func ClassifyCommand(cmd []string) CommandSafety

ClassifyCommand determines the safety level of a command.

func (CommandSafety) String

func (s CommandSafety) String() string

String returns a human-readable safety level.

type Config

type Config struct {
	// DefaultRuntime is the preferred runtime if not specified in the request.
	DefaultRuntime sandboxv1.Runtime

	// FallbackRuntimes are tried in order if the preferred runtime is unavailable.
	FallbackRuntimes []sandboxv1.Runtime

	// DefaultMode is the filesystem mode if not specified.
	DefaultMode sandboxv1.Mode

	// DefaultNetworkMode is the network mode if not specified.
	DefaultNetworkMode sandboxv1.NetworkMode

	// DefaultLimits are applied when limits are not specified in the request.
	DefaultLimits *sandboxv1.ResourceLimits

	// DefaultImage is the container image to use if not specified.
	DefaultImage string

	// PolicyPaths are paths to policy files for sandbox evaluation.
	PolicyPaths []string
}

Config configures the sandbox Manager.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a sensible default configuration.

type ExecuteResult

type ExecuteResult struct {
	// ExecutionID is the unique identifier for this execution.
	ExecutionID string

	// ExitCode is the process exit code.
	// 0 indicates success, non-zero indicates failure.
	ExitCode int32

	// Stdout is the captured standard output.
	Stdout []byte

	// Stderr is the captured standard error.
	Stderr []byte

	// Error is set if execution failed.
	Error error

	// Duration is how long the execution took.
	DurationMs int64
}

ExecuteResult contains the final result of a sandbox execution. This is a convenience type for callers that don't need streaming.

func CollectResult

func CollectResult(seq iter.Seq2[*sandboxv1.ExecuteEvent, error]) *ExecuteResult

CollectResult consumes an Execute iterator and returns the final result. This is a convenience function for callers that don't need streaming.

type ExecutionError

type ExecutionError struct {
	Message     string
	Code        string
	IsFatal     bool
	IsRetriable bool
}

ExecutionError represents an error during sandbox execution.

func (*ExecutionError) Error

func (e *ExecutionError) Error() string

type IsolatingRuntime

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

IsolatingRuntime wraps a Runtime with workspace isolation. This is used for host-native runtimes (sandbox-exec, landlock, bwrap) that don't natively support workspace isolation modes. Container runtimes like Docker handle isolation internally.

The wrapper: 1. Sets up workspace isolation before execution (snapshot, overlay, etc.) 2. Rewrites the request to use the isolated path 3. After execution, emits WorkspaceChangesEvent for review workflow 4. Handles teardown based on preserveChanges setting

Security considerations: - Isolation is set up before the untrusted command runs - Original workspace is never directly accessible to the sandboxed process - Changes are captured and can be reviewed before syncing - Symlinks in copies are skipped to prevent escape attacks

func NewIsolatingRuntime

func NewIsolatingRuntime(inner Runtime, cfg IsolatingRuntimeConfig) (*IsolatingRuntime, error)

NewIsolatingRuntime wraps a runtime with workspace isolation. Returns nil if isolation is not needed (direct mode or no workspace).

func (*IsolatingRuntime) Available

func (r *IsolatingRuntime) Available(ctx context.Context) bool

Available returns whether the inner runtime is available.

func (*IsolatingRuntime) Capabilities

func (r *IsolatingRuntime) Capabilities() *sandboxv1.RuntimeCapabilities

Capabilities returns the inner runtime's capabilities.

func (*IsolatingRuntime) Cleanup

func (r *IsolatingRuntime) Cleanup(ctx context.Context, executionID string) error

Cleanup delegates to the inner runtime.

func (*IsolatingRuntime) Execute

Execute runs a command with workspace isolation.

func (*IsolatingRuntime) Info

Info returns the inner runtime's info.

func (*IsolatingRuntime) Isolator

func (r *IsolatingRuntime) Isolator() workspace.Isolator

Isolator returns the underlying workspace isolator for sync operations. This allows callers to sync changes back to the original workspace.

func (*IsolatingRuntime) Name

Name returns the inner runtime's name.

func (*IsolatingRuntime) Version

func (r *IsolatingRuntime) Version(ctx context.Context) string

Version returns the inner runtime's version.

type IsolatingRuntimeConfig

type IsolatingRuntimeConfig struct {
	// Mode determines isolation strategy (snapshot, overlay, etc.)
	Mode sandboxv1.WorkspaceIsolationMode

	// OriginalPath is the host workspace path.
	OriginalPath string

	// ReviewBeforeCommit enables change review workflow.
	ReviewBeforeCommit bool

	// PreserveAfterExecution keeps the isolated workspace for debugging.
	PreserveAfterExecution bool

	// SetupTimeout limits time spent setting up isolation.
	SetupTimeout time.Duration

	// FileMask configuration for hiding sensitive files.
	FileMask *sandboxv1.FileMaskConfig
}

IsolatingRuntimeConfig configures the isolating wrapper.

type Manager

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

Manager coordinates sandbox runtime discovery, policy evaluation, and execution. It provides the primary interface for sandboxed execution across Deputy.

func NewManager

func NewManager(ctx context.Context, opts ...ManagerOption) (*Manager, error)

NewManager creates a new sandbox manager.

func (*Manager) AvailableRuntimes

func (m *Manager) AvailableRuntimes(ctx context.Context) []Runtime

AvailableRuntimes returns all currently available runtimes.

func (*Manager) Cleanup

func (m *Manager) Cleanup(ctx context.Context, runtime sandboxv1.Runtime, executionID string) error

Cleanup releases resources for a specific execution.

func (*Manager) Close

func (m *Manager) Close() error

Close releases all manager resources.

func (*Manager) Execute

Execute runs a command in a sandbox.

The execution process: 1. Validate and normalize the request configuration 2. Evaluate sandbox_execution policy entrypoint 3. Select an appropriate runtime 4. Execute the command and stream events

Context cancellation will terminate the sandbox execution.

func (*Manager) ExecuteSync

func (m *Manager) ExecuteSync(ctx context.Context, req *sandboxv1.ExecuteRequest) *ExecuteResult

ExecuteSync is a convenience method that runs Execute and collects the result. Use Execute directly for streaming output.

func (*Manager) GetRuntime

func (m *Manager) GetRuntime(name sandboxv1.Runtime) Runtime

GetRuntime returns a runtime by name.

func (*Manager) ListRuntimes

func (m *Manager) ListRuntimes(ctx context.Context, includeUnavailable bool) (*sandboxv1.ListRuntimesResponse, error)

ListRuntimes returns information about all registered runtimes.

func (*Manager) MustRuntime

func (m *Manager) MustRuntime(name sandboxv1.Runtime) Runtime

MustRuntime returns a runtime by name, panicking if not found. Only use in tests or initialization code.

func (*Manager) RegisterRuntime

func (m *Manager) RegisterRuntime(runtime Runtime)

RegisterRuntime adds a runtime to the manager.

type ManagerOption

type ManagerOption func(*Manager)

ManagerOption configures a Manager.

func WithAuditor

func WithAuditor(auditor *Auditor) ManagerOption

WithAuditor sets the auditor for sandbox audit logging.

func WithConfig

func WithConfig(cfg *Config) ManagerOption

WithConfig sets the manager configuration.

func WithPolicyEngine

func WithPolicyEngine(engine *policy.Engine) ManagerOption

WithPolicyEngine sets the policy engine for sandbox policy evaluation.

func WithRegistry

func WithRegistry(reg RuntimeRegistry) ManagerOption

WithRegistry sets the runtime registry.

type ResourceDefaults

type ResourceDefaults struct {
	// MemoryLimit is the default memory limit (e.g., "512m", "1g")
	MemoryLimit string

	// CPULimit is the default CPU limit (e.g., "1.0", "0.5")
	CPULimit string

	// MaxPIDs is the maximum number of processes
	MaxPIDs int32

	// MaxOpenFiles is the maximum number of open file descriptors
	MaxOpenFiles int32

	// MaxFileSizeBytes is the maximum file size that can be created
	MaxFileSizeBytes int64
}

ResourceDefaults provides sensible default resource limits.

func DefaultResourceLimits

func DefaultResourceLimits() ResourceDefaults

DefaultResourceLimits returns conservative default resource limits.

func StrictResourceLimits

func StrictResourceLimits() ResourceDefaults

StrictResourceLimits returns strict resource limits for untrusted code.

type Runtime

type Runtime interface {
	// Name returns the runtime identifier (e.g., RUNTIME_DOCKER).
	Name() sandboxv1.Runtime

	// Info returns metadata about the runtime.
	// Returns availability status, version, and capabilities.
	Info(ctx context.Context) (*sandboxv1.RuntimeInfo, error)

	// Available returns true if the runtime can be used.
	// This checks if required binaries exist and services are running.
	// For example, Docker runtime checks if docker daemon is accessible.
	Available(ctx context.Context) bool

	// Version returns the runtime version string.
	// Returns empty string if version cannot be determined.
	Version(ctx context.Context) string

	// Capabilities returns what this runtime supports.
	// Used for runtime selection and feature negotiation.
	Capabilities() *sandboxv1.RuntimeCapabilities

	// Execute runs a command in the sandbox and streams events.
	//
	// The returned iterator yields events as execution proceeds:
	//   - StartedEvent: Execution has begun
	//   - OutputEvent: stdout/stderr output
	//   - CompletedEvent: Execution finished successfully
	//   - ErrorEvent: An error occurred
	//
	// Callers should iterate until the sequence is exhausted or an error occurs.
	// Context cancellation will terminate the sandbox execution.
	//
	// Example:
	//
	//	for event, err := range runtime.Execute(ctx, req) {
	//	    if err != nil {
	//	        log.Printf("execution error: %v", err)
	//	        break
	//	    }
	//	    // Handle event based on type
	//	}
	Execute(ctx context.Context, req *sandboxv1.ExecuteRequest) iter.Seq2[*sandboxv1.ExecuteEvent, error]

	// Cleanup releases resources associated with an execution.
	// Should be called after Execute completes to clean up containers, temp files, etc.
	// It is safe to call Cleanup multiple times.
	Cleanup(ctx context.Context, executionID string) error
}

Runtime is the interface that sandbox backends implement.

Built-in implementations include Docker, gVisor, and None. External plugins can provide additional runtimes by implementing the SandboxRuntimeService proto interface.

Implementations must be safe for concurrent use.

type RuntimeError

type RuntimeError struct {
	Runtime     sandboxv1.Runtime
	Message     string
	Remediation string
}

RuntimeError is an error with additional context for runtime selection failures. It includes a remediation message to help users resolve the issue.

func (*RuntimeError) Error

func (e *RuntimeError) Error() string

type RuntimeInfoLister

type RuntimeInfoLister interface {
	RuntimeInfos(ctx context.Context, includeUnavailable bool) ([]*sandboxv1.RuntimeInfo, error)
}

RuntimeInfoLister allows runtimes to expose multiple RuntimeInfo entries. This is useful for plugin-based runtimes that may represent multiple backends.

type RuntimeOption

type RuntimeOption func(any)

RuntimeOption configures a Runtime implementation.

type RuntimeRegistry

type RuntimeRegistry interface {
	// Register adds a runtime to the registry.
	Register(runtime Runtime)

	// Get returns a runtime by name, or nil if not found.
	Get(name sandboxv1.Runtime) Runtime

	// List returns all registered runtimes.
	List() []Runtime

	// Available returns runtimes that are currently usable.
	Available(ctx context.Context) []Runtime

	// Default returns the default runtime to use.
	// Returns nil if no runtimes are available.
	Default(ctx context.Context) Runtime
}

RuntimeRegistry holds available sandbox runtimes. Used by the Manager for runtime discovery and selection.

func NewRegistry

func NewRegistry() RuntimeRegistry

NewRegistry creates a new runtime registry.

Directories

Path Synopsis
runtimes
docker
Package docker provides a Docker container sandbox runtime.
Package docker provides a Docker container sandbox runtime.
gvisor
Package gvisor provides a gVisor sandbox runtime for stronger isolation.
Package gvisor provides a gVisor sandbox runtime for stronger isolation.
none
Package none provides a no-op sandbox runtime for trusted execution.
Package none provides a no-op sandbox runtime for trusted execution.
plugin
Package plugin provides an external sandbox runtime implemented by plugins.
Package plugin provides an external sandbox runtime implemented by plugins.
sandboxexec
Package sandboxexec provides a macOS sandbox-exec runtime.
Package sandboxexec provides a macOS sandbox-exec runtime.
Package sandboxtest provides utilities for testing sandbox runtime plugins in-memory without spawning external processes or using network sockets.
Package sandboxtest provides utilities for testing sandbox runtime plugins in-memory without spawning external processes or using network sockets.
Package workspace provides Docker-specific workspace isolation.
Package workspace provides Docker-specific workspace isolation.

Jump to

Keyboard shortcuts

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