Documentation
¶
Overview ¶
Package sonnetbox evaluates untrusted Jsonnet programs in fresh WebAssembly guests.
An Engine compiles the embedded go-jsonnet guest once and creates an isolated guest instance for each evaluation. Engines are safe for concurrent use and should normally be long-lived:
engine, err := sonnetbox.NewEngine(ctx, sonnetbox.EngineConfig{})
if err != nil {
return err
}
defer engine.Close(context.Background())
result, err := engine.Evaluate(ctx, sonnetbox.Request{
Filename: "main.jsonnet",
Source: `{answer: 6 * 7}`,
})
Jsonnet code has no ambient access to the host filesystem, network, environment, arguments, or standard streams. A request can grant read-only virtual imports through an Importer and pure native functions through Capability. Both are trusted host code; implementations must honor context cancellation and the concurrency contracts documented on those types.
EngineConfig sets engine-wide resource ceilings. A Request can lower most ceilings for one evaluation through RequestLimits, but cannot raise them. Context cancellation provides the wall-clock backstop.
Example ¶
package main
import (
"context"
"fmt"
"github.com/thevilledev/sonnetbox"
)
func main() {
ctx := context.Background()
engine, err := sonnetbox.NewEngine(ctx, sonnetbox.EngineConfig{})
if err != nil {
panic(err)
}
defer func() {
if err := engine.Close(context.Background()); err != nil {
panic(err)
}
}()
result, err := engine.Evaluate(ctx, sonnetbox.Request{
Filename: "main.jsonnet",
Source: `{answer: 6 * 7}`,
})
if err != nil {
panic(err)
}
fmt.Print(string(result.Output))
}
Output: { "answer": 42 }
Index ¶
- Variables
- type ABIError
- type CancellationError
- type Capability
- type CapabilityError
- type Engine
- func (e *Engine) Close(ctx context.Context) error
- func (e *Engine) Evaluate(ctx context.Context, request Request) (Result, error)
- func (e *Engine) EvaluateAnonymous(ctx context.Context, request Request) (Result, error)
- func (e *Engine) EvaluateFile(ctx context.Context, filename string, request Request) (Result, error)
- type EngineClosedError
- type EngineConfig
- type EvaluationError
- type EvaluationStats
- type GuestTrapError
- type ImportDeniedError
- type ImportError
- type Importer
- type InvalidRequestError
- type LimitError
- type MapImporter
- type OutputMode
- type Request
- type RequestLimits
- type Result
- type VersionInfo
- type WorkspaceImporter
- type WorkspaceOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrImportDenied = errors.New("import denied")
ErrImportDenied can be returned by a custom Importer when a path is absent or rejected by policy.
Functions ¶
This section is empty.
Types ¶
type ABIError ¶
type ABIError struct {
// Err describes the protocol or guest artifact failure.
Err error
}
ABIError reports a malformed or incompatible guest/host ABI.
type CancellationError ¶
type CancellationError struct {
// Err is the context cancellation cause.
Err error
}
CancellationError reports evaluation cancellation or deadline expiry.
func (*CancellationError) Error ¶
func (e *CancellationError) Error() string
func (*CancellationError) Unwrap ¶
func (e *CancellationError) Unwrap() error
type Capability ¶
type Capability struct {
// Params lists the Jsonnet function's parameter names.
Params []string
// Call executes trusted host code with JSON-compatible arguments and must
// honor context cancellation.
Call func(context.Context, []any) (any, error)
}
Capability defines a pure Jsonnet native function. Call may execute zero, one, or multiple times and may be called concurrently by separate evaluations.
type CapabilityError ¶
type CapabilityError struct {
// Name identifies the failed capability when one is available.
Name string
// Err is the underlying trusted capability failure.
Err error
}
CapabilityError reports a trusted capability failure.
func (*CapabilityError) Error ¶
func (e *CapabilityError) Error() string
func (*CapabilityError) Unwrap ¶
func (e *CapabilityError) Unwrap() error
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine owns a compiled guest module and instantiates a fresh guest for every evaluation. An Engine is safe for concurrent use and must be closed when it is no longer needed.
func NewEngine ¶
func NewEngine(ctx context.Context, config EngineConfig) (*Engine, error)
NewEngine compiles the embedded guest and prepares an isolated Jsonnet engine. Zero-valued config fields select documented defaults. The context controls initialization and is not retained; callers must close the returned Engine.
func (*Engine) Close ¶
Close rejects new evaluations and closes the runtime. It is idempotent and aborts active guest calls.
func (*Engine) Evaluate ¶
Evaluate evaluates Request.Source in a fresh guest instance, using Request.Filename as the base for relative imports. It is safe to call concurrently.
func (*Engine) EvaluateAnonymous ¶
EvaluateAnonymous evaluates Request.Source in a fresh guest instance. Request.Filename is used only for diagnostics; imports are resolved from the importer's root.
func (*Engine) EvaluateFile ¶
func (e *Engine) EvaluateFile( ctx context.Context, filename string, request Request, ) (Result, error)
EvaluateFile loads filename through Request.Importer and evaluates it in a fresh guest instance. The filename must be a canonical virtual path, and Request.Source must be empty.
type EngineClosedError ¶
type EngineClosedError struct {
// Err is the underlying runtime error when an active evaluation was
// interrupted by Close.
Err error
}
EngineClosedError reports an evaluation attempted after Engine.Close.
func (*EngineClosedError) Error ¶
func (e *EngineClosedError) Error() string
func (*EngineClosedError) Unwrap ¶
func (e *EngineClosedError) Unwrap() error
type EngineConfig ¶
type EngineConfig struct {
// MaxMemoryBytes limits each guest's linear memory. It must be a multiple
// of 64 KiB.
MaxMemoryBytes uint64
// MaxFuel limits deterministic WebAssembly instruction work during one
// evaluation.
MaxFuel uint64
// MaxSourceBytes limits Request.Source in bytes.
MaxSourceBytes uint32
// MaxOutputBytes limits the rendered result in bytes.
MaxOutputBytes uint32
// MaxStack limits go-jsonnet interpreter stack depth.
MaxStack int
// MaxImports limits import resolutions during one evaluation.
MaxImports uint32
// MaxImportBytes limits one imported file in bytes.
MaxImportBytes uint32
// MaxTotalImportBytes limits all imported content during one evaluation.
MaxTotalImportBytes uint64
// MaxCapabilityCalls limits native capability calls during one evaluation.
MaxCapabilityCalls uint32
// MaxHostRequestBytes limits encoded requests crossing from guest to host
// and the encoded evaluation request crossing from host to guest.
MaxHostRequestBytes uint32
// MaxHostResponseBytes limits encoded responses crossing from host to
// guest. Import content is base64-encoded within this limit. Nonzero values
// must be at least 256 bytes.
MaxHostResponseBytes uint32
// MaxTraceBytes limits captured std.trace output during one evaluation.
MaxTraceBytes uint32
// MaxConcurrentEvaluations limits active guest instances. Additional
// evaluations wait for capacity while honoring context cancellation.
MaxConcurrentEvaluations uint32
}
EngineConfig sets resource ceilings for an Engine. A zero field selects the documented default for that field.
type EvaluationError ¶
type EvaluationError struct {
// Err contains the evaluator's diagnostic.
Err error
}
EvaluationError reports a static or runtime Jsonnet evaluation error.
func (*EvaluationError) Error ¶
func (e *EvaluationError) Error() string
func (*EvaluationError) Unwrap ¶
func (e *EvaluationError) Unwrap() error
type EvaluationStats ¶
type EvaluationStats struct {
// QueueDuration is the time spent waiting for an engine concurrency slot.
QueueDuration time.Duration
// ExecutionDuration is the time from acquiring a slot through decoding the
// completed guest result.
ExecutionDuration time.Duration
// FuelConsumed is the deterministic WebAssembly instruction work used.
FuelConsumed uint64
// ImportResolutions is the number of import requests made by the guest.
ImportResolutions uint32
// ImportBytes is the cumulative size of imported content.
ImportBytes uint64
// CapabilityCalls is the number of native capability calls.
CapabilityCalls uint32
// TraceBytes is the number of captured std.trace bytes.
TraceBytes uint32
// TraceTruncated reports whether trace output exceeded its configured
// limit.
TraceTruncated bool
}
EvaluationStats reports work for a successful evaluation. FuelConsumed is deterministic for the same guest and input; durations and other host-observed counters are diagnostic.
type GuestTrapError ¶
type GuestTrapError struct {
// Operation identifies the guest operation that trapped.
Operation string
// Err is the underlying WebAssembly runtime error.
Err error
}
GuestTrapError reports an unexpected WASM trap.
func (*GuestTrapError) Error ¶
func (e *GuestTrapError) Error() string
func (*GuestTrapError) Unwrap ¶
func (e *GuestTrapError) Unwrap() error
type ImportDeniedError ¶
type ImportDeniedError struct {
// ImportedFrom is the canonical path of the importing file, or empty when
// resolving from the importer root.
ImportedFrom string
// ImportedPath is the path requested by Jsonnet.
ImportedPath string
// Err describes the policy denial or missing path.
Err error
}
ImportDeniedError reports an import rejected by policy or not found.
func (*ImportDeniedError) Error ¶
func (e *ImportDeniedError) Error() string
func (*ImportDeniedError) Unwrap ¶
func (e *ImportDeniedError) Unwrap() error
type ImportError ¶
type ImportError struct {
// ImportedFrom is the canonical path of the importing file, or empty when
// resolving from the importer root.
ImportedFrom string
// ImportedPath is the path requested by Jsonnet.
ImportedPath string
// Err is the underlying trusted importer failure.
Err error
}
ImportError reports a trusted importer failure.
func (*ImportError) Error ¶
func (e *ImportError) Error() string
func (*ImportError) Unwrap ¶
func (e *ImportError) Unwrap() error
type Importer ¶
type Importer interface {
// Import resolves importedPath relative to importedFrom. It returns a
// canonical virtual path and its content. The content returned for a
// canonical path must remain stable during an evaluation.
Import(
ctx context.Context,
importedFrom string,
importedPath string,
) (canonicalPath string, content []byte, err error)
}
Importer resolves a Jsonnet import without granting guest filesystem access. Implementations are trusted host code and must be safe for concurrent calls from separate evaluations. They should return errors wrapping ErrImportDenied for paths that are absent or rejected by policy.
type InvalidRequestError ¶
type InvalidRequestError struct {
// Field identifies the rejected public field when one is available.
Field string
// Err describes why the request, context, or configuration was invalid.
Err error
}
InvalidRequestError reports an invalid public request, context, or engine configuration.
func (*InvalidRequestError) Error ¶
func (e *InvalidRequestError) Error() string
func (*InvalidRequestError) Unwrap ¶
func (e *InvalidRequestError) Unwrap() error
type LimitError ¶
type LimitError struct {
// Resource identifies the exhausted resource.
Resource string
// Limit is the configured maximum.
Limit uint64
// Actual is the observed or attempted resource use.
Actual uint64
// Err is the underlying runtime error, when one is available.
Err error
}
LimitError reports a configured resource limit.
func (*LimitError) Error ¶
func (e *LimitError) Error() string
func (*LimitError) Unwrap ¶
func (e *LimitError) Unwrap() error
type MapImporter ¶
type MapImporter struct {
// contains filtered or unexported fields
}
MapImporter resolves imports from an immutable map of canonical virtual paths.
func NewMapImporter ¶
func NewMapImporter(files map[string][]byte) (*MapImporter, error)
NewMapImporter returns an immutable virtual-file importer. It validates all paths and copies all content before returning.
type OutputMode ¶
type OutputMode uint8
OutputMode selects how the top-level Jsonnet value is manifested.
const ( // OutputModeSingle manifests one JSON value, or one unquoted string when // Request.StringOutput is set. OutputModeSingle OutputMode = iota // OutputModeMulti manifests a top-level object as filename/output pairs. OutputModeMulti // OutputModeStream manifests a top-level array as a sequence of documents. OutputModeStream )
type Request ¶
type Request struct {
// Filename is the virtual, canonical filename used in diagnostics and
// relative imports. An empty value selects "snippet.jsonnet".
Filename string
// Source is the adversarial Jsonnet program to evaluate.
Source string
// ExtVars supplies string external variables.
ExtVars map[string]string
// ExtCode supplies Jsonnet-code external variables.
ExtCode map[string]string
// TLAVars supplies string top-level arguments.
TLAVars map[string]string
// TLACode supplies Jsonnet-code top-level arguments.
TLACode map[string]string
// Importer resolves virtual imports. A nil Importer denies all imports.
Importer Importer
// Capabilities exposes only these request-scoped native functions.
Capabilities map[string]Capability
// Limits optionally lowers this evaluation's resource limits.
Limits RequestLimits
// OutputMode selects single, multi-file, or stream manifestation.
OutputMode OutputMode
// StringOutput returns a top-level Jsonnet string without JSON quoting.
// It applies to single and multi-file output.
StringOutput bool
// OmitTrailingNewline disables go-jsonnet's default output newline.
OmitTrailingNewline bool
// CaptureTrace returns bounded std.trace output in Result.Trace.
CaptureTrace bool
}
Request describes one isolated Jsonnet evaluation.
type RequestLimits ¶
type RequestLimits struct {
// MaxFuel lowers EngineConfig.MaxFuel.
MaxFuel uint64
// MaxSourceBytes lowers EngineConfig.MaxSourceBytes.
MaxSourceBytes uint32
// MaxOutputBytes lowers EngineConfig.MaxOutputBytes.
MaxOutputBytes uint32
// MaxStack lowers EngineConfig.MaxStack.
MaxStack int
// MaxImports lowers EngineConfig.MaxImports.
MaxImports uint32
// MaxImportBytes lowers EngineConfig.MaxImportBytes.
MaxImportBytes uint32
// MaxTotalImportBytes lowers EngineConfig.MaxTotalImportBytes.
MaxTotalImportBytes uint64
// MaxCapabilityCalls lowers EngineConfig.MaxCapabilityCalls.
MaxCapabilityCalls uint32
// MaxHostRequestBytes lowers EngineConfig.MaxHostRequestBytes.
MaxHostRequestBytes uint32
// MaxHostResponseBytes lowers EngineConfig.MaxHostResponseBytes.
MaxHostResponseBytes uint32
// MaxTraceBytes lowers EngineConfig.MaxTraceBytes.
MaxTraceBytes uint32
}
RequestLimits lowers resource limits for one evaluation. A zero field inherits the corresponding EngineConfig ceiling. A nonzero field cannot exceed that ceiling.
type Result ¶
type Result struct {
// Output contains single-mode rendered JSON or StringOutput bytes.
Output []byte
// Files contains multi-mode rendered outputs keyed by filename.
Files map[string][]byte
// Documents contains stream-mode rendered documents in source order.
Documents [][]byte
// Trace contains captured std.trace output.
Trace []byte
// Stats reports bounded host-observed evaluation work.
Stats EvaluationStats
}
Result is a completed Jsonnet evaluation. The request's OutputMode selects Output, Files, or Documents for the manifested value.
type VersionInfo ¶
type VersionInfo struct {
// Jsonnet is the embedded go-jsonnet semantic version.
Jsonnet string
// ABI is the private sonnetbox host/guest protocol version.
ABI uint32
}
VersionInfo identifies the evaluator and private host/guest ABI.
func Version ¶
func Version() VersionInfo
Version reports the embedded go-jsonnet evaluator and private host/guest ABI versions.
type WorkspaceImporter ¶
type WorkspaceImporter struct {
// contains filtered or unexported fields
}
WorkspaceImporter exposes read-only files beneath one host directory. It prevents relative paths and symlinks from escaping that directory.
func NewWorkspaceImporter ¶
func NewWorkspaceImporter( rootPath string, options ...WorkspaceOption, ) (*WorkspaceImporter, error)
NewWorkspaceImporter opens a traversal-resistant, read-only workspace root.
func (*WorkspaceImporter) Close ¶
func (w *WorkspaceImporter) Close() error
Close releases the workspace root. It is idempotent.
type WorkspaceOption ¶
type WorkspaceOption func(*workspaceConfig) error
WorkspaceOption configures a WorkspaceImporter.
func WithLibraryPaths ¶
func WithLibraryPaths(paths ...string) WorkspaceOption
WithLibraryPaths adds virtual Jsonnet library paths. They are searched in reverse order after resolution relative to the importing file, matching go-jsonnet FileImporter precedence.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
sonnetbox
command
Command sonnetbox evaluates Jsonnet in a fresh WebAssembly sandbox.
|
Command sonnetbox evaluates Jsonnet in a fresh WebAssembly sandbox. |
|
sonnetbox-guest
command
Package main builds the embedded sonnetbox WASI guest.
|
Package main builds the embedded sonnetbox WASI guest. |
|
compat
|
|
|
gojsonnet
Package gojsonnet provides an opt-in migration surface shaped like the common github.com/google/go-jsonnet VM API.
|
Package gojsonnet provides an opt-in migration surface shaped like the common github.com/google/go-jsonnet VM API. |
|
examples
|
|
|
config-renderer
command
Command config-renderer renders a file from a read-only Jsonnet workspace.
|
Command config-renderer renders a file from a read-only Jsonnet workspace. |
|
hello
command
Command hello demonstrates one isolated inline Jsonnet evaluation.
|
Command hello demonstrates one isolated inline Jsonnet evaluation. |
|
http-service
command
Command http-service exposes bounded Jsonnet evaluation over HTTP.
|
Command http-service exposes bounded Jsonnet evaluation over HTTP. |
|
internal
|
|
|
cli
Package cli implements the secure sonnetbox command-line interface.
|
Package cli implements the secure sonnetbox command-line interface. |
|
guestblob
Package guestblob embeds the reproducibly built Jsonnet WASI guest.
|
Package guestblob embeds the reproducibly built Jsonnet WASI guest. |
|
protocol
Package protocol defines the private host-to-guest wire protocol.
|
Package protocol defines the private host-to-guest wire protocol. |