docker

package
v0.4.10 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const ExitCodeSIGKILL = 137

ExitCodeSIGKILL is the exit status of a process killed by SIGKILL (128+9), which is what the kernel OOM killer sends.

Variables

View Source
var ErrEgressUnavailable = errors.New("network allowlist (allowed_hosts) is not available in this deployment")

ErrEgressUnavailable means a session asked for allowed_hosts but this deployment has no way to install host iptables rules.

View Source
var ErrImageUnavailable = errors.New("image not found or not accessible")

ErrImageUnavailable means the requested image cannot be used because it does not exist, the reference is malformed, or the registry denied access. It is a caller error, not a server fault.

View Source
var ErrInvalidAllowedHosts = errors.New("invalid allowed_hosts")

ErrInvalidAllowedHosts marks an allowed_hosts entry that can never be honoured (malformed, or pointing at a private/internal address). Callers report it as a client error rather than a server failure.

Functions

func EgressPolicyAvailable added in v0.4.1

func EgressPolicyAvailable() bool

EgressPolicyAvailable reports whether allowed_hosts can be enforced: either iptables is on the API host's PATH (bare-metal install) or a netpolicy helper container is configured.

func NormalizeWorkingDir added in v0.4.9

func NormalizeWorkingDir(wd string) (string, error)

NormalizeWorkingDir cleans a requested working directory and restricts it to /workspace or /tmp, which prevents access to arbitrary container paths such as /proc or /etc (including via ".." segments).

func ValidateAllowedHosts added in v0.4.9

func ValidateAllowedHosts(hosts []string) error

ValidateAllowedHosts checks the syntax and target of every entry: a hostname, an IP address or a CIDR block, none of which may point at a private, loopback or link-local address. DNS is not consulted.

Types

type Client

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

Client wraps the Docker SDK client with optional seccomp enforcement.

func New

func New() (*Client, error)

New creates a new Docker client using the environment / DOCKER_HOST.

Seccomp: DOCKER_SECCOMP_PROFILE controls which profile is applied:

  • "" → use the embedded vaultrun seccomp profile (default, recommended)
  • "default" → pass seccomp=default explicitly to rely on the daemon's built-in filter
  • "/path" → load and embed the JSON from the given file path

Cosign: when COSIGN_PUBLIC_KEY points to a PEM public key, every image is verified with `cosign verify --key <file> <image>` before use. If the key is set but the cosign binary is missing, CreateSandbox fails closed.

func (*Client) ContainerGone added in v0.4.1

func (c *Client) ContainerGone(ctx context.Context, containerID string) (bool, error)

ContainerGone reports whether the daemon definitively has no such container. Any other inspect failure (daemon hiccup, timeout) is returned as an error so callers never treat "could not check" as "gone".

func (*Client) ContainerLogs

func (c *Client) ContainerLogs(ctx context.Context, containerName string, tail int) (string, error)

ContainerLogs returns the last tail lines of combined stdout+stderr for containerName. When tail <= 0 all available log lines are returned.

func (*Client) ContainerRunning

func (c *Client) ContainerRunning(ctx context.Context, containerID string) (bool, error)

ContainerRunning returns true if the container exists and is running.

func (*Client) ContainerStats

func (c *Client) ContainerStats(ctx context.Context, containerName string) (*ContainerStatsResult, error)

ContainerStats returns a single-sample resource snapshot for containerName.

func (*Client) CreateSandbox

func (c *Client) CreateSandbox(ctx context.Context, cfg SandboxConfig) (string, error)

CreateSandbox creates and starts an isolated Docker container.

Security steps (in order):

  1. Cosign image signature verification (if COSIGN_PUBLIC_KEY is set)
  2. Image pull if not cached
  3. Per-session Docker bridge network creation + iptables egress rules (only when NetworkEnabled && len(AllowedHosts) > 0)
  4. Container create + start with seccomp, CapDrop ALL, no-new-privileges

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, cfg ExecConfig) (*ExecResult, error)

Exec runs a command inside the sandbox container and buffers full output. It is deliberately NOT shell-invoked — command and args are passed as separate fields to the Docker exec API, preventing shell injection.

func (*Client) ExecSimple added in v0.3.0

func (c *Client) ExecSimple(ctx context.Context, containerID string, cmd []string) (stdout, stderr string, err error)

ExecSimple is a convenience wrapper for running simple commands that returns stdout, stderr and error

func (*Client) ExecStream

func (c *Client) ExecStream(ctx context.Context, cfg ExecConfig, stdout, stderr io.Writer) (*ExecResult, error)

ExecStream runs a command and writes output chunks to stdout/stderr as they arrive. The ExecResult's Stdout and Stderr fields are empty — data is written directly to the provided writers.

func (*Client) ImageExists

func (c *Client) ImageExists(ctx context.Context, image string) (bool, error)

ImageExists returns true if the image is already locally available.

func (*Client) Inner

func (c *Client) Inner() *client.Client

func (*Client) ListImages

func (c *Client) ListImages(ctx context.Context) ([]ImageSummary, error)

ListImages returns locally available Docker images.

func (*Client) PullImage

func (c *Client) PullImage(ctx context.Context, image string) error

PullImage pulls an image if not already present.

func (*Client) ReadFile added in v0.3.0

func (c *Client) ReadFile(ctx context.Context, containerID, path string) ([]byte, error)

ReadFile reads a file from a container

func (*Client) SeccompJSON

func (c *Client) SeccompJSON() string

SeccompJSON returns the raw seccomp profile JSON configured for this client. Used by the warm pool so it can apply the same profile as CreateSandbox.

func (*Client) StopSandbox

func (c *Client) StopSandbox(ctx context.Context, containerID string) error

StopSandbox stops and removes the container, then cleans up any associated per-session network and iptables egress rules.

func (*Client) UseNetpolicyContainer added in v0.4.1

func (c *Client) UseNetpolicyContainer(name string)

UseNetpolicyContainer routes iptables calls through `docker exec` into a long-running helper container that shares the host network namespace and has NET_ADMIN (the "netpolicy" service in deployments/docker-compose.yml).

This is required when the API itself runs in a container: iptables executed in the API's own network namespace would never see the sandbox bridge traffic, so rules would silently enforce nothing.

func (*Client) VerifyImage

func (c *Client) VerifyImage(ctx context.Context, image string) (string, error)

VerifyImage checks the container image's cryptographic signature using cosign when a public key is configured via COSIGN_PUBLIC_KEY.

Behaviour:

  • Key NOT set → no-op, returns (image, nil)
  • Key set, cosign binary missing → returns error (fail-closed)
  • Key set, signature absent/invalid → returns error (fail-closed)
  • Key set, signature valid → returns digest-pinned image ref, e.g. "python@sha256:abc123…" — use this for all subsequent pull/run operations to close the TOCTOU window between verify and pull.

This must be called before PullImage / ImageExists so that unverified images are never instantiated as containers.

func (*Client) WriteFile added in v0.3.0

func (c *Client) WriteFile(ctx context.Context, containerID, path string, content []byte) error

WriteFile writes a file to a container

type ContainerStatsResult

type ContainerStatsResult struct {
	CPUPercent       float64 `json:"cpu_percent"`
	MemoryBytes      uint64  `json:"memory_bytes"`
	MemoryLimitBytes uint64  `json:"memory_limit_bytes"`
	NetworkRxBytes   uint64  `json:"network_rx_bytes"`
	NetworkTxBytes   uint64  `json:"network_tx_bytes"`
}

ContainerStatsResult holds the one-shot resource metrics for a container.

type ExecConfig

type ExecConfig struct {
	ContainerID    string
	Command        string
	Args           []string
	Env            map[string]string
	WorkingDir     string
	TimeoutSeconds int
	MaxOutputBytes int64
}

ExecConfig holds parameters for running a command inside a container.

type ExecResult

type ExecResult struct {
	ExitCode   int
	Stdout     string // populated by Exec; empty when using ExecStream
	Stderr     string // populated by Exec; empty when using ExecStream
	DurationMS int64
	TimedOut   bool
	Truncated  bool // true when stdout or stderr was capped at MaxOutputBytes (M-10)
	// OOMKilled is set when the process was SIGKILLed (exit 137) and the
	// container's cgroup recorded an out-of-memory kill. MemoryLimitMB is the
	// container's memory limit in that case, for the error message.
	OOMKilled     bool
	MemoryLimitMB int64
}

ExecResult is the result of an exec invocation.

func (*ExecResult) OOMMessage added in v0.3.4

func (r *ExecResult) OOMMessage() string

OOMMessage is the human-readable note appended to stderr when a command was killed for exceeding the container memory limit.

type ImageSummary

type ImageSummary struct {
	ID        string    `json:"id"`
	Tags      []string  `json:"tags"`
	SizeBytes int64     `json:"size_bytes"`
	CreatedAt time.Time `json:"created_at"`
}

ImageSummary is a trimmed image descriptor returned by ListImages.

type SandboxConfig

type SandboxConfig struct {
	SessionID         uuid.UUID
	Image             string
	WorkspacePath     string // Path to workspace on the API container filesystem
	HostWorkspacePath string // Path to workspace on the Docker host (for bind mounts); defaults to WorkspacePath if empty
	NetworkEnabled    bool
	CPULimit          float64 // fractional CPUs, e.g. 0.5 = half a core
	MemoryLimitMB     int
	ContainerName     string
	// AllowedHosts is an optional list of hostnames or IPs the container may
	// reach when NetworkEnabled is true.
	//
	// When non-empty, a dedicated per-session Docker bridge network is created
	// and host-side iptables rules enforce that only DNS and the resolved IPs
	// of the listed hosts are reachable. AllowedHosts entries are also injected
	// into /etc/hosts via ExtraHosts for in-container DNS resolution.
	//
	// When empty (and NetworkEnabled), the container uses the default bridge
	// without iptables filtering (operator is responsible for egress policy).
	AllowedHosts []string
	// GPUDevices enables NVIDIA GPU access inside the container.
	// Values: "all" (all GPUs), "0" (first GPU), "0,1" (first two GPUs), "" (disabled).
	// Requires nvidia-container-toolkit on the host.
	GPUDevices string
}

SandboxConfig holds the parameters for creating a session container.

Jump to

Keyboard shortcuts

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