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
- Variables
- func DecodeData(raw json.RawMessage) (any, error)
- func DecodeValue(raw json.RawMessage) (any, error)
- func EncodeData(data map[string]any) (json.RawMessage, error)
- func EncodeValue(v any) (json.RawMessage, error)
- func LimitMemory(limit uint64) error
- type Call
- type CallFunc
- type Client
- type Conn
- type Done
- type Message
- type Reply
- type Start
- type Stats
- type ToolInfo
Constants ¶
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.
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.
const MemoryLimitEnforced = true
MemoryLimitEnforced reports whether the OS enforces the sandbox memory limit on this platform.
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 ¶
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.
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.
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 ¶
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 ¶
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.
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.
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 ¶
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 ¶
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.