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 ¶
- Variables
- func ApplySeccomp() error
- func Available() bool
- func ContextWithMode(ctx context.Context, m Mode) context.Context
- func DefaultSeccompProfile() []byte
- func DockerAvailable() bool
- func FormatResult(result *VerificationResult) string
- func GVisorAvailable() bool
- func GVisorDockerArgs() []string
- func GenerateSeatbeltProfile(policy *SeatbeltPolicy) string
- func IsAvailable() bool
- func LandlockAvailable() bool
- func RunSeatbelted(ctx context.Context, command string, policy *SeatbeltPolicy) (*exec.Cmd, error)
- func SeatbeltAvailable() bool
- func WrapCommand(command string, cfg SandboxConfig) (string, []string)
- type AdversaryInspector
- type CachedImage
- type CodeVerifier
- func (cv *CodeVerifier) AddBlockedFunction(fn string)
- func (cv *CodeVerifier) AddBlockedModule(module string)
- func (cv *CodeVerifier) AddBlockedPattern(pattern string) error
- func (cv *CodeVerifier) Verify(code, language string) *VerificationResult
- func (cv *CodeVerifier) VerifyBash(code string) []Violation
- func (cv *CodeVerifier) VerifyGo(code string) []Violation
- func (cv *CodeVerifier) VerifyPython(code string) []Violation
- type Config
- type ContainerSandbox
- func (c *ContainerSandbox) BuildFromDockerfile(ctx context.Context, dockerfile string) (string, error)
- func (c *ContainerSandbox) ContainerID() string
- func (c *ContainerSandbox) Exec(ctx context.Context, command string, timeout time.Duration) (string, error)
- func (c *ContainerSandbox) HotSwap(ctx context.Context) error
- func (c *ContainerSandbox) Image() string
- func (c *ContainerSandbox) Running() bool
- func (c *ContainerSandbox) SetImage(img string)
- func (c *ContainerSandbox) Start(ctx context.Context) error
- func (c *ContainerSandbox) Stop() error
- type DevEnvManager
- func (d *DevEnvManager) GetOrBuild(ctx context.Context, dockerfile string) (string, error)
- func (d *DevEnvManager) Invalidate(projectDir string)
- func (d *DevEnvManager) IsStale(projectDir string) bool
- func (d *DevEnvManager) RebuildAndForceSwap(ctx context.Context, dockerfilePath string) (string, error)
- type EgressInspector
- type Finding
- type InspectionResult
- type IsolationLevel
- type LandlockSandbox
- type Mode
- type NetworkProxy
- func (np *NetworkProxy) EnvVars() map[string]string
- func (np *NetworkProxy) GetLog() []ProxyLogEntry
- func (np *NetworkProxy) GetStats() ProxyStats
- func (np *NetworkProxy) IsAllowed(host string) bool
- func (np *NetworkProxy) Start(ctx context.Context) (string, error)
- func (np *NetworkProxy) Stop() error
- type ProxyConfig
- type ProxyLogEntry
- type ProxyStats
- type Sandbox
- type SandboxConfig
- type SandboxManager
- func (m *SandboxManager) Cleanup(maxAge time.Duration) error
- func (m *SandboxManager) Create(workDir string, envVars map[string]string) (*SandboxState, error)
- func (m *SandboxManager) DiffSandbox(id string) ([]string, error)
- func (m *SandboxManager) FormatStatus() string
- func (m *SandboxManager) List() []*SandboxState
- func (m *SandboxManager) Pause(id string) error
- func (m *SandboxManager) Restore(data []byte) (*SandboxState, error)
- func (m *SandboxManager) Resume(id string) (*SandboxState, error)
- func (m *SandboxManager) Snapshot(id string) ([]byte, error)
- type SandboxSelection
- type SandboxState
- type SeatbeltPolicy
- type SwapRequest
- type ThreatLevel
- type VerificationResult
- type Violation
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
RunSeatbelted is not available on non-darwin platforms.
func SeatbeltAvailable ¶
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 ¶
type AdversaryInspector struct{}
AdversaryInspector detects prompt injection attempts in tool outputs.
func (*AdversaryInspector) Inspect ¶
func (ai *AdversaryInspector) Inspect(content string) *InspectionResult
Inspect checks content for prompt injection patterns.
type CachedImage ¶
CachedImage holds metadata about a cached Docker image for a project.
type CodeVerifier ¶
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 ¶
func NewCodeVerifier() *CodeVerifier
NewCodeVerifier returns a CodeVerifier pre-configured with sensible defaults for Python, Go, and Bash analysis.
func (*CodeVerifier) AddBlockedFunction ¶
func (cv *CodeVerifier) AddBlockedFunction(fn string)
AddBlockedFunction adds a function to the blocked list.
func (*CodeVerifier) AddBlockedModule ¶
func (cv *CodeVerifier) AddBlockedModule(module string)
AddBlockedModule adds a module to the blocked list.
func (*CodeVerifier) AddBlockedPattern ¶
func (cv *CodeVerifier) AddBlockedPattern(pattern string) error
AddBlockedPattern compiles and adds a regex pattern to the blocked list.
func (*CodeVerifier) Verify ¶
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 ¶
func (cv *CodeVerifier) VerifyBash(code string) []Violation
VerifyBash analyses shell script code for dangerous commands.
func (*CodeVerifier) VerifyGo ¶
func (cv *CodeVerifier) VerifyGo(code string) []Violation
VerifyGo analyses Go source code using go/ast for imports and calls.
func (*CodeVerifier) VerifyPython ¶
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.
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 ¶
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 ¶
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 ¶
type EgressInspector struct {
AllowedDomains []string
}
EgressInspector detects data exfiltration attempts in tool commands/outputs.
func (*EgressInspector) Inspect ¶
func (ei *EgressInspector) Inspect(content string) *InspectionResult
Inspect checks content for data exfiltration attempts.
type Finding ¶
type Finding struct {
Type string
Level ThreatLevel
Message string
Content string // the offending content snippet
}
Finding represents a detected security issue.
type InspectionResult ¶
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.
func ModeFromContext ¶
ModeFromContext retrieves the sandbox Mode from a context. Returns ModeOff when no mode is set.
type NetworkProxy ¶
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 ¶
func NewNetworkProxy(config ProxyConfig) *NetworkProxy
NewNetworkProxy creates a new network proxy from the given configuration.
func (*NetworkProxy) EnvVars ¶
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 ¶
func (np *NetworkProxy) GetLog() []ProxyLogEntry
GetLog returns a copy of all proxy log entries.
func (*NetworkProxy) GetStats ¶
func (np *NetworkProxy) GetStats() ProxyStats
GetStats returns a copy of the current proxy statistics.
func (*NetworkProxy) IsAllowed ¶
func (np *NetworkProxy) IsAllowed(host string) bool
IsAllowed checks whether a host is permitted by the proxy rules.
func (*NetworkProxy) Start ¶
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 ¶
func (np *NetworkProxy) Stop() error
Stop stops the proxy server and cleans up resources.
type ProxyConfig ¶
type ProxyConfig struct {
AllowedDomains []string
BlockedDomains []string
Mode string // "allowlist", "blocklist", "open", "closed"
LogRequests bool
}
ProxyConfig configures the network proxy behavior.
func DefaultDevelopmentConfig ¶
func DefaultDevelopmentConfig() ProxyConfig
DefaultDevelopmentConfig returns a proxy config suitable for development that allows common package registries and blocks internal networks.
type ProxyLogEntry ¶
type ProxyLogEntry struct {
Timestamp time.Time
Host string
Method string
Allowed bool
Reason string
}
ProxyLogEntry records a single proxy request event.
type ProxyStats ¶
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.
type SandboxConfig ¶
SandboxConfig describes how a command should be sandboxed.
type SandboxManager ¶
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 ¶
func NewSandboxManager(dir string) *SandboxManager
NewSandboxManager creates a new SandboxManager that persists state to dir.
func (*SandboxManager) Cleanup ¶
func (m *SandboxManager) Cleanup(maxAge time.Duration) error
Cleanup removes sandboxes older than maxAge and their persisted state.
func (*SandboxManager) Create ¶
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 ¶
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 ¶
func (m *SandboxManager) FormatStatus() string
FormatStatus returns a human-readable summary of all sandboxes.
func (*SandboxManager) List ¶
func (m *SandboxManager) List() []*SandboxState
List returns all sandboxes sorted by creation time (newest first).
func (*SandboxManager) Pause ¶
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 ¶
func (m *SandboxManager) Restore(data []byte) (*SandboxState, error)
Restore deserializes snapshot data and creates a new sandbox from it.
func (*SandboxManager) Resume ¶
func (m *SandboxManager) Resume(id string) (*SandboxState, error)
Resume loads a paused sandbox from disk, restores its file state, and marks it as running.
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 ¶
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 ¶
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 ¶
func DefaultHawkPolicy(workDir string) *SeatbeltPolicy
DefaultHawkPolicy is a stub on non-darwin platforms.
type SwapRequest ¶
SwapRequest is sent when a container hot-swap is needed after a rebuild.
type ThreatLevel ¶
type ThreatLevel int
ThreatLevel classifies the severity of a detected threat.
const ( ThreatNone ThreatLevel = iota ThreatLow ThreatMedium ThreatHigh ThreatCritical )
func (ThreatLevel) String ¶
func (t ThreatLevel) String() string
type VerificationResult ¶
type VerificationResult struct {
Safe bool
Violations []Violation
Warnings []string
Language string
}
VerificationResult holds the outcome of a code verification pass.
type Violation ¶
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.