Skip to content
starpkgPublic

About

🐚 Starlark module for executing shell commands with cross-platform support, environment variables, timeouts, and detailed command results

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

Β 

History

21 Commits

Folders and files

Repository files navigation

🐚 cmd β€” Starlark module for executing external commands

codecov binary footprint

The cmd module lets Starlark scripts run external programs across Windows, macOS, and Linux. Execution is always via argv (exec.Command), never through a shell, and the module is disabled by default β€” the Go host must opt in with an allowlist before any command can run.

Security model (read this first)

cmd is deny-by-default and the policy is set by the Go host, never by the script or by environment variables:

  1. Disabled by default. A module from NewModule() refuses every run() call. The host enables execution with cmd.NewModuleWithAllow(...).
  2. Allowlist, deny-by-default. Once enabled, a command runs only if its canonical form (argv joined by single spaces) matches an allowlist prefix at a word boundary: "git" permits git status but not gitleaks; "go test" permits go test ./... but not go build. An empty allowlist permits nothing.
  3. No shell interpolation. Commands are split into argv and executed directly β€” there is no /bin/sh -c. Shell features like $VAR, &&, |, globbing, and ; are not interpreted; pass environment via env= and run one program per call.
  4. Unicode hardening. Command text is rejected if it contains control characters or Unicode format/zero-width characters (e.g. zero-width space, BiDi overrides, BOM), which could otherwise hide or reorder text to slip past the allowlist.
  5. Explicit allow-all escape hatch. cmd.NewModuleWithAllowAll() enables the module and bypasses the allowlist entirely β€” every command runs. It is the deliberate "dangerous, run anything" path for a host that has already decided the caller is fully trusted (e.g. a CLI behind a --dangerously-allow-all style flag). The input hardening above (argv-only, no shell, Unicode rejection) still applies; only the allowlist is skipped. Prefer NewModuleWithAllow with a specific allowlist whenever the command set is known. This trusted mode also permits arbitrary environment overrides; dynamic-linker variables are still stripped.
  6. Host-controlled environment keys. NewModuleWithAllow permits no script/config environment overrides. Use NewModuleWithPolicy with Policy{Commands: ..., EnvKeys: ...} to grant exact keys. The same check applies to env=, set_env() and CMD_ENV before a process starts. Names are case-sensitive on Unix and case-insensitive on Windows; prefixes and wildcards are not expanded.

The enable flag, command/environment grants, and allow-all decision are not configuration keys β€” they are set in Go via NewModuleWithAllow, NewModuleWithPolicy or NewModuleWithAllowAll and cannot be widened by a script or environment variable.

Environment grants and compatibility

Scripts using env=, set_env() or CMD_ENV with NewModuleWithAllow must migrate to explicit environment grants. For example:

module := cmd.NewModuleWithPolicy(cmd.Policy{
    Commands: []string{"go env GOOS"},
    EnvKeys:  []string{"GOOS"},
})

Granting a key permits arbitrary values for every allowed command: review the selected programs before granting keys such as PATH, BASH_ENV, GIT_CONFIG_* or interpreter startup options. Grants do not expose additional host environment variables. These checks govern the module's config and call inputs; the host must also prevent untrusted scripts from mutating process-wide environment or executable files through other modules.

Cross-platform note

Because there is no shell, the first token must be a real executable on PATH for the current OS. Shell built-ins are not available as argv:

  • Windows dir, and echo as a cmd.exe builtin, are not runnable directly β€” use real binaries (go, git, where, …) or invoke the interpreter explicitly if you allowlist it.
  • echo is a real binary on most Unix systems but not on Windows.

Prefer real cross-platform tools (e.g. go, git) in portable scripts.

Installation

go get github.com/starpkg/cmd

Quick Start

Construct the module with an allowlist in Go, wire it into a Starlet interpreter, then load("cmd", …) from a script:

package main

import (
    "fmt"

    "github.com/1set/starlet"
    "github.com/starpkg/cmd"
)

func main() {
    // Enable execution with an allowlist (deny-by-default).
    cmdModule := cmd.NewModuleWithAllow("go", "git status")
    interpreter := starlet.New(
        starlet.WithModuleLoader("cmd", cmdModule.LoadModule()),
    )

    script := `
load("cmd", "run", "which")

# Look up an executable without running anything.
print("go at:", which("go"))

# Run an allowlisted command and inspect the result.
result = run("go version")
print("ok:", result.success, "code:", result.exit_code)
print(result.stdout)
`

    if err := interpreter.ExecScript("example.star", script); err != nil {
        fmt.Println("Error:", err)
    }
}

For the complete per-builtin reference β€” signatures, parameters, returns, errors, examples β€” the ProcessResult fields, and the configuration accessors, see docs/API.md.

Starlark API at a glance

Top-level builtins (load("cmd", …)):

  • run(command, cwd?, env?, stdin?, timeout?, combine_output?, realtime_output?, capture_output?) β€” run an allowlisted command via argv; returns a ProcessResult.
  • which(command) β€” return the full path of an executable on PATH, or None; never executes.

run returns a ProcessResult struct with fields success, exit_code, stdout, stderr, output, error, pid, start_time, end_time, and duration.

See docs/API.md for the full signatures, return values, errors, and examples of both builtins above.

Configuration

The module's behavioral defaults (cwd, env, timeout, combine_output, realtime_output, capture_output) are configured via environment variables (CMD_*) or per-option get_<key> / set_<key> accessor builtins, and serve as defaults for run. The enable flag and allowlist are not config β€” they are host-only and cannot be widened from a script. See the Configuration section of docs/API.md for the full option table, defaults, and accessors.

License

MIT

Go compatibility

The library supports Go 1.19 and keeps go.starlark.net pinned to v0.0.0-20260324133313-ffb3f39dd27a. The command splitter uses bitbucket.org/creachadair/shell v0.0.7 (Go 1.16): v0.0.8 raised its declared minimum to Go 1.20 while changing only comments in the runtime source. The older pin preserves the same command-splitting implementation without imposing that additional dependency requirement. Use a supported patched Go toolchain for production applications.

About

🐚 Starlark module for executing shell commands with cross-platform support, environment variables, timeouts, and detailed command results

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages