gateway

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 35 Imported by: 0 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 gateway implements sailwright-gateway, a host-side policy enforcement point that lets an agent in a devcontainer drive a pinned sailwright binary over MCP.

The gateway only knows how commands may run (authentication, classification into the safe set or host approval, snapshots, execution, audit). It knows nothing about tests; deterministic scenarios live in test/e2e and use the gateway as a client.

Index

Constants

View Source
const (

	// AgentSocketName and AgentTokenName are the files in the agent dir. The agent dir
	// is meant to be bind-mounted read-only into devcontainers.
	AgentSocketName = "gateway.sock"
	AgentTokenName  = "token"
)
View Source
const (
	RiskHostModifying   = "HOST-MODIFYING"
	RiskHostCode        = "HOST-CODE"
	RiskPassthroughArgs = "PASSTHROUGH-ARGS"
	RiskExternalPaths   = "EXTERNAL-PATHS"
	RiskNetworkWrite    = "NETWORK-WRITE"
	RiskCredentials     = "CREDENTIALS"
	RiskAllTargets      = "ALL-TARGETS"
)

Risk flags shown to the human approver. They are hints for review, not a policy: everything outside the safe set needs approval regardless of its flags.

View Source
const StateLockName = "gateway.lock"

StateLockName is the lock file in the state dir that a running gateway holds.

Variables

View Source
var ErrBusy = errors.New("another job is active; wait for it or cancel it")

ErrBusy is returned when another job is active; jobs run one at a time.

View Source
var ErrStateLocked = errors.New("another gateway is using this state dir")

ErrStateLocked means another process holds the state dir lock.

View Source
var ErrVMAccessUnavailable = errors.New("VM access is not available in this gateway version")

ErrVMAccessUnavailable is returned until VM access is implemented.

Functions

func AssessRisk

func AssessRisk(args []string, bundleRoot string) []string

AssessRisk derives review hints from raw sailwright arguments. Absolute paths inside bundleRoot (an agent path, may be empty) are snapshotted and not counted as external.

func BuildChildEnv

func BuildChildEnv(dirs ManagedDirs, passthrough []string, getenv func(string) string) []string

BuildChildEnv returns the complete environment for a sailwright child process. It is built from scratch; getenv is usually os.Getenv.

func CleanableDirs

func CleanableDirs(cfg Config) []string

CleanableDirs returns the cache and Packer cache below the data dir. A shared cache dir belongs to the operator's own sailwright and is never cleaned. VM state (.vagrant, libvirt images) and the isolated config are never included.

func ClearCache

func ClearCache(cfg Config) error

ClearCache deletes the contents of the cleanable dirs and keeps the dirs themselves. It continues after errors (for example files still in use on Windows) and returns them joined.

func ConfirmPin

func ConfirmPin(pinned PinnedBinary, in *bufio.Reader, out io.Writer) (bool, error)

ConfirmPin asks the operator on the terminal to confirm the binary hash. The reader is shared with the approval console so no buffered input is lost.

func DefaultDataDir

func DefaultDataDir() (string, error)

DefaultDataDir returns the data dir used with the default state dir. The data dir holds ISOs, images and build caches, so like the sailwright CLI it follows the platform's data location instead of the config location. An empty result means <state dir>/data.

func DefaultStateDir

func DefaultStateDir() (string, error)

DefaultStateDir returns the per-user gateway state directory.

func FormatGB

func FormatGB(bytes int64) string

FormatGB renders a byte count for the operator.

func HashFile

func HashFile(path string) (string, int64, error)

HashFile returns the SHA-256 of a file as lowercase hex.

func ListenAgentSocket

func ListenAgentSocket(dir string) (net.Listener, string, error)

ListenAgentSocket creates <dir>/gateway.sock with owner-only permissions. A stale socket from a previous run is replaced; a live one is an error.

func LoadOrCreateToken

func LoadOrCreateToken(stateDir string) (string, error)

LoadOrCreateToken returns the bearer token, creating a new random one when missing.

func LoadToken

func LoadToken(stateDir string) (string, error)

LoadToken reads the bearer token and refuses files that others can read.

func NewHTTPHandler

func NewHTTPHandler(policy SecurityPolicy, mcpHandler http.Handler) http.Handler

NewHTTPHandler wraps the MCP handler with the security middleware and routes it.

func PassthroughSecrets

func PassthroughSecrets(passthrough []string, getenv func(string) string) []string

PassthroughSecrets returns the values of passthrough variables; they are redacted from all output.

func RemoveSnapshot

func RemoveSnapshot(dir string) error

RemoveSnapshot restores write permission and removes a snapshot directory.

func RemoveStaleStaging

func RemoveStaleStaging(stagingRoot string)

RemoveStaleStaging deletes snapshots and become-password files that a crashed gateway left in stagingRoot. Call it only once this gateway owns the listeners, so no other instance is using the directory.

func RewriteBundlePaths

func RewriteBundlePaths(args []string, snapshot Snapshot) []string

RewriteBundlePaths replaces absolute agent paths inside the bundle with the matching snapshot paths, including the value part of --flag=value and @file arguments. Relative paths need no rewrite because approved commands run inside the snapshot.

func RotateToken

func RotateToken(stateDir string) (string, error)

RotateToken writes a new random bearer token and returns it.

func TokenPath

func TokenPath(stateDir string) string

TokenPath returns the bearer token file inside the state dir.

func WithBecomePasswordFile

func WithBecomePasswordFile(argv []string, path string) []string

WithBecomePasswordFile passes an Ansible become password file to `sailwright provision` as a passthrough argument.

Types

type Approval

type Approval struct {
	Decision       Decision
	BecomePassword string
}

Approval is the operator's answer. BecomePassword is only set for approve-sudo and must never be shown, logged or returned to the agent.

type ApprovalRequest

type ApprovalRequest struct {
	ID        string
	Tool      string
	Argv      []string
	Dir       string
	Risk      []string
	Snapshot  *Snapshot
	NotSafe   string
	AgentNote string
	BinarySHA string
	// Become offers "approve-sudo": the operator also enters the sudo password that
	// Ansible needs for become tasks on this host.
	Become bool
	// BecomeWarning, if set, says why the sudo password may reach another host.
	BecomeWarning string
}

ApprovalRequest is what the human sees before an out-of-safe-set command runs.

type Approver

type Approver interface {
	Enabled() bool
	Request(ctx context.Context, req ApprovalRequest) Approval
}

Approver decides approval requests through a channel the agent cannot reach.

type AuditEvent

type AuditEvent struct {
	Time         time.Time      `json:"time"`
	Event        string         `json:"event"`
	Peer         string         `json:"peer,omitempty"`
	Tool         string         `json:"tool,omitempty"`
	JobID        string         `json:"job_id,omitempty"`
	Tier         string         `json:"tier,omitempty"`
	Argv         []string       `json:"argv,omitempty"`
	Params       map[string]any `json:"params,omitempty"`
	BinarySHA256 string         `json:"binary_sha256,omitempty"`
	Snapshot     *Snapshot      `json:"snapshot,omitempty"`
	Risk         []string       `json:"risk,omitempty"`
	Decision     string         `json:"decision,omitempty"`
	ExitCode     *int           `json:"exit_code,omitempty"`
	DurationMS   int64          `json:"duration_ms,omitempty"`
	Error        string         `json:"error,omitempty"`
	HTTPStatus   int            `json:"http_status,omitempty"`
	SudoPassword bool           `json:"sudo_password,omitempty"`
}

AuditEvent is one line of the JSONL audit log.

type AuditLog

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

AuditLog appends events to a JSONL file.

func OpenAuditLog

func OpenAuditLog(path string, redactor *Redactor) (*AuditLog, error)

OpenAuditLog opens (or creates) the audit log with owner-only permissions.

func (*AuditLog) Close

func (a *AuditLog) Close() error

Close closes the log file.

func (*AuditLog) Record

func (a *AuditLog) Record(event AuditEvent) error

Record writes one event. Errors are returned so callers can fail closed.

type CacheDir

type CacheDir struct {
	Path  string
	Bytes int64
}

CacheDir is one gateway-owned cache directory and the bytes it uses.

type CacheUsage

type CacheUsage struct {
	Dirs  []CacheDir
	Total int64
}

CacheUsage is what the gateway may delete without touching created VMs, its config or a cache it shares with the operator's own sailwright.

func MeasureCache

func MeasureCache(cfg Config) (CacheUsage, error)

MeasureCache sums the size of the regular files in the cleanable dirs. Symlinks are not followed.

func (CacheUsage) CleanQuestion

func (u CacheUsage) CleanQuestion() string

CleanQuestion describes the usage and asks whether to delete it.

type Config

type Config struct {
	Listen             string             `yaml:"listen"`
	AllowedHosts       []string           `yaml:"allowed_hosts"`
	AllowedSourceCIDRs []string           `yaml:"allowed_source_cidrs"`
	AllowedOrigins     []string           `yaml:"allowed_origins"`
	Binary             string             `yaml:"binary"`
	BinarySHA256       string             `yaml:"binary_sha256"`
	DataDir            string             `yaml:"data_dir"`
	SharedCacheDir     string             `yaml:"shared_cache_dir"`
	EnvPassthrough     []string           `yaml:"env_passthrough"`
	PullAllowlist      []string           `yaml:"pull_allowlist"`
	AgentWorkspaces    []WorkspaceMapping `yaml:"agent_workspaces"`
	JobTimeout         string             `yaml:"job_timeout"`
	ApprovalTTL        string             `yaml:"approval_ttl"`
	MinFreeDiskGB      int                `yaml:"min_free_disk_gb"`
	CleanPromptMinGB   int                `yaml:"clean_prompt_min_gb"`
	OutputLimitBytes   int                `yaml:"output_limit_bytes"`
	SnapshotMaxBytes   int64              `yaml:"snapshot_max_bytes"`
	SnapshotMaxFiles   int                `yaml:"snapshot_max_files"`
	AgentDir           string             `yaml:"agent_dir"`
	// ViewListen is the loopback address of the live view for build screenshots
	// ("off" disables it); port 0 picks a free port.
	ViewListen string `yaml:"view_listen"`
	// ScreenStuckAfter is how long console and output must stay unchanged before a
	// build is reported as possibly stuck ("off" disables the hint).
	ScreenStuckAfter string `yaml:"screen_stuck_after"`

	// Resolved values, filled by Resolve.
	StateDir              string         `yaml:"-"`
	ListenAddr            netip.AddrPort `yaml:"-"` // invalid when the TCP listener is off
	ViewAddr              netip.AddrPort `yaml:"-"` // invalid when the live view is off
	SourcePrefixes        []netip.Prefix `yaml:"-"`
	JobTimeoutValue       time.Duration  `yaml:"-"`
	ApprovalTTLValue      time.Duration  `yaml:"-"`
	ScreenStuckAfterValue time.Duration  `yaml:"-"`
}

Config is the operator-owned gateway configuration. It is never writable through MCP.

func LoadConfig

func LoadConfig(stateDir string, configPath string) (Config, error)

LoadConfig reads <stateDir>/gateway.yaml (or configPath when set). A missing default config file yields the defaults; unknown fields are an error.

func (Config) CleanPromptThreshold

func (c Config) CleanPromptThreshold() int64

CleanPromptThreshold returns the cache size from which the gateway offers to clean on Ctrl+C, or 0 if the prompt is disabled.

func (Config) LegacyDataDir

func (c Config) LegacyDataDir() string

LegacyDataDir returns <state dir>/data when it exists but is no longer the data dir, so the operator can remove data the gateway does not use anymore.

func (*Config) Resolve

func (c *Config) Resolve() error

Resolve applies defaults and validates the configuration.

type Confirmer

type Confirmer interface {
	Confirm(ctx context.Context, question string) bool
}

Confirmer asks the operator a yes/no question on the gateway terminal. It returns false unless the operator answers yes; cancelling ctx counts as no.

type ConsoleApprover

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

ConsoleApprover asks the operator on the gateway's own foreground terminal. It has no network surface, so an agent cannot approve its own requests. At most one request is pending; each decision is single-use and expires.

func NewConsoleApprover

func NewConsoleApprover(in *bufio.Reader, out io.Writer, ttl time.Duration) *ConsoleApprover

NewConsoleApprover starts reading operator commands from in.

func (*ConsoleApprover) Confirm

func (a *ConsoleApprover) Confirm(ctx context.Context, question string) bool

Confirm prints question and waits for the next line typed on the console. It returns false while an approval request is pending or the console is closed.

func (*ConsoleApprover) Enabled

func (a *ConsoleApprover) Enabled() bool

Enabled reports whether the console is still readable.

func (*ConsoleApprover) HideInputWith

func (a *ConsoleApprover) HideInputWith(hide InputHider) *ConsoleApprover

HideInputWith sets how terminal echo is turned off while a password is typed. Without it, approve-sudo is refused so a password is never echoed.

func (*ConsoleApprover) Request

Request prints the request and blocks until the operator decides, the request expires or ctx is cancelled.

type Decision

type Decision string

Decision is the outcome of an approval request.

const (
	DecisionApproved  Decision = "approved"
	DecisionDenied    Decision = "denied"
	DecisionExpired   Decision = "expired"
	DecisionCancelled Decision = "cancelled"
	DecisionBusy      Decision = "busy"
)

type DisabledApprover

type DisabledApprover struct{}

DisabledApprover rejects every request; used when the gateway has no terminal.

func (DisabledApprover) Enabled

func (DisabledApprover) Enabled() bool

Enabled reports false.

func (DisabledApprover) Request

Request always denies.

type Gateway

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

Gateway wires policy, execution, jobs and the MCP server together.

func New

func New(opts Options) (*Gateway, error)

New builds a gateway. The config must already be resolved.

func (*Gateway) Close

func (g *Gateway) Close() error

Close releases resources. Close cancels running jobs and background refreshes and waits for them, so no child process outlives the gateway.

func (*Gateway) Handler

func (g *Gateway) Handler() http.Handler

Handler returns the HTTP handler with all security checks applied.

func (*Gateway) Jobs

func (g *Gateway) Jobs() *JobManager

Jobs exposes the job manager (tests and shutdown).

func (*Gateway) Listen

func (g *Gateway) Listen() (*Listeners, error)

Listen opens the TCP listener (unless listen is off) and, except on Windows, the agent Unix socket, and writes a copy of the token next to the socket.

func (*Gateway) RefreshTargets

func (g *Gateway) RefreshTargets(ctx context.Context)

RefreshTargets asks the pinned binary for every `<command> list --json`. The individual commands are not audited; one event records the refresh.

func (*Gateway) Serve

func (g *Gateway) Serve(ctx context.Context) error

Serve opens all listeners and serves until ctx is cancelled.

func (*Gateway) ServeListener

func (g *Gateway) ServeListener(ctx context.Context, listener net.Listener) error

ServeListener serves on a single TCP listener (tests).

func (*Gateway) ServeListeners

func (g *Gateway) ServeListeners(ctx context.Context, listeners *Listeners) error

ServeListeners serves on every open listener until ctx is cancelled.

func (*Gateway) ViewHandler

func (g *Gateway) ViewHandler() http.Handler

ViewHandler serves the live view. It is meant for a loopback-only listener.

type GatewayInfo

type GatewayInfo struct {
	GatewayVersion  string              `json:"gateway_version"`
	HostOS          string              `json:"host_os"`
	HostArch        string              `json:"host_arch"`
	BinarySHA256    string              `json:"binary_sha256"`
	BinarySource    string              `json:"binary_source"`
	DataDir         string              `json:"data_dir"`
	ApprovalEnabled bool                `json:"approval_enabled"`
	SafeTools       []string            `json:"safe_tools"`
	ApprovalTools   []string            `json:"approval_tools"`
	Playbooks       []string            `json:"playbooks"`
	PullAllowlist   []string            `json:"pull_allowlist"`
	AgentWorkspaces []string            `json:"agent_workspaces"`
	ActiveJob       string              `json:"active_job,omitempty"`
	Targets         map[string][]string `json:"targets"`
	TargetErrors    map[string]string   `json:"target_errors,omitempty"`
	VMAccess        string              `json:"vm_access"`
	Limits          GatewayLimits       `json:"limits"`
}

GatewayInfo describes the gateway to agents.

type GatewayLimits

type GatewayLimits struct {
	JobTimeoutSeconds  int64 `json:"job_timeout_seconds"`
	ApprovalTTLSeconds int64 `json:"approval_ttl_seconds"`
	OutputLimitBytes   int   `json:"output_limit_bytes"`
	SnapshotMaxBytes   int64 `json:"snapshot_max_bytes"`
	SnapshotMaxFiles   int   `json:"snapshot_max_files"`
	// MinFreeDiskGB is the free space required before build, create and pull; 0 means
	// the check is disabled.
	MinFreeDiskGB int `json:"min_free_disk_gb"`
}

GatewayLimits are the operator-configured limits an agent can run into.

type GrammarContext

type GrammarContext struct {
	Catalog       *TargetCatalog
	PlaybookDir   string
	Playbooks     []string
	PullAllowlist []string
}

GrammarContext carries everything the grammar needs to validate an operation.

type HelpOutput

type HelpOutput struct {
	Text string `json:"text"`
}

HelpOutput is the result of command_help.

type InputHider

type InputHider func() (restore func(), err error)

InputHider turns off terminal echo and returns a function that restores it.

func TerminalInputHider

func TerminalInputHider(fd int) InputHider

TerminalInputHider turns off echo on the terminal fd while a password is typed. The terminal stays in line mode, so the approval console keeps reading whole lines.

type JobListOutput

type JobListOutput struct {
	Jobs []JobView `json:"jobs"`
}

JobListOutput is the result of job_list.

type JobManager

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

JobManager runs at most one job at a time and keeps a short history.

func NewJobManager

func NewJobManager(opts JobManagerOptions) *JobManager

NewJobManager creates a job manager.

func (*JobManager) Active

func (m *JobManager) Active() string

Active returns the active job id, if any.

func (*JobManager) Cancel

func (m *JobManager) Cancel(id string) (JobView, bool)

Cancel cancels a pending or running job.

func (*JobManager) CancelAll

func (m *JobManager) CancelAll()

CancelAll cancels every unfinished job (shutdown).

func (*JobManager) Get

func (m *JobManager) Get(id string) (JobView, bool)

Get returns a job view.

func (*JobManager) LatestScreenJob

func (m *JobManager) LatestScreenJob() (string, bool)

LatestScreenJob returns the active build job, or else the most recent one.

func (*JobManager) List

func (m *JobManager) List() []JobView

List returns all known jobs, oldest first.

func (*JobManager) Output

func (m *JobManager) Output(id string, offset int64, maxBytes int) (OutputChunk, bool)

Output returns a chunk of a job's output.

func (*JobManager) Screenshot

func (m *JobManager) Screenshot(id string, index int) (ScreenshotResult, error)

Screenshot returns a kept console frame of a job; index 0 is the newest. A running job is sampled first so the frame is current.

func (*JobManager) SetViewURL

func (m *JobManager) SetViewURL(url string)

SetViewURL sets the live view address printed when a build starts.

func (*JobManager) Submit

func (m *JobManager) Submit(spec JobSpec) (JobView, error)

Submit starts a job unless another one is active.

func (*JobManager) Wait

func (m *JobManager) Wait(ctx context.Context, id string) (JobView, error)

Wait blocks until the job is finished or ctx is done (used by tests and shutdown).

func (*JobManager) WaitAll

func (m *JobManager) WaitAll()

WaitAll blocks until every job goroutine has finished (shutdown).

type JobManagerOptions

type JobManagerOptions struct {
	Runner      *Runner
	Approver    Approver
	Audit       *AuditLog
	Redactor    *Redactor
	LogsDir     string
	StagingDir  string
	DataDir     string
	MinFreeGB   int
	OutputLimit int
	BinarySHA   string
	OnFinish    func()
	Console     io.Writer
	// Follow mirrors job output (redacted) to this writer, e.g. the gateway terminal.
	Follow io.Writer
	// CacheDir is the sailwright cache dir, where builds record console frames.
	CacheDir string
	// ScreensDir keeps the sampled frames per job; empty disables screenshots.
	ScreensDir string
	// StuckAfter is the idle time after which a build is suspected stuck; 0 disables.
	StuckAfter time.Duration
}

JobManagerOptions configures a JobManager.

type JobOutputResult

type JobOutputResult struct {
	OutputChunk
	State    JobState `json:"state"`
	ExitCode *int     `json:"exit_code,omitempty"`
}

JobOutputResult is the result of job_output.

type JobSpec

type JobSpec struct {
	Tool             string
	Tier             string
	Argv             []string
	Dir              string
	Timeout          time.Duration
	Params           map[string]any
	Peer             string
	Risk             []string
	Snapshot         *Snapshot
	NeedsApproval    bool
	NotSafe          string
	AgentNote        string
	RequiresFreeDisk bool
	// Become lets the operator approve with a sudo password for Ansible become tasks.
	Become bool
	// BecomeWarning is shown with approve-sudo when the args can redirect the play.
	BecomeWarning string
	// Target is the VM of a safe-set operation; build jobs record console frames for it.
	Target *JobTarget
}

JobSpec describes a job to run.

type JobState

type JobState string

JobState is the lifecycle state of a job.

const (
	JobPendingApproval JobState = "pending_approval"
	JobRunning         JobState = "running"
	JobSucceeded       JobState = "succeeded"
	JobFailed          JobState = "failed"
	JobCancelled       JobState = "cancelled"
	JobDenied          JobState = "denied"
	JobExpired         JobState = "expired"
)

type JobTarget

type JobTarget struct {
	Kind OpKind
	OS   string
	Type string
	Arch string
}

JobTarget is the VM a job operates on, taken from the validated Operation.

type JobView

type JobView struct {
	ID        string    `json:"job_id"`
	Tool      string    `json:"tool"`
	Tier      string    `json:"tier"`
	State     JobState  `json:"state"`
	Argv      []string  `json:"argv"`
	Risk      []string  `json:"risk,omitempty"`
	ExitCode  *int      `json:"exit_code,omitempty"`
	Error     string    `json:"error,omitempty"`
	Created   time.Time `json:"created"`
	Started   time.Time `json:"started,omitzero"`
	Finished  time.Time `json:"finished,omitzero"`
	Snapshot  *Snapshot `json:"snapshot,omitempty"`
	OutputLen int64     `json:"output_bytes"`
	// SudoPassword reports that the operator supplied a sudo password for this run.
	// The password itself is never exposed.
	SudoPassword bool `json:"sudo_password,omitempty"`
	// LastOutputAt is when the job last wrote output; builds can be silent for long.
	LastOutputAt time.Time `json:"last_output_at,omitzero"`
	// ScreenshotAvailable reports that job_screenshot has a console frame.
	ScreenshotAvailable bool `json:"screenshot_available,omitempty"`
	// ScreenChangedAt is when the VM console last changed visibly (cursor blinks and
	// spinners do not count).
	ScreenChangedAt time.Time `json:"screen_changed_at,omitzero"`
	// StuckSuspected is a hint that neither the console nor the output changed for a
	// long time. The gateway never cancels a job because of it.
	StuckSuspected bool `json:"stuck_suspected,omitempty"`
}

JobView is the agent-visible state of a job.

func (JobView) Done

func (v JobView) Done() bool

Done reports whether the job reached a final state.

type LineConfirmer

type LineConfirmer struct {
	In  *bufio.Reader
	Out io.Writer
}

LineConfirmer asks on a reader nobody else reads; used when the approval console is disabled but the gateway still runs on a terminal.

func (LineConfirmer) Confirm

func (c LineConfirmer) Confirm(ctx context.Context, question string) bool

Confirm prints question and waits for one line from In.

type ListTargetsOutput

type ListTargetsOutput struct {
	Command string   `json:"command"`
	Targets []Target `json:"targets"`
}

ListTargetsOutput is the result of list_targets.

type Listeners

type Listeners struct {
	// Lock is the state dir lock, held for as long as the gateway runs.
	Lock       *StateLock
	TCP        net.Listener
	Socket     net.Listener
	SocketPath string
	// View serves the build live view on loopback for the human on the host.
	View    net.Listener
	ViewURL string
}

Listeners are the endpoints the gateway serves on.

The Unix socket in the agent dir is the simple, portable way for Linux containers (rootful or rootless Docker, Podman): the directory is bind-mounted read-only into the devcontainer. The TCP listener serves Docker Desktop on macOS and Windows, where host.docker.internal reaches the host's loopback.

func (*Listeners) Close

func (l *Listeners) Close()

Close closes all listeners.

type ManagedDirs

type ManagedDirs struct {
	AppData     string
	Config      string
	Cache       string
	Vagrant     string
	PackerCache string
	Work        string
	Staging     string
	Logs        string
	// Screens keeps sampled build console frames per job; jobs do not survive a restart.
	Screens string
}

ManagedDirs are the gateway-owned sailwright directories, isolated from the user's regular sailwright data.

func NewManagedDirs

func NewManagedDirs(cfg Config) ManagedDirs

NewManagedDirs derives the managed directories from the config.

func (ManagedDirs) Ensure

func (d ManagedDirs) Ensure() error

Ensure creates all managed directories with owner-only permissions.

func (ManagedDirs) PlaybookDir

func (d ManagedDirs) PlaybookDir() string

PlaybookDir is where the pinned binary extracts its embedded playbooks.

type ManagedVM

type ManagedVM struct {
	OS      string
	Type    string
	Arch    string
	Engine  string
	Address netip.Addr
}

ManagedVM is a VM that sailwright created and that an agent may reach.

type ManagedVMResolver

type ManagedVMResolver interface {
	Resolve(ctx context.Context, osName, osType, arch string) (ManagedVM, error)
}

ManagedVMResolver resolves sailwright-managed VMs and their addresses. A future /tunnel endpoint will only connect to addresses returned here (never to addresses supplied by the agent), so the gateway cannot become a proxy into the host network.

type OpKind

type OpKind string

OpKind identifies an operation of the safe set.

const (
	OpList      OpKind = "list"
	OpHelp      OpKind = "help"
	OpBuild     OpKind = "build"
	OpCreate    OpKind = "create"
	OpStart     OpKind = "start"
	OpStop      OpKind = "stop"
	OpDestroy   OpKind = "destroy"
	OpProvision OpKind = "provision"
	OpPull      OpKind = "pull"
)

type Operation

type Operation struct {
	Kind     OpKind
	Command  string   // for OpList: the listed command
	HelpPath []string // for OpHelp: the command path, e.g. ["provision"]
	OS       string
	Type     string
	Arch     string
	Engine   string
	Check    bool
	// Verbosity is the Ansible verbosity; -1 keeps the CLI default.
	Verbosity int
	// Playbook is the name of an embedded playbook (without .yml); empty keeps the default.
	Playbook string
	Headless bool
	Verbose  bool
	NoCache  bool
	Ref      string
}

Operation is a fully validated safe-set operation.

func ParseSafe

func ParseSafe(args []string, ctx GrammarContext) (Operation, error)

ParseSafe tries to map free-form sailwright arguments onto a safe operation. An error means "not in the safe set" and carries the reason shown to the approver.

func (Operation) Argv

func (o Operation) Argv(ctx GrammarContext) []string

Argv renders the canonical sailwright argv for a validated operation.

func (*Operation) Validate

func (o *Operation) Validate(ctx GrammarContext) error

Validate checks an operation against the identifier rules and the target catalog and fills CLI defaults (arch, type) so the canonical argv is explicit.

type Options

type Options struct {
	Config   Config
	Pinned   PinnedBinary
	Token    string
	Approver Approver
	Console  io.Writer
	// FollowOutput mirrors job output to Console.
	FollowOutput bool
	Version      string
	Getenv       func(string) string
}

Options configures a Gateway.

type OutputChunk

type OutputChunk struct {
	Data            string `json:"data"`
	Offset          int64  `json:"offset"`
	NextOffset      int64  `json:"next_offset"`
	TruncatedBefore bool   `json:"truncated_before"`
}

OutputChunk is a slice of job output.

type PinnedBinary

type PinnedBinary struct {
	Source string
	Path   string
	SHA256 string
	Size   int64
}

PinnedBinary is the gateway-owned copy of the sailwright binary under test. Only this copy is ever executed, so changing the source after startup has no effect.

func PinBinary

func PinBinary(source string, stateDir string, expectedSHA256 string) (PinnedBinary, error)

PinBinary copies source into <stateDir>/bin and returns the pinned copy. When expectedSHA256 is set, the source must match it.

func (PinnedBinary) Verify

func (p PinnedBinary) Verify() error

Verify re-hashes the pinned copy and fails if it changed since pinning.

type Redactor

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

Redactor replaces known secret values with a marker.

func NewRedactor

func NewRedactor(secrets ...string) *Redactor

NewRedactor builds a redactor; very short values are ignored to avoid mangling output.

func (*Redactor) String

func (r *Redactor) String(value string) string

String redacts a string. A nil redactor returns the value unchanged.

func (*Redactor) Strings

func (r *Redactor) Strings(values []string) []string

Strings redacts every element.

func (*Redactor) With

func (r *Redactor) With(secrets ...string) *Redactor

With returns a redactor that also hides the given secrets, keeping r's minimum length.

func (*Redactor) WithRequired

func (r *Redactor) WithRequired(secrets ...string) *Redactor

WithRequired is like With but also hides short values. Use it for secrets that must never appear, such as a sudo password, accepting that output may be mangled.

type Runner

type Runner struct {
	Binary PinnedBinary
	Env    []string
}

Runner executes the pinned sailwright binary. It never uses a shell: the argv slice is passed to the OS as-is, stdin is closed, and the environment is built from scratch.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, argv []string, dir string, out io.Writer) (int, error)

Run executes argv in dir, streaming combined output to out. Cancelling ctx terminates the whole process tree. It returns the exit code (or -1 when the process could not be started or was killed by a signal).

type ScreenFrame

type ScreenFrame struct {
	Seq        int
	Path       string
	CapturedAt time.Time
	Size       int
}

ScreenFrame is one sampled console frame kept for a job.

type ScreenStatus

type ScreenStatus struct {
	Frames         int
	LastFrameAt    time.Time
	ChangedAt      time.Time
	ChangedCells   int
	StuckSuspected bool
}

ScreenStatus summarizes the console frames of a job.

type ScreenshotInfo

type ScreenshotInfo struct {
	JobID                  string    `json:"job_id"`
	State                  JobState  `json:"state"`
	Available              bool      `json:"available"`
	Reason                 string    `json:"reason,omitempty"`
	Index                  int       `json:"index"`
	FramesAvailable        int       `json:"frames_available"`
	CapturedAt             time.Time `json:"captured_at,omitzero"`
	AgeSeconds             int64     `json:"age_seconds,omitempty"`
	ScreenChangedAt        time.Time `json:"screen_changed_at,omitzero"`
	ScreenUnchangedSeconds int64     `json:"screen_unchanged_seconds,omitempty"`
	StuckSuspected         bool      `json:"stuck_suspected,omitempty"`
	LiveView               string    `json:"live_view,omitempty"`
}

ScreenshotInfo describes the frame returned by job_screenshot, or why there is none.

type ScreenshotResult

type ScreenshotResult struct {
	View   JobView
	Status ScreenStatus
	Frame  ScreenFrame
	Data   []byte
	Reason string
}

ScreenshotResult is a console frame of a build job, or the reason there is none.

type SecurityPolicy

type SecurityPolicy struct {
	Token          string
	SourcePrefixes []netip.Prefix
	AllowedHosts   []string
	AllowedOrigins []string
	Audit          *AuditLog
}

SecurityPolicy holds the request checks shared by every endpoint (/mcp now, /tunnel later).

func (SecurityPolicy) Middleware

func (p SecurityPolicy) Middleware(next http.Handler) http.Handler

Middleware enforces source address, Host, Origin and bearer token checks in that order and fails closed. Requests over the agent Unix socket skip the network checks.

type Snapshot

type Snapshot struct {
	AgentRoot string `json:"agent_root"`
	HostRoot  string `json:"host_root"`
	Dir       string `json:"dir"`
	TreeHash  string `json:"tree_hash"`
	Files     int    `json:"files"`
	Bytes     int64  `json:"bytes"`
}

Snapshot is a read-only, gateway-owned copy of an agent-provided bundle. Approved commands run against the snapshot, so editing the bundle after approval changes nothing.

func CreateConfinedSnapshot

func CreateConfinedSnapshot(agentRoot string, workspaceHost string, rel string, displayRoot string, stagingRoot string, limits SnapshotLimits) (Snapshot, error)

CreateConfinedSnapshot snapshots the directory rel below the operator-configured workspace. The bundle root is opened through the workspace os.Root in one step, so a symlink the agent swaps in after TranslateAgentPath cannot redirect it outside the workspace. displayRoot is only recorded for the approval prompt.

func CreateSnapshot

func CreateSnapshot(agentRoot string, hostRoot string, stagingRoot string, limits SnapshotLimits) (Snapshot, error)

CreateSnapshot copies hostRoot into a new directory below stagingRoot. Files are read through os.Root, so symlinks cannot escape the bundle even if the agent swaps files while the copy runs. Symlinks to directories are rejected.

hostRoot is opened by path; use CreateConfinedSnapshot for agent-supplied paths.

type SnapshotLimits

type SnapshotLimits struct {
	MaxBytes int64
	MaxFiles int
}

SnapshotLimits bound what a bundle snapshot may copy.

type StateLock

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

StateLock is an exclusive advisory lock on a gateway state dir. The operating system releases it when the process exits, so a crash never leaves a stale lock.

func AcquireStateLock

func AcquireStateLock(stateDir string) (*StateLock, error)

AcquireStateLock takes the lock without blocking. It returns ErrStateLocked if another process holds it.

func (*StateLock) Release

func (l *StateLock) Release()

Release drops the lock. It is safe on a nil lock.

type Target

type Target struct {
	OS     string            `json:"os"`
	Type   string            `json:"type"`
	Arch   string            `json:"arch"`
	Engine string            `json:"engine"`
	Fields map[string]string `json:"fields,omitempty"`
}

Target is one entry of `<command> list --json` reported by the pinned binary.

func ParseTargetListing

func ParseTargetListing(output []byte) ([]Target, error)

ParseTargetListing extracts the JSON listing from CLI output. Diagnostic lines the CLI may print before the document are ignored.

type TargetCatalog

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

TargetCatalog caches the valid targets per command, as reported by the pinned binary. The gateway never imports sailwright internals, so the enums always match the version under test.

func NewTargetCatalog

func NewTargetCatalog() *TargetCatalog

NewTargetCatalog returns an empty catalog.

func (*TargetCatalog) Errors

func (c *TargetCatalog) Errors() map[string]string

Errors returns the last listing error per command.

func (*TargetCatalog) HasTypedTargets

func (c *TargetCatalog) HasTypedTargets(command string, osName string) bool

HasTypedTargets reports whether a command lists the OS with a type (e.g. ubuntu server/desktop), which means the CLI default type applies when none is given.

func (*TargetCatalog) Match

func (c *TargetCatalog) Match(command string, osName, osType, arch, engine string) []Target

Match returns the targets of command that match the requested identity. Empty type or engine match any value.

func (*TargetCatalog) Set

func (c *TargetCatalog) Set(command string, targets []Target, listErr error)

Set stores the listing for one command.

func (*TargetCatalog) Summary

func (c *TargetCatalog) Summary() map[string][]string

Summary returns the distinct os/type/arch/engine values per command.

func (*TargetCatalog) Targets

func (c *TargetCatalog) Targets(command string) []Target

Targets returns the cached targets for a command.

type WorkspaceMapping

type WorkspaceMapping struct {
	Agent string `yaml:"agent"`
	Host  string `yaml:"host"`
}

WorkspaceMapping maps a directory the agent sees (inside its container) to the host directory that backs it, usually a devcontainer bind mount. Every mapped host directory is treated as agent-writable.

func TranslateAgentPath

func TranslateAgentPath(agentPath string, workspaces []WorkspaceMapping) (string, WorkspaceMapping, error)

TranslateAgentPath maps a path inside the agent container to the host path that backs it. Only configured agent workspaces are accepted.

Directories

Path Synopsis
Package client finds and connects to a sailwright-gateway from inside a container.
Package client finds and connects to a sailwright-gateway from inside a container.
Package gatewaytest starts a real sailwright-gateway against a fake sailwright CLI.
Package gatewaytest starts a real sailwright-gateway against a fake sailwright CLI.

Jump to

Keyboard shortcuts

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