docker

package
v0.0.0-...-7871f83 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package docker provides Docker-based tool sandboxing for secure execution of containerized commands with resource limits and network isolation.

Docker tools run inside isolated containers, providing access to any CLI tool available as a Docker image (nmap, ffmpeg, imagemagick, etc.) while maintaining strict security boundaries through Linux namespaces, resource limits, and network policies.

Security Model

Docker tools provide container-level security guarantees:

  • Network isolation: Default "none" mode blocks all network access
  • Resource limits: Memory and CPU usage strictly enforced
  • Filesystem isolation: No host access unless explicitly mounted
  • Command allowlisting: Optionally restrict which commands can run

Example Usage

// Create a network scanning tool using nmap
nmapTool, err := docker.NewTool("nmap_scan", "instrumentisto/nmap:latest",
    docker.WithDescription("Scan network hosts and ports using nmap"),
    docker.WithTimeout(5*time.Minute),
    docker.WithNetworkMode("host"),
    docker.WithPullImage(true),
)
if err != nil {
    log.Fatal(err)
}
defer nmapTool.Close()

// Execute the tool
result, err := nmapTool.Call(ctx, `{"command": "-sV -p 80,443 example.com"}`)

Network Modes

The package supports Docker network modes:

  • "none": Complete network isolation (default, most secure)
  • "bridge": Container can access external networks via Docker bridge
  • "host": Container shares host network stack (least secure, use with caution)

Resource Limits

Default resource limits applied to all containers:

  • Memory: 256MB (configurable via WithMemoryLimit)
  • CPU: 0.5 CPU (configurable via WithCPUQuota)
  • Timeout: 30 seconds (configurable via WithTimeout)

Comparison with WASM Tools

Use Docker tools when you need:

  • Existing CLI tools (nmap, ffmpeg, curl, etc.)
  • Complex dependencies that would be hard to compile to WASM
  • Network access (HTTP clients, scanners)
  • Longer-running tasks where ~100-500ms startup is acceptable

Use WASM tools when you need:

  • Sub-millisecond latency
  • Maximum memory isolation
  • Simple, self-contained logic
  • No external dependencies

Package docker provides sentinel errors for the docker tool package.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyCommand is returned when a docker command is empty.
	ErrEmptyCommand = errors.New("tool/docker: empty command")
)

Functions

This section is empty.

Types

type Args

type Args struct {
	Command string `json:"command" jsonschema:"required,description=The command to execute in the container"`
}

Args defines the JSON schema for the Docker tool input.

type Config

type Config struct {
	// Image is the Docker image to run (e.g., "instrumentisto/nmap:latest")
	Image string

	// Command is the command and arguments to pass to the container
	Command []string

	// Env is a list of environment variables in the form "KEY=value"
	Env []string

	// NetworkMode specifies the network mode ("host", "bridge", "none")
	// Default is "none" for maximum isolation.
	NetworkMode string

	// Timeout for the container execution. Zero means no timeout.
	Timeout time.Duration

	// AutoRemove determines if the container should be removed after execution.
	AutoRemove bool

	// Privileged runs the container in privileged mode.
	// WARNING: Use with extreme caution - bypasses most security features.
	Privileged bool

	// Mounts for volume bindings (optional)
	Mounts []mount.Mount

	// WorkingDir sets the working directory inside the container
	WorkingDir string

	// User sets the user inside the container (e.g., "1000:1000")
	User string

	// PullImage determines if the image should be pulled before running
	PullImage bool

	// MemoryLimit is the memory limit in bytes (0 = unlimited)
	MemoryLimit int64

	// CPUQuota is the CPU quota (100000 = 1 CPU)
	CPUQuota int64
}

Config holds the configuration for running a Docker container.

type Option

type Option func(*Options)

Option is a functional option for configuring a Docker tool.

func WithAllowedCommands

func WithAllowedCommands(commands ...string) Option

WithAllowedCommands restricts which commands can be executed. Only commands starting with one of these prefixes are allowed.

func WithCPUQuota

func WithCPUQuota(quota int64) Option

WithCPUQuota sets the CPU quota (100000 = 1 CPU).

func WithDescription

func WithDescription(description string) Option

WithDescription sets the tool description shown to the LLM.

func WithMemoryLimit

func WithMemoryLimit(limit int64) Option

WithMemoryLimit sets the container memory limit in bytes.

func WithNetworkMode

func WithNetworkMode(mode string) Option

WithNetworkMode sets the container network mode. Valid values: "none" (default), "bridge", "host".

func WithPullImage

func WithPullImage(pull bool) Option

WithPullImage enables pulling the image before running.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the execution timeout.

func WithUser

func WithUser(user string) Option

WithUser sets the user inside the container (e.g., "1000:1000").

func WithWorkingDir

func WithWorkingDir(dir string) Option

WithWorkingDir sets the working directory inside the container.

type Options

type Options struct {
	// Description explains what the tool does (shown to LLM)
	Description string

	// Timeout for command execution (default: 30s)
	Timeout time.Duration

	// NetworkMode controls network access ("none", "bridge", "host")
	// Default is "none" for maximum isolation.
	NetworkMode string

	// AllowedCommands restricts which commands can be executed (optional).
	// If set, only commands starting with one of these prefixes are allowed.
	AllowedCommands []string

	// MemoryLimit in bytes (default: 256MB)
	MemoryLimit int64

	// CPUQuota (100000 = 1 CPU, default: 50000 = 0.5 CPU)
	CPUQuota int64

	// PullImage pulls the image before first use
	PullImage bool

	// User sets the user inside the container (e.g., "1000:1000")
	User string

	// WorkingDir sets the working directory inside the container
	WorkingDir string
}

Options configures a Docker tool.

type Result

type Result struct {
	// Stdout contains the standard output from the container
	Stdout []byte

	// Stderr contains the standard error from the container
	Stderr []byte

	// ExitCode is the container's exit code
	ExitCode int

	// Duration is how long the container ran
	Duration time.Duration
}

Result contains the output and metadata from a container run.

type Runner

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

Runner provides a reusable interface for running containerized tools. It wraps the Docker client and handles container lifecycle management.

func NewRunner

func NewRunner() (*Runner, error)

NewRunner creates a new Docker runner instance. It connects to the Docker daemon using environment variables (DOCKER_HOST, etc.) and automatically negotiates the API version.

func NewRunnerWithClient

func NewRunnerWithClient(cli *client.Client) *Runner

NewRunnerWithClient creates a new Docker runner with a pre-configured client. Use this for testing or when you need custom client configuration.

func (*Runner) Close

func (r *Runner) Close() error

Close closes the Docker client connection.

func (*Runner) ImageExists

func (r *Runner) ImageExists(ctx context.Context, imageName string) (bool, error)

ImageExists checks if a Docker image exists locally.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, config Config) (*Result, error)

Run executes a Docker container with the given configuration and returns the result. The container is started, waited for, and its output is captured. If AutoRemove is false, the container is forcefully removed after execution.

type Tool

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

Tool implements tool.Tool for Docker-based command execution. It provides sandboxed execution of containerized commands with configurable resource limits and network isolation.

func NewTool

func NewTool(name, image string, optFns ...Option) (*Tool, error)

NewTool creates a new Docker tool.

Parameters:

  • name: Tool name exposed to the LLM (snake_case recommended)
  • image: Docker image to use (e.g., "python:3.12-slim")
  • optFns: Functional options for configuration

Example:

tool, err := docker.NewTool("python_exec", "python:3.12-slim",
    docker.WithDescription("Execute Python code"),
    docker.WithTimeout(30*time.Second),
    docker.WithNetworkMode("none"),
)

func (*Tool) Call

func (t *Tool) Call(ctx context.Context, argsJSON string) (any, error)

Call executes the tool with JSON-serialized arguments. The command is parsed from the JSON input and executed in a Docker container.

func (*Tool) Close

func (t *Tool) Close() error

Close releases resources associated with the tool.

func (*Tool) Definition

func (t *Tool) Definition() *tool.Definition

Definition returns the tool definition with JSON schema.

func (*Tool) Description

func (t *Tool) Description() string

Description returns the tool description.

func (*Tool) Name

func (t *Tool) Name() string

Name returns the tool name.

Jump to

Keyboard shortcuts

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