sandbox

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: MIT Imports: 30 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

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

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

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, error)

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, or an error if no sandbox backend is available.

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 ApprovalStore

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

ApprovalStore persists typed grants to a JSON file.

func NewApprovalStore

func NewApprovalStore(filePath string) *ApprovalStore

NewApprovalStore creates an approval store backed by the given file.

func NewGlobalApprovalStore

func NewGlobalApprovalStore() *ApprovalStore

NewGlobalApprovalStore creates an approval store for the user's home directory.

func NewProjectApprovalStore

func NewProjectApprovalStore(projectDir string) *ApprovalStore

NewProjectApprovalStore creates an approval store for a project directory.

func (*ApprovalStore) AddGrant

func (s *ApprovalStore) AddGrant(grant TypedGrant) error

AddGrant adds a new grant to the store and persists it.

func (*ApprovalStore) Check

func (s *ApprovalStore) Check(class GrantClass, target string) (GrantAction, bool)

Check evaluates whether a tool call is allowed, denied, or unknown. Returns: action (allow/deny), found (true if a matching grant exists).

func (*ApprovalStore) CleanupExpired

func (s *ApprovalStore) CleanupExpired() int

CleanupExpired removes expired grants and persists the change.

func (*ApprovalStore) Grants

func (s *ApprovalStore) Grants() []TypedGrant

Grants returns a snapshot of all grants.

func (*ApprovalStore) RemoveGrant

func (s *ApprovalStore) RemoveGrant(class GrantClass, target string) error

RemoveGrant removes a grant by class and target.

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

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"`
	Tier         Tier     `json:"tier"` // security tier (strict / workspace / off)
	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. The new default is TierWorkspace (allow workspace writes, deny process exec) which is safer than the legacy TierOff behavior. Users who need the full legacy behavior (process exec + writes) can set Tier=TierOff in their config.

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) SetRuntimeConfig

func (c *ContainerSandbox) SetRuntimeConfig(cfg RuntimeConfig)

SetRuntimeConfig overrides the declarative runtime config (extra deps and startup env vars). Additive: an empty config restores prior behavior.

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

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.

func (*DevEnvManager) SetRuntimeConfig

func (d *DevEnvManager) SetRuntimeConfig(cfg RuntimeConfig)

SetRuntimeConfig overrides the declarative runtime config used when building images. Additive: an empty config restores prior behavior.

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 GrantAction

type GrantAction string

GrantAction represents the action of a grant.

const (
	GrantAllow GrantAction = "allow"
	GrantDeny  GrantAction = "deny"
)

type GrantClass

type GrantClass string

GrantClass represents the type of operation being granted.

const (
	ClassBash  GrantClass = "bash"
	ClassRead  GrantClass = "read"
	ClassWrite GrantClass = "write"
	ClassEdit  GrantClass = "edit"
)

type InspectionResult

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. Unrecognized values default to ModeStrict (fail-closed) to prevent accidental sandbox bypass via typos.

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 PolicyConfig

type PolicyConfig struct {
	Default PolicyDecision `json:"default"`
	Rules   []PolicyRule   `json:"rules"`
}

PolicyConfig defines the sandbox policy configuration.

type PolicyDecision

type PolicyDecision string

PolicyDecision represents the outcome of a policy check.

const (
	DecisionAllow PolicyDecision = "allow"
	DecisionDeny  PolicyDecision = "deny"
	DecisionAsk   PolicyDecision = "ask"
)

type PolicyManager

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

PolicyManager adds policy-aware tool interception on top of the sandbox.

func NewPolicyManager

func NewPolicyManager(projectDir string) *PolicyManager

NewPolicyManager creates a policy manager for the given project.

func (*PolicyManager) Allow

func (m *PolicyManager) Allow(class GrantClass, target string) error

Allow persists an allow grant for the given class and target.

func (*PolicyManager) CheckTool

func (m *PolicyManager) CheckTool(class GrantClass, target string) (PolicyDecision, bool)

CheckTool evaluates a tool call against the policy and approval grants. Returns the decision and whether the caller should prompt the user.

func (*PolicyManager) Deny

func (m *PolicyManager) Deny(class GrantClass, target string) error

Deny persists a deny grant for the given class and target.

func (*PolicyManager) Policy

func (m *PolicyManager) Policy() PolicyConfig

Policy returns the current policy config.

func (*PolicyManager) ReloadPolicy

func (m *PolicyManager) ReloadPolicy()

ReloadPolicy re-reads policy files from disk.

type PolicyRule

type PolicyRule struct {
	Class   string `json:"class"`   // "bash", "read", "write", "edit"
	Pattern string `json:"pattern"` // glob or prefix pattern
	Action  string `json:"action"`  // "allow", "deny", "ask"
}

PolicyRule defines a single policy rule.

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 RuntimeConfig

type RuntimeConfig struct {
	// RuntimeExtraDeps is a list of shell commands run during image build,
	// after the base image, to install extra dependencies. Each entry becomes
	// its own RUN layer in the generated Dockerfile fragment.
	RuntimeExtraDeps []string `json:"runtime_extra_deps"`
	// RuntimeStartupEnvVars are environment variables injected when the
	// container starts (docker run -e KEY=VALUE).
	RuntimeStartupEnvVars map[string]string `json:"runtime_startup_env_vars"`
}

RuntimeConfig declares additive runtime customizations for a container sandbox. It is parsed from .agents/runtime.jsonc (project) and is fully optional: the empty value reproduces the current behavior exactly.

func LoadRuntimeConfig

func LoadRuntimeConfig(projectDir string) RuntimeConfig

LoadRuntimeConfig reads .agents/runtime.jsonc from projectDir. A missing file yields a zero RuntimeConfig and no error; a malformed file is logged and also yields a zero config (fail-open to current behavior, since this is purely additive).

func (RuntimeConfig) AppendExtraDeps

func (c RuntimeConfig) AppendExtraDeps(dockerfile string) string

AppendExtraDeps returns dockerfile with the extra-deps RUN layers appended. When there are no extra deps, dockerfile is returned unchanged. A trailing newline is ensured before appending so the fragment is well-formed.

func (RuntimeConfig) ExtraDepsDockerfileFragment

func (c RuntimeConfig) ExtraDepsDockerfileFragment() string

ExtraDepsDockerfileFragment composes the RUN layers for runtime_extra_deps. Returns "" when there are no extra deps. Each command is emitted as its own RUN instruction so build-cache invalidation is granular and errors are attributable to a single command. Blank/whitespace-only entries are skipped.

func (RuntimeConfig) IsEmpty

func (c RuntimeConfig) IsEmpty() bool

IsEmpty reports whether the config carries no customizations.

func (RuntimeConfig) StartupEnvArgs

func (c RuntimeConfig) StartupEnvArgs() []string

StartupEnvArgs returns the "-e KEY=VALUE" docker run arguments for the configured startup env vars, sorted by key for deterministic output. Returns nil when there are no env vars.

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
	// Tier selects the security tier (strict / workspace / off).
	// Empty defaults to TierOff for back-compat with legacy
	// callers that don't know about tiers. New callers should
	// set Tier explicitly (typically TierWorkspace to match
	// the Config.Tier default in DefaultConfig).
	Tier Tier
}

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.

func (*SandboxManager) Snapshot

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

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
	Tier          Tier
}

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

func DefaultHawkPolicy

func DefaultHawkPolicy(workDir string, tier Tier) *SeatbeltPolicy

DefaultHawkPolicy creates a sensible default SeatbeltPolicy for hawk operations in the given working directory. The tier parameter selects the security posture:

  • TierStrict: deny everything
  • TierWorkspace (new default): allow workspace writes, no process
  • TierOff: legacy behavior (allow everything)

type SwapRequest

type SwapRequest struct {
	ImageTag   string
	Dockerfile string
	Workspace  string
}

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 Tier

type Tier string

Tier controls the sandbox's security posture. The new default is TierWorkspace (allow workspace writes, deny process exec) which is safer than the legacy TierOff default. Existing users who rely on process exec can opt back in via Tier=TierOff in their config.

const (
	// TierStrict denies everything: no writes, no process exec,
	// no network. The agent can only read.
	TierStrict Tier = "strict"
	// TierWorkspace is the new default. Allows writes to the
	// workspace + scratch dir, but denies process exec. An agent
	// that needs to run Bash must either be in container mode
	// (ContainerExecutor) or have Tier set to TierOff.
	TierWorkspace Tier = "workspace"
	// TierOff is the legacy default. Allow everything: writes,
	// process exec, network. Used by users who need the full
	// pre-tier behavior.
	TierOff Tier = "off"
)

type TypedGrant

type TypedGrant struct {
	Action  GrantAction `json:"action"`
	Class   GrantClass  `json:"class"`
	Target  string      `json:"target"` // path pattern or command prefix
	Scope   string      `json:"scope"`  // "project" | "global"
	Expires *time.Time  `json:"expires,omitempty"`
}

TypedGrant is a policy grant for a specific class and target.

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.

Jump to

Keyboard shortcuts

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