sandbox

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

This file implements sandbox escalation, following upstream escalation.ts. Read-only may widen to workspace-write or danger-full-access; workspace-write may widen only to danger-full-access, which cannot widen further. Schemas expose the closed target set; runtime checks compare the actual effective mode. sandbox_permissions and nonempty justification must appear together. Approval fails closed: check widening first, request approval, then map the result. Invalid widening never prompts; allowed-once grants only this call, while rejection, cancellation, and unavailable approval have distinct errors.

Sandbox invariants follow upstream sandbox, sandbox-policy, and sandbox-local invariant modules. InvariantEnabled controls checks; failures panic with package attribution. Checks cover valid modes, consistent policy fields, workspace roots, forbidden danger-mode confinement, escalation targets, and nonempty confined argument vectors.

LocalProvider follows upstream sandbox-local. Backend probing tries bwrap then landlock on Linux, seatbelt on macOS, and windows-acl on Windows. It runs a read-only profile with a true command and caches probe results. Confine builds backend-specific arguments and denial signatures: EROFS for bwrap, EACCES for landlock, and EPERM for seatbelt. RunnerCommand overrides skip probing and use the configured runner directly.

This file builds profiles for bwrap, landlock, and seatbelt, following upstream sandbox-local/profiles.ts. Bwrap mounts the root read-only and adds writable temporary/workspace mounts for workspace-write. Landlock allows root reads and /dev/null writes, adding temporary/workspace writes when requested. Seatbelt denies file writes except /dev/null and permitted workspace subpaths. Functions return profile arguments; LocalProvider assembles the complete command.

Writable-root calculation follows upstream sandbox/roots.ts. CanonicalPath resolves symlinks, including macOS /tmp to /private/tmp, retaining the original path on failure rather than inventing a fallback grant. WritableRoots is shared by process confinement and in-process filesystem guards. Workspace-write permits deduplicated canonical workspace and temporary roots; read-only and danger-full-access need no writable-root list.

Package sandbox defines process confinement, following upstream sandbox and sandbox-policy (M26). Modes constrain filesystem effects only. Each call resolves a complete execution policy, including workspaceRoot even in danger mode. Bash and filesystem consumers share policy resolution to keep mode precedence and root fallback consistent. Confine applies only to constrained modes and must fail closed with SANDBOX_UNAVAILABLE if no backend exists.

Session sandbox overrides are persisted through sandbox/mode events, following upstream sandbox-policy/session-mode.ts. These log-only events stay out of the model transcript; the latest mode overrides deployment defaults. Replay restores state without cross-session configuration. The delegation source marks overrides installed for subagents; policy resolution consumes the same persisted state.

Index

Constants

View Source
const SandboxUnavailableErrorCode = "SANDBOX_UNAVAILABLE"

SandboxUnavailableErrorCode is the stable unavailable-backend error code.

Variables

View Source
var (
	// ErrEscalationNotWider indicates the target is not strictly wider than the effective mode.
	ErrEscalationNotWider = errors.New("escalation not strictly wider")
	// ErrEscalationNoApprover indicates missing approval service; escalation fails closed.
	ErrEscalationNoApprover = errors.New("escalation requires approval, but no approver is available")
	// ErrEscalationRejected indicates user rejection.
	ErrEscalationRejected = errors.New("escalation rejected by user")
	// ErrEscalationCancelled indicates canceled approval.
	ErrEscalationCancelled = errors.New("escalation approval cancelled")
	// ErrEscalationUnavailable indicates an unavailable approval channel.
	ErrEscalationUnavailable = errors.New("escalation requires approval, but no approval channel is available")
)
View Source
var InvariantEnabled = true

InvariantEnabled defaults to true for development checks. Production callers may set it false to skip validation.

SandboxModes lists valid modes for option advertising and runtime validation.

Functions

func AssertConfinedArgv

func AssertConfinedArgv(result ConfinedArgv)

AssertConfinedArgv checks that the provider returned a valid, nonempty command.

func AssertConfinedPolicy

func AssertConfinedPolicy(policy SandboxPolicy)

AssertConfinedPolicy validates fields of a confined SandboxPolicy.

func AssertEscalationTarget

func AssertEscalationTarget(target SandboxMode)

AssertEscalationTarget validates membership in the closed escalation target set.

func AssertExecutionPolicy

func AssertExecutionPolicy(policy SandboxExecutionPolicy)

AssertExecutionPolicy checks execution-policy field consistency.

func AssertNotDangerBeforeConfine

func AssertNotDangerBeforeConfine(mode SandboxMode)

AssertNotDangerBeforeConfine rejects danger mode before ToConfined.

func AssertValidMode

func AssertValidMode(mode SandboxMode)

AssertValidMode validates a sandbox mode.

func AssertWritableRoots

func AssertWritableRoots(mode SandboxMode, roots []string)

AssertWritableRoots requires roots for workspace-write and none for other modes.

func BwrapProfileArgs

func BwrapProfileArgs(policy SandboxPolicy) []string

BwrapProfileArgs returns arguments between the runner and command separator. All modes mount / read-only, provide /dev and /proc, isolate PIDs, and enable die-with-parent. Workspace-write also mounts a writable /tmp tmpfs and binds the workspace root read-write.

func CanEscalateTo

func CanEscalateTo(effectiveMode, targetMode SandboxMode) bool

CanEscalateTo permits strictly wider modes only, never equal or narrower modes. Danger-full-access is the terminal mode.

func CanonicalPath

func CanonicalPath(path string) string

CanonicalPath resolves symlinks to match the paths used by Seatbelt and filesystem containment checks. On failure it returns the original path: a missing root grants nothing until it exists, while inventing a fallback could grant a path the caller never named.

func EscalationHintMarker

func EscalationHintMarker(subject string) string

EscalationHintMarker provides an immediate retry hint when escalation fields are advertised: repeat the same operation with the narrowest sufficient wider sandbox_permissions and a justification. Subject names the operation family: command for Bash or operation for filesystem tools.

func LandlockProfileArgs

func LandlockProfileArgs(policy SandboxPolicy) []string

LandlockProfileArgs builds launcher readOnly/readWrite grants. Read-only permits reads under / and writes to /dev/null, required by many programs. Workspace-write additionally permits /tmp and the workspace root.

func SandboxDenialMarker

func SandboxDenialMarker(mode SandboxMode) string

SandboxDenialMarker is shared by Bash and filesystem enforcement so the model recognizes policy denials consistently, whether imposed by the kernel or filesystem mutation guards.

func SeatbeltProfileArgs

func SeatbeltProfileArgs(policy SandboxPolicy) []string

SeatbeltProfileArgs returns -p and an SBPL script. The script enables version 1, allows defaults, denies file-write operations, then permits /dev/null writes. Workspace-write also allows writes under the workspace root.

func SetSandboxMode

func SetSandboxMode(sess SessionAppender, mode SandboxMode) error

SetSandboxMode is the sole write path for session overrides: append a sandbox/mode event without out-of-band state. Consumers fold the log for each Bash/filesystem call, so the change affects the next invocation.

func SetSandboxModeWithSource

func SetSandboxModeWithSource(sess SessionAppender, mode SandboxMode, source ModeSource) error

SetSandboxModeWithSource also records provenance, such as delegation.

func ValidateEscalationArgs

func ValidateEscalationArgs(sandboxPermissions, justification string) error

ValidateEscalationArgs requires sandbox_permissions and justification together or neither; justification must remain nonempty after trimming. An unexplained approval request or an unused justification is malformed.

func WritableRoots

func WritableRoots(policy SandboxExecutionPolicy) []string

WritableRoots returns canonical, deduplicated write grants. Read-only returns none. Workspace-write includes the policy workspace, /tmp, and os.TempDir so platform temporary-file creation remains permitted. Danger-full-access bypasses confinement and needs no root list.

Types

type BackendType

type BackendType string

BackendType identifies a local sandbox backend.

const (
	// BackendBwrap selects Linux Bubblewrap.
	BackendBwrap BackendType = "bwrap"
	// BackendLandlock selects Linux Landlock.
	BackendLandlock BackendType = "landlock"
	// BackendSeatbelt selects macOS Seatbelt.
	BackendSeatbelt BackendType = "seatbelt"
	// BackendWindowsACL selects Windows ACL confinement.
	BackendWindowsACL BackendType = "windows-acl"
	// BackendUnavailable indicates no usable local backend.
	BackendUnavailable BackendType = "unavailable"
)

type ConfinedArgv

type ConfinedArgv struct {
	// Argv combines runner, profile, separator, and original command arguments.
	Argv []string `json:"argv"`
	// Enforcement reports the backend's coverage for this policy.
	Enforcement SandboxEnforcement `json:"enforcement"`
	// DenialSignatures contains backend-specific stderr denial substrings.
	DenialSignatures []string `json:"denialSignatures"`
	// RunnerFailureRules contains structured evidence of runner failure.
	RunnerFailureRules []RunnerFailureRule `json:"runnerFailureRules"`
}

ConfinedArgv contains wrapped argv, achieved enforcement, and independent stderr classifiers for denials and runner failures.

type ConfinedSandboxMode

type ConfinedSandboxMode string

ConfinedSandboxMode excludes danger-full-access. Danger-mode consumers execute their original argv directly without calling the sandbox provider.

const (
	ConfinedReadOnly       ConfinedSandboxMode = "read-only"
	ConfinedWorkspaceWrite ConfinedSandboxMode = "workspace-write"
)

Supported confined modes.

type EscalationApprovalRequest

type EscalationApprovalRequest struct {
	// ToolName records the requested tool.
	ToolName string
	// CallID identifies the call associated with the approval prompt.
	CallID string
	// Reason combines the target mode and justification for auditing.
	Reason string
}

EscalationApprovalRequest includes attribution, tool, call ID, and rationale for auditing.

type EscalationApprover

type EscalationApprover interface {
	// Request asks for one operation's approval and returns a closed-set outcome.
	Request(ctx context.Context, req EscalationApprovalRequest) (EscalationOutcome, error)
}

EscalationApprover is supplied by the tool layer. This package interprets results without importing the approval or agent packages.

type EscalationOutcome

type EscalationOutcome string

EscalationOutcome is the closed set of approval outcomes, matching ApprovalOutcome.

const (
	// EscalationAllowedOnce grants only the current invocation, not permanent access.
	EscalationAllowedOnce EscalationOutcome = "allowed-once"
	// EscalationRejected indicates user rejection.
	EscalationRejected EscalationOutcome = "rejected"
	// EscalationCancelled indicates canceled approval.
	EscalationCancelled EscalationOutcome = "cancelled"
	// EscalationUnavailable indicates an unavailable approval channel.
	EscalationUnavailable EscalationOutcome = "unavailable"
)

type EscalationRequest

type EscalationRequest struct {
	// RequestedMode is the schema-constrained target from EscalationTargets.
	RequestedMode SandboxMode
	// Justification is the model's rationale, shown unchanged within the audit reason.
	Justification string
	// EffectiveMode is the session override or composition default; the target must be wider.
	EffectiveMode SandboxMode
	// Subject names the operation family in user-facing text: command or operation.
	Subject string
	// ToolName is recorded in the approval request.
	ToolName string
	// CallID identifies the tool call attached to the approval prompt.
	CallID string
}

EscalationRequest is evaluated by ApproveEscalation.

type LocalConfig

type LocalConfig struct {
	// RunnerCommand overrides detection, for example bwrap or sandbox-exec.
	// A nonempty command is used directly without probing.
	RunnerCommand string
	// BackendType selects the backend explicitly with RunnerCommand.
	BackendType BackendType
}

LocalConfig configures LocalProvider.

type LocalProvider

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

LocalProvider implements SandboxProvider by probing supported backends for the current platform.

func NewLocalProvider

func NewLocalProvider(config *LocalConfig) *LocalProvider

NewLocalProvider creates a local provider; nil config enables automatic detection.

func (*LocalProvider) Available

func (p *LocalProvider) Available() bool

Available reports whether a local sandbox backend is available.

func (*LocalProvider) Backend

func (p *LocalProvider) Backend() BackendType

Backend returns the detected backend type.

func (*LocalProvider) Confine

func (p *LocalProvider) Confine(argv []string, policy SandboxPolicy) (ConfinedArgv, error)

Confine implements SandboxProvider by building backend-specific command arguments.

func (*LocalProvider) DenialSignatures

func (p *LocalProvider) DenialSignatures() []string

DenialSignatures returns backend denial strings for failure matching.

func (*LocalProvider) Runner

func (p *LocalProvider) Runner() string

Runner returns the detected runner command.

type ModeSource

type ModeSource string

ModeSource identifies the origin of a sandbox/mode event.

const (
	// ModeSourceDelegation marks an override installed during subagent delegation.
	ModeSourceDelegation ModeSource = "delegation"
)

type RunnerFailureRule

type RunnerFailureRule struct {
	// AllowedExitCodes optionally restricts matching to listed nonzero exit codes.
	AllowedExitCodes []int `json:"allowedExitCodes,omitempty"`
	// FatalSignatures are case-insensitive diagnostic substrings on individual stderr lines.
	FatalSignatures []string `json:"fatalSignatures"`
	// InformationalLines excludes harmless case-insensitive whole-line matches before fatal checks.
	InformationalLines []string `json:"informationalLines,omitempty"`
}

RunnerFailureRule identifies runner failure before the command executes.

func (RunnerFailureRule) Matches

func (r RunnerFailureRule) Matches(exitCode int, stderr string) (string, bool)

Matches checks the exit code, excludes informational lines, then searches for fatal substrings.

type SandboxEnforcement

type SandboxEnforcement string

SandboxEnforcement reports actual coverage. Full covers all filesystem effects promised by the mode; partial covers only a subset because of backend or kernel limitations. Consumers needing strict boundaries must reject partial.

const (
	EnforcementFull    SandboxEnforcement = "full"
	EnforcementPartial SandboxEnforcement = "partial"
)

Enforcement levels.

type SandboxExecutionPolicy

type SandboxExecutionPolicy struct {
	// Mode selects filesystem effects for this execution.
	Mode SandboxMode `json:"mode"`
	// WorkspaceRoot is the absolute writable workspace root.
	WorkspaceRoot string `json:"workspaceRoot"`
	// SessionID identifies the calling session; empty gives agentless calls per-call backend state.
	SessionID brand.SessionID `json:"sessionId,omitempty"`
}

SandboxExecutionPolicy is the resolved filesystem policy for one capability call. It retains workspaceRoot in danger mode so consumers resolve once before choosing the execution path.

func (SandboxExecutionPolicy) IsDanger

func (p SandboxExecutionPolicy) IsDanger() bool

IsDanger reports whether to bypass confinement and spawn the original argv.

func (SandboxExecutionPolicy) ToConfined

func (p SandboxExecutionPolicy) ToConfined() (SandboxPolicy, error)

ToConfined converts execution policy after the caller has excluded danger mode.

type SandboxMode

type SandboxMode string

SandboxMode constrains filesystem side effects.

const (
	ModeReadOnly         SandboxMode = "read-only"
	ModeWorkspaceWrite   SandboxMode = "workspace-write"
	ModeDangerFullAccess SandboxMode = "danger-full-access"
)

Modes match pkg/session.SandboxMode.

func ApproveEscalation

func ApproveEscalation(ctx context.Context, req EscalationRequest, approver EscalationApprover) (SandboxMode, error)

ApproveEscalation resolves escalation before execution: validate strict widening without prompting for invalid targets, validate paired arguments, require an approver, then map the result to a granted mode or precise error. The returned grant applies only to the requesting invocation.

func EffectiveSandboxMode

func EffectiveSandboxMode(events []session.SessionEvent) (SandboxMode, bool)

EffectiveSandboxMode scans backward for the latest sandbox/mode event, returning ok false if absent. It is a pure fold, so resume requires only replaying the log rather than a separate catch-up mechanism.

func EscalationTargets

func EscalationTargets() []SandboxMode

EscalationTargets returns workspace-write and danger-full-access for capability schemas. Read-only is the baseline, never an escalation target.

type SandboxPolicy

type SandboxPolicy struct {
	SandboxExecutionPolicy
	// Mode is restricted to read-only or workspace-write.
	Mode ConfinedSandboxMode `json:"mode"`
}

SandboxPolicy carries the boundary for each confined call, not fixed backend state.

type SandboxPolicyRequest

type SandboxPolicyRequest struct {
	// Session supplies the immutable working-directory boundary.
	Session Session
	// Mode is an explicit approved override taking precedence over session policy.
	Mode *SandboxMode
}

SandboxPolicyRequest supplies inputs for resolving one capability call's policy.

type SandboxPolicyService

type SandboxPolicyService struct {
	// DefaultMode is the deployment default, including agentless calls.
	DefaultMode SandboxMode
	// FallbackRoot is the workspace root for agentless sessions or missing cwd.
	FallbackRoot string
}

SandboxPolicyService implements ctx.sandboxPolicy, sharing mode precedence and root fallback between Bash and filesystem consumers.

func NewPolicyService

func NewPolicyService(defaultMode SandboxMode, fallbackRoot string) *SandboxPolicyService

NewPolicyService creates a policy resolver.

func (*SandboxPolicyService) OverrideOf

func (s *SandboxPolicyService) OverrideOf(session Session) (SandboxMode, bool)

OverrideOf reads only the session override, returning ok false rather than applying defaults.

func (*SandboxPolicyService) Resolve

Resolve selects a complete policy for one call. Precedence is explicit req.Mode, latest logged session mode, then deployment default. The root is the canonical session cwd or the configured agentless fallback.

type SandboxProvider

type SandboxProvider interface {
	// Confine wraps argv under the policy and must fail closed on missing backends
	// or wrapping errors; it must never silently execute without confinement.
	Confine(argv []string, policy SandboxPolicy) (ConfinedArgv, error)
}

SandboxProvider abstracts process confinement through ctx.sandbox.

type SandboxUnavailableError

type SandboxUnavailableError struct {
	Msg string
}

SandboxUnavailableError indicates no usable backend.

func (*SandboxUnavailableError) Error

func (e *SandboxUnavailableError) Error() string

type Session

type Session interface {
	// ID returns the branded session identifier.
	ID() brand.SessionID
	// Cwd returns the immutable workspace boundary, or empty if absent.
	Cwd() string
	// SandboxMode returns the latest logged override, with ok false if absent.
	SandboxMode() (SandboxMode, bool)
}

Session exposes the immutable working directory as the workspace boundary and the last logged sandbox mode as a session override.

type SessionAppender

type SessionAppender interface {
	Append(data session.EventData) (uint64, error)
}

SessionAppender abstracts event appends and is implemented by SessionLog.

type UnavailableProvider

type UnavailableProvider struct{}

UnavailableProvider always fails closed with SANDBOX_UNAVAILABLE and is the production fallback when no backend is available.

func (*UnavailableProvider) Confine

Confine always reports unavailable, enforcing fail-closed behavior.

Jump to

Keyboard shortcuts

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