rubyeval

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 19 Imported by: ? 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 rubyeval evaluates arbitrary Policyfile.rb files by running CRuby compiled to WebAssembly (the official ruby/ruby.wasm WASI build) under the pure-Go wazero runtime — no system Ruby and no CGo required.

The user's Policyfile.rb is instance_eval'd, inside a real Ruby VM, against a faithful reimplementation of chef-cli's Policyfile DSL (shim.rb). Because the file runs in genuine CRuby, ANY valid Ruby works — loops, conditionals, helper methods, ENV, string interpolation, the stdlib, and require_relative against sibling files. Only the Policyfile DSL *methods* are reimplemented; the language is real. The shim captures every declaration and serializes it to canonical JSON, which Evaluate unmarshals into an EvaluatedPolicy.

See doc.go for the canonical JSON schema, the chef semantics it mirrors, and the evaluation-vs-resolution boundary.

Index

Constants

This section is empty.

Variables

View Source
var ErrRubyWasmMisconfigured = errors.New("configured ruby.wasm runtime is unusable")

ErrRubyWasmMisconfigured marks the subset of ErrRubyWasmUnavailable caused by a runtime directory that was deliberately configured but cannot be used. Callers use it to avoid telling the user to get network access when the fix is to correct the directory.

View Source
var ErrRubyWasmUnavailable = errors.New("policyfile: ruby.wasm runtime is unavailable")

ErrRubyWasmUnavailable wraps any failure to obtain the pinned ruby.wasm (no network, GitHub unreachable, etc.). Tests and the CLI treat it as a "skip cleanly / explain" signal rather than a hard error, so a network-less CI still passes.

Functions

func IsMisconfigured added in v0.24.0

func IsMisconfigured(err error) bool

IsUnavailable reports whether err indicates the ruby.wasm runtime could not be obtained (so callers can skip rather than fail). IsMisconfigured reports whether err is a configured-runtime problem rather than a missing download.

func IsUnavailable

func IsUnavailable(err error) bool

Types

type CookbookSpec

type CookbookSpec struct {
	// VersionConstraint is the Semverse-normalized constraint string.
	VersionConstraint string `json:"version_constraint"`
	// SourceOptions holds per-cookbook source options (path:, git:, ref:,
	// branch:, tag:, …) with symbol keys stringified.
	SourceOptions map[string]any `json:"source_options"`
}

CookbookSpec is one cookbook's declared constraint and source options.

type DefaultSource

type DefaultSource struct {
	// Type is the semantic source type: "community", "chef_server",
	// "chef_repo", "artifactory", or "delivery_supermarket". ":supermarket" and
	// ":community" both map to "community" (chef treats them identically).
	Type string `json:"type"`
	// URI is the source URI for community/chef_server/artifactory/
	// delivery_supermarket sources.
	URI string `json:"uri,omitempty"`
	// Path is the expanded chef-repo path for chef_repo sources.
	Path string `json:"path,omitempty"`
}

DefaultSource is one default_source declaration.

type Dependency

type Dependency struct {
	Name       string
	Constraint string
}

Dependency is one cookbook dependency from a metadata.rb `depends` declaration: the dependency name and its Semverse-normalized version constraint (e.g. ["beta", "~> 1.0"]). The order of a cookbook's Dependencies is the declaration order, matching chef.

type Engine

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

Engine owns the wazero runtime and the compiled CRuby module, which are expensive to build (compilation takes a few seconds) and so are created once and reused across Evaluate calls.

func NewEngine

func NewEngine() *Engine

NewEngine returns an Engine that downloads ruby.wasm over HTTP on first use.

func (*Engine) Available

func (e *Engine) Available() error

Available reports whether the pinned ruby.wasm runtime can be obtained (downloaded or already cached). It returns an error wrapping ErrRubyWasmUnavailable when the runtime cannot be fetched, which callers use to skip cleanly rather than fail. It does not compile the module.

func (*Engine) Evaluate

func (e *Engine) Evaluate(ctx context.Context, source string, opts Options) (*EvaluatedPolicy, error)

Evaluate runs source as a Policyfile.rb and returns the captured declarations.

Evaluation mirrors chef: problems the file would surface (an empty run_list, invalid run_list item names, conflicting sources, a syntax error, or an exception raised by the file) are collected into EvaluatedPolicy.Errors rather than raised. When that slice is non-empty Evaluate also returns a non-nil error summarizing it, while still returning the (partial) policy, so callers can both detect the failure and inspect what was captured.

A returned error wrapping ErrRubyWasmUnavailable means the runtime could not be obtained (e.g. offline); callers should skip/degrade rather than treat it as a Policyfile problem.

func (*Engine) EvaluateFile

func (e *Engine) EvaluateFile(ctx context.Context, path string) (*EvaluatedPolicy, error)

EvaluateFile reads a Policyfile.rb from disk and evaluates it, using its directory for sibling resolution and its basename for backtraces. A denylist-filtered view of the host environment is passed through so dynamic Policyfiles can still read benign vars (ENV[...] behaves as it would for chef), while obviously-sensitive vars (credentials, tokens, keys) are withheld from attacker-controllable Ruby — see sanitizedHostEnv.

func (*Engine) EvaluateFileWithRaw

func (e *Engine) EvaluateFileWithRaw(ctx context.Context, path string) (*EvaluatedPolicy, []byte, error)

EvaluateFileWithRaw is EvaluateFile but also returns the raw canonical JSON the shim emitted. The resolver uses the raw bytes to reproduce chef's exact attribute key ordering in the lock.

func (*Engine) EvaluateMetadata

func (e *Engine) EvaluateMetadata(ctx context.Context, source string, opts Options) (*Metadata, error)

EvaluateMetadata runs a cookbook's metadata.rb source through the embedded CRuby engine and returns its name, version, and dependencies. Because the file runs in a real Ruby VM, any valid Ruby works (version helpers, conditionals, require_relative). Dependency constraints come back normalized by the same Semverse chef uses.

func (*Engine) EvaluateMetadataFile

func (e *Engine) EvaluateMetadataFile(ctx context.Context, path string) (*Metadata, error)

EvaluateMetadataFile reads a cookbook's metadata.rb from disk and evaluates it, using its directory for sibling resolution (require_relative of version helpers, etc.).

Unlike the Policyfile path, cookbook metadata is given NO host environment. metadata.rb has no legitimate need for ENV, and a third-party cookbook's metadata.rb is the primary exfiltration vector (it runs during dependency resolution of any cookbook you depend on), so we deny it the host env entirely. Leaving Options.Env nil makes the guest see an empty ENV.

type EvaluatedPolicy

type EvaluatedPolicy struct {
	// Name is the policy name (the `name` declaration). Empty if unset.
	Name string `json:"name"`

	// RunList is the primary run_list, stored exactly as chef stores it: the
	// raw item strings as written (e.g. "recipe[app::default]", "role[web]"),
	// not normalized to recipe[...] form.
	RunList []string `json:"run_list"`

	// NamedRunLists holds each named_run_list keyed by its name (symbols are
	// stringified, matching chef).
	NamedRunLists map[string][]string `json:"named_run_lists"`

	// DefaultSources lists default_source declarations in order. Each carries a
	// "type" (community/chef_server/chef_repo/artifactory/delivery_supermarket)
	// plus the located option ("uri" or, for chef_repo, an expanded "path").
	DefaultSources []DefaultSource `json:"default_source"`

	// Cookbooks maps cookbook name to its declared version constraint and
	// source options. The constraint is normalized exactly as chef's Semverse
	// does (e.g. ">= 1.0" -> ">= 1.0.0", "~> 2.0" stays "~> 2.0"). Note chef
	// keeps only the FIRST constraint when several are passed.
	Cookbooks map[string]CookbookSpec `json:"cookbooks"`

	// IncludedPolicies lists include_policy declarations.
	IncludedPolicies []IncludedPolicy `json:"included_policies"`

	// DefaultAttributes is the deep-merged tree built from default[...] = ...
	// assignments (string-keyed, autovivified), matching chef's VividMash.
	DefaultAttributes map[string]any `json:"default_attributes"`

	// OverrideAttributes is the same for override[...] = ... assignments.
	OverrideAttributes map[string]any `json:"override_attributes"`

	// Errors holds the validation/evaluation problems chef would record for
	// this file (empty run_list, invalid item names, conflicting sources, a
	// syntax error, or an exception raised by the file). chef does not raise on
	// these — it collects them — and neither does the shim.
	Errors []string `json:"errors"`
}

EvaluatedPolicy is the fully-evaluated intent of a Policyfile.rb, captured by running the file through the embedded Ruby DSL shim. It mirrors the canonical JSON the shim emits (see shim.rb / doc.go) and the state chef-cli's ChefCLI::Policyfile::DSL records for the same file.

This is the *evaluation* result — the declared intent — not a resolved lock. Version solving, source fetching, and identifier computation are a separate concern (see the policy install command and the package docs for the exact evaluation-vs-resolution boundary).

func Evaluate

func Evaluate(ctx context.Context, source string, opts Options) (*EvaluatedPolicy, error)

Evaluate runs source as a Policyfile.rb against the embedded DSL using the default engine. See Engine.Evaluate.

type IncludedPolicy

type IncludedPolicy struct {
	Name          string         `json:"name"`
	SourceOptions map[string]any `json:"source_options"`
}

IncludedPolicy is one include_policy declaration.

type Metadata

type Metadata struct {
	Name         string       `json:"name"`
	Version      string       `json:"version"`
	Dependencies []Dependency `json:"dependencies"`
	Errors       []string     `json:"errors"`
}

Metadata is the resolution-relevant subset of a cookbook's metadata.rb / metadata.json: its name, version, and ordered dependency list. It is exactly what the Policyfile depsolver needs to build the dependency graph and the cookbook identifier inputs.

type Options

type Options struct {
	// Filename is the basename the Policyfile is written under in the work dir
	// and the filename used for Ruby backtraces. Defaults to "Policyfile.rb".
	Filename string
	// Dir, if set, is a directory whose files are copied next to the Policyfile
	// in the work dir, so the Policyfile can require_relative / File.read its
	// siblings. The Policyfile source passed to Evaluate always takes
	// precedence over a same-named file in Dir.
	Dir string
	// Env is the set of environment variables exposed to the Policyfile (so
	// ENV[...] works). When nil, the Policyfile sees no host environment.
	Env map[string]string
	// Timeout bounds this single evaluation (compile + run). When zero or
	// negative, defaultEvalTimeout is used. A timed-out guest is interrupted.
	Timeout time.Duration
}

Options tunes a single Evaluate call.

Jump to

Keyboard shortcuts

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