sandbox

package
v0.72.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sandbox runs a script in a child process under an OS memory limit and carries its tool calls back to the parent.

Starlark checks its step budget and cancellation only between steps, and a single expression such as "a" * 1_000_000_000 allocates its whole result in one step, so no in-process check can stop it. The child process is started from the same executable; it limits its own memory before it reads the script, runs it, and asks the parent to make every tool call. The parent keeps the caller's identity and credentials, authorizes and makes each call, and treats everything the child sends as untrusted.

The two processes exchange newline-delimited JSON messages over the child's stdin and stdout, each at most MaxMessageBytes long.

Index

Constants

View Source
const Arg = "__toolhive_script_sandbox__"

Arg is the first argument that starts an executable as a sandbox child. The script package checks for it at init, before main runs.

View Source
const MaxMessageBytes = 8 << 20

MaxMessageBytes caps one protocol message: the script and its data, a tool result, or the script's result. It matches the server's default request body limit. The child holds about three copies of a message while it decodes one (the line, the decoded value, the Starlark value), which fits in its memory limit next to the Go runtime's own share, and the parent's buffers stay small whatever the child sends.

View Source
const MemoryLimitEnforced = true

MemoryLimitEnforced reports whether the OS enforces the sandbox memory limit on this platform.

View Source
const MinMemoryLimit = 32 << 20

MinMemoryLimit is the smallest memory limit Run accepts: below it the Go runtime of the child has too little room to run a script.

Variables

View Source
var ErrCrashed = errors.New("script sandbox crashed")

ErrCrashed marks a child that exited without a result for a reason Run cannot name. The Go runtime does not always report a refused memory request as running out of memory (it can also fault), so this can be the memory limit too.

View Source
var ErrMemoryLimitExceeded = errors.New("script exceeded its memory limit")

ErrMemoryLimitExceeded marks a script the OS stopped because it used more memory than the sandbox allows.

View Source
var ErrMessageTooLarge = fmt.Errorf("sandbox message is larger than %d MiB", MaxMessageBytes>>20)

ErrMessageTooLarge is returned when a message is longer than MaxMessageBytes.

Functions

func DecodeData

func DecodeData(raw json.RawMessage) (any, error)

DecodeData decodes plain JSON, such as Start.Data, with every number as a json.Number.

func DecodeValue

func DecodeValue(raw json.RawMessage) (any, error)

DecodeValue decodes a value encoded with EncodeValue. Numbers come back as int64 when they are integers in its range and as float64 otherwise.

func EncodeData

func EncodeData(data map[string]any) (json.RawMessage, error)

EncodeData encodes a script's data arguments for Start.Data so that the engine in the child sees the values it would see in this process. The engine turns a whole float64 below 2^53 into an int and keeps any other float64 a float, and converts a json.Number by its text; EncodeData writes each float64 as the number text that DecodeData and that conversion turn into the same value. json.Number values pass through unchanged. NaN and infinities have no JSON form and are rejected.

func EncodeValue

func EncodeValue(v any) (json.RawMessage, error)

EncodeValue encodes v, a tool's arguments, as JSON so that DecodeValue gives back the Go types the script engine passes to a tool: integers as int64 and floats as float64, including whole floats such as 1.0, which plain JSON cannot tell apart from integers. Authorization tells them apart (Cedar maps int64 to Long and float64 to Decimal), so a tool argument must cross the boundary unchanged. NaN and infinities have no JSON form and are rejected.

func LimitMemory

func LimitMemory(limit uint64) error

LimitMemory limits the memory the calling process can map to limit bytes above what it has mapped so far, where the OS supports it, and sets the Go runtime's soft limit to three quarters of that growth, so the garbage collector works harder before the hard limit stops the process. The child calls it before it reads the script.

The soft limit starts from the memory the Go runtime accounts for, not from what the process has mapped: the mapped total also counts the executable's data and memory the runtime reserves at startup (tens to hundreds of MiB), so a soft limit measured from it would sit above the hard limit and never engage, leaving the heap to grow to twice its live data.

Types

type Call

type Call struct {
	ID   uint64 `json:"id"`
	Name string `json:"name"`
	// Arguments is the tool's argument map, encoded with EncodeValue.
	Arguments json.RawMessage `json:"arguments,omitempty"`
}

Call asks the parent to call a tool. ID is unique among the child's calls that have not been answered yet.

type CallFunc

type CallFunc func(ctx context.Context, name string, args map[string]any) (json.RawMessage, error)

CallFunc makes one tool call for the child, in the parent. It returns the JSON-encoded mcp.CallToolResult, or an error whose message the script sees.

type Client

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

Client makes tool calls from the child through the parent. Run must be running for a call to get its reply.

func NewClient

func NewClient(conn *Conn) *Client

NewClient returns a Client that talks to the parent over conn.

func (*Client) Call

func (c *Client) Call(ctx context.Context, name string, args map[string]any) (json.RawMessage, error)

Call asks the parent to call the tool name with args, and returns the JSON-encoded mcp.CallToolResult it replies with.

func (*Client) Run

func (c *Client) Run(onClose func())

Run reads the parent's replies and hands each to the call waiting for it, until the connection fails or the parent closes it. It then fails every waiting call and calls onClose, so the script can stop.

type Conn

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

Conn reads and writes protocol messages. Receive must be called from one goroutine at a time; Send is safe for concurrent use.

func NewConn

func NewConn(r io.Reader, w io.Writer) *Conn

NewConn returns a Conn that reads messages from r and writes them to w.

func (*Conn) Receive

func (c *Conn) Receive() (*Message, error)

Receive reads the next message. It returns io.EOF once the other side has closed its end, and ErrMessageTooLarge for a line over the limit.

func (*Conn) Send

func (c *Conn) Send(msg *Message) error

Send writes msg as one line. It returns ErrMessageTooLarge, and writes nothing, if the encoded message is longer than MaxMessageBytes.

type Done

type Done struct {
	Result json.RawMessage `json:"result,omitempty"`
	Error  string          `json:"error,omitempty"`
	// StepLimit reports that the script failed because it used up its step
	// budget.
	StepLimit bool  `json:"stepLimit,omitempty"`
	Stats     Stats `json:"stats"`
}

Done is how the script ended: the JSON-encoded mcp.CallToolResult it returned, or the message of the error it failed with.

func Run

func Run(ctx context.Context, memoryLimit uint64, start *Start, call CallFunc) (*Done, error)

Run runs start in a new child process whose memory is limited to memoryLimit bytes (where the OS supports it; see MemoryLimitEnforced), answering its tool calls with call. It returns the child's Done message.

When ctx is done the child is killed and Run returns ctx.Err(). When the child dies for lack of memory, the error matches ErrMemoryLimitExceeded. The child gets an empty environment, so nothing the parent holds in its environment, such as credentials, reaches the script.

func Serve

func Serve(ctx context.Context, conn *Conn, start *Start, call CallFunc) (*Done, error)

Serve sends start to the child at the other end of conn, answers its tool calls with call, and returns the child's Done message.

The child is untrusted: Serve calls only the tools named in start, answers at most start.ParallelMax calls at a time (when set) holding at most argumentBudget bytes of their arguments, recovers a call that panics, and fails on any message it did not expect. Before it returns, it closes its side of conn, cancels the calls it is still making and waits for them, so call never runs after Serve has returned.

type Message

type Message struct {
	// Start is the parent's first message: the script to run.
	Start *Start `json:"start,omitempty"`
	// Call is the child asking the parent to make a tool call.
	Call *Call `json:"call,omitempty"`
	// Reply is the parent's answer to a Call.
	Reply *Reply `json:"reply,omitempty"`
	// Done is the child's last message: how the script ended.
	Done *Done `json:"done,omitempty"`
}

Message is one protocol message. Exactly one field is set.

type Reply

type Reply struct {
	ID     uint64          `json:"id"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  string          `json:"error,omitempty"`
}

Reply answers the Call with the same ID: either the JSON-encoded mcp.CallToolResult, or the message of the error the call returned.

type Start

type Start struct {
	Script string `json:"script"`
	// Data is the script's data arguments, encoded with EncodeData and
	// decoded with DecodeData.
	Data      json.RawMessage `json:"data,omitempty"`
	Tools     []ToolInfo      `json:"tools,omitempty"`
	StepLimit uint64          `json:"stepLimit,omitempty"`
	// ParallelMax caps how many callables parallel() runs at once, and how
	// many calls the parent answers at once; zero means no cap.
	ParallelMax int `json:"parallelMax,omitempty"`
}

Start carries everything the child needs to run one script.

type Stats

type Stats struct {
	Steps         uint64 `json:"steps,omitempty"`
	ParallelCalls int    `json:"parallelCalls,omitempty"`
	ParallelTasks int    `json:"parallelTasks,omitempty"`
}

Stats mirrors script.Stats.

type ToolInfo

type ToolInfo struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

ToolInfo names a tool the script may call. The child gets no way to call it other than a Call message.

Jump to

Keyboard shortcuts

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