sandbox

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package sandbox provides sandbox mode for isolated command execution. devenv.go adds dynamic Dockerfile caching per project.

Package sandbox provides adversary detection and egress inspection. Detects prompt injection, data exfiltration, and suspicious tool outputs.

Package sandbox provides sandbox mode for isolated command execution. This uses namespace/container isolation where available.

Index

Constants

This section is empty.

Variables

View Source
var ContainerImageTag = "latest"

ContainerImageTag is set at build time via ldflags. Falls back to "latest".

Functions

func ApplySeccomp

func ApplySeccomp() error

ApplySeccomp applies the default seccomp-bpf filter to the current process. The filter is irreversible: once installed it cannot be removed. Requires PR_SET_NO_NEW_PRIVS to be set first (Landlock's Apply does this).

func Available

func Available() bool

Available returns true if any sandbox mechanism is available on this system. This is a convenience alias for IsAvailable.

func ContextWithMode

func ContextWithMode(ctx context.Context, m Mode) context.Context

ContextWithMode attaches a sandbox Mode to a context.

func DefaultSeccompProfile

func DefaultSeccompProfile() []byte

DefaultSeccompProfile returns a raw BPF program (as bytes) that blocks dangerous syscalls. Each blocked syscall returns EPERM to the caller.

func DockerAvailable

func DockerAvailable() bool

DockerAvailable returns true if Docker daemon is reachable.

func FormatResult added in v0.2.0

func FormatResult(result *VerificationResult) string

FormatResult produces a human-readable summary of verification results.

func GVisorAvailable

func GVisorAvailable() bool

GVisorAvailable returns true if Docker is available with the runsc (gVisor) runtime.

func GVisorDockerArgs

func GVisorDockerArgs() []string

GVisorDockerArgs returns additional Docker args to use gVisor runtime. This provides VM-class isolation without actual VMs.

func GenerateSeatbeltProfile added in v0.2.0

func GenerateSeatbeltProfile(policy *SeatbeltPolicy) string

GenerateSeatbeltProfile is a stub on non-darwin platforms.

func IsAvailable

func IsAvailable() bool

IsAvailable checks if sandboxing is available on this system.

func LandlockAvailable

func LandlockAvailable() bool

LandlockAvailable returns true if Landlock is supported on this kernel. It attempts to create a zero-length ruleset; ENOSYS or EOPNOTSUPP indicates no support.

func RunSeatbelted added in v0.2.0

func RunSeatbelted(ctx context.Context, command string, policy *SeatbeltPolicy) (*exec.Cmd, error)

RunSeatbelted is not available on non-darwin platforms.

func SeatbeltAvailable added in v0.2.0

func SeatbeltAvailable() bool

SeatbeltAvailable always returns false on non-darwin platforms.

func WrapCommand

func WrapCommand(command string, cfg SandboxConfig) (string, []string)

WrapCommand wraps a shell command string with sandbox isolation based on the provided SandboxConfig. It returns the executable name and argument list suitable for exec.Command.

Types

type AdversaryInspector added in v0.2.0

type AdversaryInspector struct{}

AdversaryInspector detects prompt injection attempts in tool outputs.

func (*AdversaryInspector) Inspect added in v0.2.0

func (ai *AdversaryInspector) Inspect(content string) *InspectionResult

Inspect checks content for prompt injection patterns.

type CachedImage

type CachedImage struct {
	Tag         string
	ContentHash string
	BuiltAt     time.Time
	Stale       bool
}

CachedImage holds metadata about a cached Docker image for a project.

type CodeVerifier added in v0.2.0

type CodeVerifier struct {
	BlockedModules   []string
	BlockedFunctions []string
	BlockedPatterns  []*regexp.Regexp
	AllowedPaths     []string
	// contains filtered or unexported fields
}

CodeVerifier performs static analysis of generated code before execution, blocking dangerous operations such as forbidden imports, destructive system calls, and unsafe patterns.

func NewCodeVerifier added in v0.2.0

func NewCodeVerifier() *CodeVerifier

NewCodeVerifier returns a CodeVerifier pre-configured with sensible defaults for Python, Go, and Bash analysis.

func (*CodeVerifier) AddBlockedFunction added in v0.2.0

func (cv *CodeVerifier) AddBlockedFunction(fn string)

AddBlockedFunction adds a function to the blocked list.

func (*CodeVerifier) AddBlockedModule added in v0.2.0

func (cv *CodeVerifier) AddBlockedModule(module string)

AddBlockedModule adds a module to the blocked list.

func (*CodeVerifier) AddBlockedPattern added in v0.2.0

func (cv *CodeVerifier) AddBlockedPattern(pattern string) error

AddBlockedPattern compiles and adds a regex pattern to the blocked list.

func (*CodeVerifier) Verify added in v0.2.0

func (cv *CodeVerifier) Verify(code, language string) *VerificationResult

Verify analyses code in the given language and returns a structured result. Supported languages: "go", "python", "bash".

func (*CodeVerifier) VerifyBash added in v0.2.0

func (cv *CodeVerifier) VerifyBash(code string) []Violation

VerifyBash analyses shell script code for dangerous commands.

func (*CodeVerifier) VerifyGo added in v0.2.0

func (cv *CodeVerifier) VerifyGo(code string) []Violation

VerifyGo analyses Go source code using go/ast for imports and calls.

func (*CodeVerifier) VerifyPython added in v0.2.0

func (cv *CodeVerifier) VerifyPython(code string) []Violation

VerifyPython analyses Python source code using regex-based pattern matching.

type Config

type Config struct {
	Enabled      bool     `json:"enabled"`
	Type         string   `json:"type"` // "namespace", "docker", "chroot", "seatbelt", "none"
	AllowNetwork bool     `json:"allow_network"`
	AllowWrite   bool     `json:"allow_write"`
	ReadOnlyDirs []string `json:"read_only_dirs"`
	WritableDirs []string `json:"writable_dirs"`
	MaxMemoryMB  int      `json:"max_memory_mb"`
	MaxCPUPct    int      `json:"max_cpu_pct"`
}

Config describes sandbox configuration.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default sandbox configuration.

type ContainerSandbox

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

ContainerSandbox executes commands inside a Docker container, providing full isolation. It supports dynamic Dockerfile generation for on-the-fly environment setup (inspired by herm's DevEnv pattern).

func NewContainerSandbox

func NewContainerSandbox(projectDir string) *ContainerSandbox

NewContainerSandbox creates a container sandbox for the given project.

func (*ContainerSandbox) BuildFromDockerfile

func (c *ContainerSandbox) BuildFromDockerfile(ctx context.Context, dockerfile string) (string, error)

BuildFromDockerfile builds a new image from a Dockerfile in the project. Returns the image tag that can be used for subsequent Start calls.

func (*ContainerSandbox) ContainerID

func (c *ContainerSandbox) ContainerID() string

ContainerID returns the full container ID (empty if not running).

func (*ContainerSandbox) Exec

func (c *ContainerSandbox) Exec(ctx context.Context, command string, timeout time.Duration) (string, error)

Exec runs a command inside the container and returns its output.

func (*ContainerSandbox) HotSwap

func (c *ContainerSandbox) HotSwap(ctx context.Context) error

HotSwap stops the current container and starts a new one with the updated image.

func (*ContainerSandbox) Image

func (c *ContainerSandbox) Image() string

Image returns the current image name.

func (*ContainerSandbox) Running

func (c *ContainerSandbox) Running() bool

Running reports whether the container is active.

func (*ContainerSandbox) SetImage

func (c *ContainerSandbox) SetImage(img string)

SetImage updates the image to use for the next Start call.

func (*ContainerSandbox) Start

func (c *ContainerSandbox) Start(ctx context.Context) error

Start launches the container with the project directory mounted.

func (*ContainerSandbox) Stop

func (c *ContainerSandbox) Stop() error

Stop terminates the container.

type DevEnvManager

type DevEnvManager struct {

	// OnSwapNeeded is called after a successful rebuild to request a container
	// hot-swap. The session should stop the old container and start a new one
	// with the given image tag. May be nil.
	OnSwapNeeded func(req SwapRequest)
	// contains filtered or unexported fields
}

DevEnvManager caches Docker images per-project based on Dockerfile content hashes.

func NewDevEnvManager

func NewDevEnvManager(projectDir string) *DevEnvManager

NewDevEnvManager creates a new DevEnvManager for the given project directory.

func (*DevEnvManager) GetOrBuild

func (d *DevEnvManager) GetOrBuild(ctx context.Context, dockerfile string) (string, error)

GetOrBuild returns the cached image tag if the Dockerfile content hash matches, otherwise rebuilds and caches the new image.

func (*DevEnvManager) Invalidate

func (d *DevEnvManager) Invalidate(projectDir string)

Invalidate marks the cache for the given project directory as stale.

func (*DevEnvManager) IsStale

func (d *DevEnvManager) IsStale(projectDir string) bool

IsStale checks if the Dockerfile for the given project directory has changed since last build.

func (*DevEnvManager) RebuildAndForceSwap added in v0.2.0

func (d *DevEnvManager) RebuildAndForceSwap(ctx context.Context, dockerfilePath string) (string, error)

RebuildAndForceSwap forces a rebuild even if cached, then triggers the OnSwapNeeded callback. This is the hot-swap path.

type EgressInspector added in v0.2.0

type EgressInspector struct {
	AllowedDomains []string
}

EgressInspector detects data exfiltration attempts in tool commands/outputs.

func (*EgressInspector) Inspect added in v0.2.0

func (ei *EgressInspector) Inspect(content string) *InspectionResult

Inspect checks content for data exfiltration attempts.

type Finding added in v0.2.0

type Finding struct {
	Type    string
	Level   ThreatLevel
	Message string
	Content string // the offending content snippet
}

Finding represents a detected security issue.

type InspectionResult added in v0.2.0

type InspectionResult struct {
	Safe     bool
	Findings []Finding
}

InspectionResult holds all findings from an inspection.

type IsolationLevel

type IsolationLevel string

IsolationLevel represents the desired sandbox strength.

const (
	IsolationDefault   IsolationLevel = "default"
	IsolationEnhanced  IsolationLevel = "enhanced"
	IsolationContainer IsolationLevel = "container"
	IsolationMaximum   IsolationLevel = "maximum"
	IsolationOff       IsolationLevel = "off"
)

type LandlockSandbox

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

LandlockSandbox restricts filesystem access for the current process.

func NewLandlockSandbox

func NewLandlockSandbox(projectDir string) *LandlockSandbox

NewLandlockSandbox creates a sandbox that allows read/write to the project directory and /tmp, and read-only access to essential system paths.

func (*LandlockSandbox) AddReadOnlyPath

func (l *LandlockSandbox) AddReadOnlyPath(path string)

AddReadOnlyPath appends a read-only path to the sandbox configuration. Must be called before Apply.

func (*LandlockSandbox) AddReadWritePath

func (l *LandlockSandbox) AddReadWritePath(path string)

AddReadWritePath appends a read-write path to the sandbox configuration. Must be called before Apply.

func (*LandlockSandbox) Apply

func (l *LandlockSandbox) Apply() error

Apply enforces the Landlock rules on the current process. After this call, the process cannot access any path not explicitly allowed. This is irreversible for the lifetime of the process.

type Mode

type Mode string

Mode represents the sandbox isolation level.

const (
	ModeStrict    Mode = "strict"    // read-only filesystem
	ModeWorkspace Mode = "workspace" // write only in project dir + /tmp
	ModeOff       Mode = "off"       // no restrictions
)

func ModeFromContext

func ModeFromContext(ctx context.Context) Mode

ModeFromContext retrieves the sandbox Mode from a context. Returns ModeOff when no mode is set.

func ParseMode

func ParseMode(s string) Mode

ParseMode converts a string to a Mode, defaulting to ModeOff for unrecognised values.

type NetworkProxy added in v0.2.0

type NetworkProxy struct {
	AllowedDomains []string
	BlockedDomains []string
	AllowAll       bool
	BlockAll       bool
	Port           int

	Stats ProxyStats
	Log   []ProxyLogEntry
	// contains filtered or unexported fields
}

NetworkProxy provides domain-level network access control for commands run by the agent. Inspired by Codex CLI's network-proxy approach.

func NewNetworkProxy added in v0.2.0

func NewNetworkProxy(config ProxyConfig) *NetworkProxy

NewNetworkProxy creates a new network proxy from the given configuration.

func (*NetworkProxy) EnvVars added in v0.2.0

func (np *NetworkProxy) EnvVars() map[string]string

EnvVars returns environment variables to set for child processes so they route traffic through this proxy.

func (*NetworkProxy) GetLog added in v0.2.0

func (np *NetworkProxy) GetLog() []ProxyLogEntry

GetLog returns a copy of all proxy log entries.

func (*NetworkProxy) GetStats added in v0.2.0

func (np *NetworkProxy) GetStats() ProxyStats

GetStats returns a copy of the current proxy statistics.

func (*NetworkProxy) IsAllowed added in v0.2.0

func (np *NetworkProxy) IsAllowed(host string) bool

IsAllowed checks whether a host is permitted by the proxy rules.

func (*NetworkProxy) Start added in v0.2.0

func (np *NetworkProxy) Start(ctx context.Context) (string, error)

Start starts the HTTP CONNECT proxy on localhost and returns the proxy address.

func (*NetworkProxy) Stop added in v0.2.0

func (np *NetworkProxy) Stop() error

Stop stops the proxy server and cleans up resources.

type ProxyConfig added in v0.2.0

type ProxyConfig struct {
	AllowedDomains []string
	BlockedDomains []string
	Mode           string // "allowlist", "blocklist", "open", "closed"
	LogRequests    bool
}

ProxyConfig configures the network proxy behavior.

func DefaultDevelopmentConfig added in v0.2.0

func DefaultDevelopmentConfig() ProxyConfig

DefaultDevelopmentConfig returns a proxy config suitable for development that allows common package registries and blocks internal networks.

type ProxyLogEntry added in v0.2.0

type ProxyLogEntry struct {
	Timestamp time.Time
	Host      string
	Method    string
	Allowed   bool
	Reason    string
}

ProxyLogEntry records a single proxy request event.

type ProxyStats added in v0.2.0

type ProxyStats struct {
	AllowedRequests int64
	BlockedRequests int64
	TotalBytes      int64
	UniqueHosts     map[string]int
}

ProxyStats tracks network proxy usage statistics.

type Sandbox

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

Sandbox provides isolated execution environment.

func New

func New(config *Config) (*Sandbox, error)

New creates a new sandbox.

func (*Sandbox) Close

func (s *Sandbox) Close() error

Close cleans up sandbox resources.

func (*Sandbox) Run

func (s *Sandbox) Run(ctx context.Context, command string) (*exec.Cmd, error)

Run executes a command in the sandbox.

type SandboxConfig

type SandboxConfig struct {
	Mode         Mode
	WorkspaceDir string
	AllowNetwork bool
}

SandboxConfig describes how a command should be sandboxed.

type SandboxManager added in v0.2.0

type SandboxManager struct {
	Sandboxes    map[string]*SandboxState
	Dir          string
	MaxSandboxes int
	// contains filtered or unexported fields
}

SandboxManager manages sandbox lifecycle including pause/resume and snapshots.

func NewSandboxManager added in v0.2.0

func NewSandboxManager(dir string) *SandboxManager

NewSandboxManager creates a new SandboxManager that persists state to dir.

func (*SandboxManager) Cleanup added in v0.2.0

func (m *SandboxManager) Cleanup(maxAge time.Duration) error

Cleanup removes sandboxes older than maxAge and their persisted state.

func (*SandboxManager) Create added in v0.2.0

func (m *SandboxManager) Create(workDir string, envVars map[string]string) (*SandboxState, error)

Create creates a new sandbox with the given working directory and environment variables. It captures the initial file state of workDir.

func (*SandboxManager) DiffSandbox added in v0.2.0

func (m *SandboxManager) DiffSandbox(id string) ([]string, error)

DiffSandbox compares the current file state of a sandbox's working directory against its initial state and returns a list of changes.

func (*SandboxManager) FormatStatus added in v0.2.0

func (m *SandboxManager) FormatStatus() string

FormatStatus returns a human-readable summary of all sandboxes.

func (*SandboxManager) List added in v0.2.0

func (m *SandboxManager) List() []*SandboxState

List returns all sandboxes sorted by creation time (newest first).

func (*SandboxManager) Pause added in v0.2.0

func (m *SandboxManager) Pause(id string) error

Pause captures the current file state, persists the sandbox to disk, and marks it as paused.

func (*SandboxManager) Restore added in v0.2.0

func (m *SandboxManager) Restore(data []byte) (*SandboxState, error)

Restore deserializes snapshot data and creates a new sandbox from it.

func (*SandboxManager) Resume added in v0.2.0

func (m *SandboxManager) Resume(id string) (*SandboxState, error)

Resume loads a paused sandbox from disk, restores its file state, and marks it as running.

func (*SandboxManager) Snapshot added in v0.2.0

func (m *SandboxManager) Snapshot(id string) ([]byte, error)

Snapshot serializes the full state of a sandbox to JSON bytes.

type SandboxSelection

type SandboxSelection struct {
	Backend string // "landlock", "seatbelt", "nsjail", "bwrap", "docker", "none"
	Reason  string // why this was selected
}

SandboxSelection represents the chosen sandbox backend.

func SelectSandbox

func SelectSandbox(level IsolationLevel, projectDir string) SandboxSelection

SelectSandbox automatically chooses the best available sandbox backend for the current platform and requested isolation level.

macOS: seatbelt (always available) Linux: landlock+seccomp > nsjail > bubblewrap > docker > none

type SandboxState added in v0.2.0

type SandboxState struct {
	ID           string            `json:"id"`
	WorkDir      string            `json:"work_dir"`
	EnvVars      map[string]string `json:"env_vars"`
	Files        map[string][]byte `json:"files"`
	ProcessState string            `json:"process_state"`
	CreatedAt    time.Time         `json:"created_at"`
	PausedAt     *time.Time        `json:"paused_at,omitempty"`
	ResumedAt    *time.Time        `json:"resumed_at,omitempty"`
	Status       string            `json:"status"` // "running", "paused", "terminated"
	// contains filtered or unexported fields
}

SandboxState represents the full state of an execution sandbox.

type SeatbeltPolicy added in v0.2.0

type SeatbeltPolicy struct {
	AllowNetwork  bool
	AllowWrite    bool
	ReadablePaths []string
	WritablePaths []string
	AllowProcess  bool
	AllowSysctl   bool
}

SeatbeltPolicy describes the permissions for a macOS seatbelt sandbox profile. This is a stub on non-darwin platforms.

func DefaultHawkPolicy added in v0.2.0

func DefaultHawkPolicy(workDir string) *SeatbeltPolicy

DefaultHawkPolicy is a stub on non-darwin platforms.

type SwapRequest added in v0.2.0

type SwapRequest struct {
	ImageTag   string
	Dockerfile string
	Workspace  string
}

SwapRequest is sent when a container hot-swap is needed after a rebuild.

type ThreatLevel added in v0.2.0

type ThreatLevel int

ThreatLevel classifies the severity of a detected threat.

const (
	ThreatNone ThreatLevel = iota
	ThreatLow
	ThreatMedium
	ThreatHigh
	ThreatCritical
)

func (ThreatLevel) String added in v0.2.0

func (t ThreatLevel) String() string

type VerificationResult added in v0.2.0

type VerificationResult struct {
	Safe       bool
	Violations []Violation
	Warnings   []string
	Language   string
}

VerificationResult holds the outcome of a code verification pass.

type Violation added in v0.2.0

type Violation struct {
	Type     string // "blocked_module", "blocked_function", "dangerous_pattern", "file_access", "network_access", "system_call"
	Line     int
	Code     string
	Reason   string
	Severity string // "error", "warning"
}

Violation represents a single dangerous construct found in the code.

Jump to

Keyboard shortcuts

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