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
- Variables
- func AssessRisk(args []string, bundleRoot string) []string
- func BuildChildEnv(dirs ManagedDirs, passthrough []string, getenv func(string) string) []string
- func CheckCompatibility(ctx context.Context, pinned PinnedBinary, dirs ManagedDirs, ...) error
- func CleanableDirs(cfg Config) []string
- func ClearCache(cfg Config) error
- func ConfirmPin(pinned PinnedBinary, in *bufio.Reader, out io.Writer) (bool, error)
- func DefaultDataDir() (string, error)
- func DefaultStateDir() (string, error)
- func EnableVirtualTerminal(*os.File) (restore func(), ok bool)
- func FormatGB(bytes int64) string
- func HashFile(path string) (string, int64, error)
- func IsolatedOwnershipNotice(cfg Config) (string, error)
- func ListenAgentSocket(dir string) (net.Listener, string, error)
- func LoadOrCreateToken(stateDir string) (string, error)
- func LoadToken(stateDir string) (string, error)
- func NewHTTPHandler(policy SecurityPolicy, mcpHandler, tunnelHandler http.Handler) http.Handler
- func PassthroughSecrets(passthrough []string, getenv func(string) string) []string
- func RemoveRegisteredWorkspace(cfg Config, agentPath string) (bool, error)
- func RemoveSnapshot(dir string) error
- func RemoveStaleStaging(stagingRoot string)
- func RewriteBundlePaths(args []string, snapshot Snapshot) []string
- func RotateToken(stateDir string) (string, error)
- func TerminalSize(fd int) func() (width, height int)
- func TokenPath(stateDir string) string
- func VerifyWorkspaceProbe(hostDir string, token string) error
- func WithBecomePasswordFile(argv []string, path string) []string
- func WorkspacesPath(stateDir string) string
- type Approval
- type ApprovalRequest
- type Approver
- type AuditEvent
- type AuditLog
- type AutoApprover
- type CLIManagedVMResolver
- func (r *CLIManagedVMResolver) Close() error
- func (r *CLIManagedVMResolver) Identify(ctx context.Context, osName, osType, arch string, names ...string) (VMIdentity, error)
- func (r *CLIManagedVMResolver) Resolve(ctx context.Context, osName, osType, arch string, names ...string) (ManagedVM, error)
- func (r *CLIManagedVMResolver) ResolveFresh(ctx context.Context, osName, osType, arch string, names ...string) (ManagedVM, error)
- type CacheDir
- type CacheUsage
- type Config
- type Confirmer
- type ConsoleApprover
- func (a *ConsoleApprover) Confirm(ctx context.Context, question string) bool
- func (a *ConsoleApprover) Enabled() bool
- func (a *ConsoleApprover) HideInputWith(hide InputHider) *ConsoleApprover
- func (a *ConsoleApprover) Request(ctx context.Context, req ApprovalRequest) Approval
- func (a *ConsoleApprover) WithPromptHook(hook func(waiting bool)) *ConsoleApprover
- type Decision
- type DisabledApprover
- type Escalation
- type Gateway
- func (g *Gateway) Close() error
- func (g *Gateway) Handler() http.Handler
- func (g *Gateway) Jobs() *JobManager
- func (g *Gateway) Listen() (*Listeners, error)
- func (g *Gateway) RefreshTargets(ctx context.Context)
- func (g *Gateway) Serve(ctx context.Context) error
- func (g *Gateway) ServeListener(ctx context.Context, listener net.Listener) error
- func (g *Gateway) ServeListeners(ctx context.Context, listeners *Listeners) error
- func (g *Gateway) ViewHandler() http.Handler
- type GatewayInfo
- type GatewayLimits
- type GrammarContext
- type HelpOutput
- type InputHider
- type JobListOutput
- type JobManager
- func (m *JobManager) Active() string
- func (m *JobManager) Cancel(id string) (JobView, bool)
- func (m *JobManager) CancelAll()
- func (m *JobManager) Get(id string) (JobView, bool)
- func (m *JobManager) LatestScreenJob() (string, bool)
- func (m *JobManager) List() []JobView
- func (m *JobManager) Output(id string, offset int64, maxBytes int) (OutputChunk, bool)
- func (m *JobManager) Screenshot(id string, index int) (ScreenshotResult, error)
- func (m *JobManager) SetViewURL(url string)
- func (m *JobManager) Submit(spec JobSpec) (JobView, error)
- func (m *JobManager) Wait(ctx context.Context, id string) (JobView, error)
- func (m *JobManager) WaitAll()
- type JobManagerOptions
- type JobOutputResult
- type JobSpec
- type JobState
- type JobTarget
- type JobView
- type LineConfirmer
- type ListTargetsOutput
- type Listeners
- type LiveConsole
- type LiveTail
- type ManagedDirs
- type ManagedVM
- type ManagedVMResolver
- type OpKind
- type Operation
- type Options
- type OutputChunk
- type PinnedBinary
- type Redactor
- type RegisteredWorkspace
- type Runner
- type ScreenFrame
- type ScreenStatus
- type ScreenshotInfo
- type ScreenshotResult
- type SecurityPolicy
- type Snapshot
- type SnapshotLimits
- type StateLock
- type Target
- type TargetCatalog
- func (c *TargetCatalog) Errors() map[string]string
- func (c *TargetCatalog) HasTypedTargets(command string, osName string) bool
- func (c *TargetCatalog) Match(command string, osName, osType, arch, engine string) []Target
- func (c *TargetCatalog) Set(command string, targets []Target, listErr error)
- func (c *TargetCatalog) Summary() map[string][]string
- func (c *TargetCatalog) Targets(command string) []Target
- type VMIdentity
- type VMInfoOutput
- type VMTarget
- type WorkspaceMapping
- type WorkspaceRegisterOutput
Constants ¶
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" )
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.
const StateLockName = "gateway.lock"
StateLockName is the lock file in the state dir that a running gateway holds.
const ( // WorkspaceProbeName is the file the agent writes into its workspace to prove // which host directory backs it. WorkspaceProbeName = ".sailwright-gateway-probe" )
Variables ¶
var ErrApprovalPending = errors.New("waits for operator approval")
ErrApprovalPending reports that a request waits for the operator.
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.
var ErrStateLocked = errors.New("another gateway is using this state dir")
ErrStateLocked means another process holds the state dir lock.
var ErrVMAccessPending = errors.New("VM access waits for operator approval")
ErrVMAccessPending reports that the operator has not yet decided an access request.
ErrVMAccessUnavailable reports that a managed guest cannot currently be reached.
Functions ¶
func AssessRisk ¶
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 CheckCompatibility ¶ added in v0.27.0
func CheckCompatibility(ctx context.Context, pinned PinnedBinary, dirs ManagedDirs, env, installedEnv []string, shared bool, out io.Writer) error
CheckCompatibility checks the state contract before any shared-state command. The pinned CLI must report a compatible contract in shared mode. The installed `sailwright` on PATH is only probed for comparison, with installedEnv (which must not carry passthrough secrets): a missing contract there is a warning, an incompatible reported contract is an error in shared mode.
func CleanableDirs ¶
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 ¶
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 ¶
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 ¶
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 ¶
DefaultStateDir returns the per-user gateway state directory.
func EnableVirtualTerminal ¶ added in v0.28.0
EnableVirtualTerminal reports whether the terminal behind f processes VT sequences; every terminal on these hosts does, except TERM=dumb. Nothing needs to be restored.
func IsolatedOwnershipNotice ¶ added in v0.27.0
IsolatedOwnershipNotice returns a startup note, once per state directory, for an isolated gateway without ownership records. Gateways before the ownership gate applied to isolated state recorded nothing, so the VMs they created now count as not created by the gateway. Adopting them automatically would also adopt the operator's VMs, which share the hypervisor's global names.
func ListenAgentSocket ¶
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 ¶
LoadOrCreateToken returns the bearer token, creating a new random one when missing.
func NewHTTPHandler ¶
func NewHTTPHandler(policy SecurityPolicy, mcpHandler, tunnelHandler http.Handler) http.Handler
NewHTTPHandler wraps the MCP and (optional, may be nil) tunnel handlers with the security middleware and routes them.
func PassthroughSecrets ¶
PassthroughSecrets returns the values of passthrough variables; they are redacted from all output.
func RemoveRegisteredWorkspace ¶ added in v0.28.0
RemoveRegisteredWorkspace removes the registered workspace for an agent path. It reports false when none is registered; gateway.yaml entries are not touched.
func RemoveSnapshot ¶
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 ¶
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 ¶
RotateToken writes a new random bearer token and returns it.
func TerminalSize ¶ added in v0.28.0
TerminalSize reports the size of the terminal on fd.
func VerifyWorkspaceProbe ¶ added in v0.28.0
VerifyWorkspaceProbe checks that hostDir holds the probe file the agent wrote into the directory it sees, which proves hostDir is the agent's mount and not a host directory it merely named.
func WithBecomePasswordFile ¶
WithBecomePasswordFile passes an Ansible become password file to `sailwright provision` as a passthrough argument.
func WorkspacesPath ¶ added in v0.28.0
WorkspacesPath returns the file that holds the registered workspaces.
Types ¶
type Approval ¶
type Approval struct {
Decision Decision
BecomePassword string
// Auto is set when AutoApprover decided without the operator.
Auto bool
}
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
// Command, if set, replaces the sailwright command line in the prompt, for
// requests that change the gateway rather than run the CLI.
Command 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"`
// AutoApproved marks decisions made by --bypass-approvals instead of the operator.
AutoApproved bool `json:"auto_approved,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 ¶
OpenAuditLog opens (or creates) the audit log with owner-only permissions.
func (*AuditLog) Record ¶
func (a *AuditLog) Record(event AuditEvent) error
Record writes one event. Errors are returned so callers can fail closed.
type AutoApprover ¶ added in v0.27.0
AutoApprover approves every request without asking. It exists for disposable test environments (serve --bypass-approvals) and removes the human check entirely: any agent with the token can run every command the gateway grammar accepts. Each decision is still printed so the console shows what ran.
func (AutoApprover) Enabled ¶ added in v0.27.0
func (AutoApprover) Enabled() bool
Enabled reports true so approval-gated tools and VM access requests are offered.
func (AutoApprover) Request ¶ added in v0.27.0
func (a AutoApprover) Request(_ context.Context, req ApprovalRequest) Approval
Request approves immediately. Become requests get no sudo password.
type CLIManagedVMResolver ¶ added in v0.27.0
type CLIManagedVMResolver struct {
// Context bounds all lookups to the owner lifetime; nil uses Background.
Context context.Context
Runner *Runner
Work string
Redactor *Redactor
// Console receives the reason of failed lookups for the operator; may be nil.
Console io.Writer
// contains filtered or unexported fields
}
CLIManagedVMResolver asks only the pinned CLI for guest connection details. Lookups for different targets run concurrently; concurrent lookups for the same target share one CLI invocation.
func (*CLIManagedVMResolver) Close ¶ added in v0.27.0
func (r *CLIManagedVMResolver) Close() error
Close prevents new lookups, cancels CLI processes and waits for their exit.
func (*CLIManagedVMResolver) Identify ¶ added in v0.27.0
func (r *CLIManagedVMResolver) Identify(ctx context.Context, osName, osType, arch string, names ...string) (VMIdentity, error)
Identify runs `vm identity`. It is not cached: callers use it to decide whether a VM is still the one the gateway knows.
func (*CLIManagedVMResolver) ResolveFresh ¶ added in v0.27.0
type CacheUsage ¶
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"`
StateIsolation string `yaml:"state_isolation"`
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"`
MaxInstances int `yaml:"max_instances"`
MaxTunnels int `yaml:"max_tunnels"`
TunnelIdleTimeout string `yaml:"tunnel_idle_timeout"`
TunnelIdleTimeoutValue time.Duration `yaml:"-"`
// TunnelAllowedCIDRs adds guest networks a tunnel may reach besides the
// subnets of the host's own interfaces, for routed guest networks.
TunnelAllowedCIDRs []string `yaml:"tunnel_allowed_cidrs"`
// 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.
// LegacyIsolation is set when state_isolation was unset and isolated mode was
// selected because <data_dir>/app from an older gateway exists.
LegacyIsolation bool `yaml:"-"`
// GateForeignVMs requires operator approval before the agent uses a VM this
// gateway did not create. Always set: hypervisor VM names are global, so the
// operator's VMs are reachable with isolated state too.
GateForeignVMs bool `yaml:"-"`
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:"-"`
TunnelPrefixes []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 ¶
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 ¶
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 ¶
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.
type Confirmer ¶
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 ¶
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 ¶
func (a *ConsoleApprover) Request(ctx context.Context, req ApprovalRequest) Approval
Request prints the request and blocks until the operator decides, the request expires or ctx is cancelled.
func (*ConsoleApprover) WithPromptHook ¶ added in v0.28.0
func (a *ConsoleApprover) WithPromptHook(hook func(waiting bool)) *ConsoleApprover
WithPromptHook sets a function told when the console starts and stops waiting for the operator's input, e.g. to hide the live job output while they type. The hook runs while the console's lock is held, so it must not call back into the console.
type DisabledApprover ¶
type DisabledApprover struct{}
DisabledApprover rejects every request; used when the gateway has no terminal.
func (DisabledApprover) Request ¶
func (DisabledApprover) Request(context.Context, ApprovalRequest) Approval
Request always denies.
type Escalation ¶ added in v0.27.0
Escalation is why a job that looked safe needs operator approval.
type Gateway ¶
type Gateway struct {
// contains filtered or unexported fields
}
Gateway wires policy, execution, jobs and the MCP server together.
func (*Gateway) Close ¶
Close releases resources. Close cancels running jobs and background refreshes and waits for them, so no child process outlives the gateway.
func (*Gateway) Jobs ¶
func (g *Gateway) Jobs() *JobManager
Jobs exposes the job manager (tests and shutdown).
func (*Gateway) Listen ¶
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 ¶
RefreshTargets asks the pinned binary for every `<command> list --json`. The individual commands are not audited; one event records the refresh.
func (*Gateway) ServeListener ¶
ServeListener serves on a single TCP listener (tests).
func (*Gateway) ServeListeners ¶
ServeListeners serves on every open listener until ctx is cancelled.
func (*Gateway) ViewHandler ¶
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 {
MaxInstances int `json:"max_instances"`
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.
func (GrammarContext) ResolveVMTarget ¶ added in v0.27.0
func (ctx GrammarContext) ResolveVMTarget(listCommand, osName, osType, arch, engine string, names ...string) (VMTarget, error)
ResolveVMTarget validates a target and fills the CLI defaults (arch amd64; type server for OSes that list types, none for the others) against the targets that `sailwright <listCommand> list` reports. Every tool that names a VM goes through it, so jobs, vm_info, tunnels and ownership records agree on the VM's name.
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 id of the job that blocks new submissions, 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 ¶
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
// Live shows the newest lines of the running job on the gateway terminal. Follow
// takes precedence.
Live LiveTail
// 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 {
// BeforeRun reserves resources after approval and releases them on every exit.
BeforeRun func(context.Context) (func(), error)
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
// Env adds NAME=value entries to this job's child environment.
Env []string
// OnFinished runs after the command ran, before the job is reported done.
// succeeded is true only for exit code 0.
OnFinished func(jobID string, succeeded bool)
// Recheck runs in the job right before the command starts, under the job's
// context, for jobs that do not need approval yet. A non-nil result makes the
// job wait for operator approval after all. Slow checks (hypervisor queries)
// belong here rather than in the tool call, which must return quickly, and
// running them last narrows the gap between check and use.
Recheck func(ctx context.Context) *Escalation
}
JobSpec describes a job to run.
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.
type LineConfirmer ¶
LineConfirmer asks on a reader nobody else reads; used when the approval console is disabled but the gateway still runs on a terminal.
type ListTargetsOutput ¶
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.
type LiveConsole ¶ added in v0.28.0
type LiveConsole struct {
// contains filtered or unexported fields
}
LiveConsole is the gateway terminal with a small region at the bottom that shows the last lines of the running job. It redraws that region in place with VT sequences. Normal console output is written above it and stays in the scrollback. Every terminal write, on stdout and stderr, must go through the same LiveConsole, or the cursor math breaks.
func NewLiveConsole ¶ added in v0.28.0
func NewLiveConsole(out io.Writer, lines int, size func() (width, height int)) *LiveConsole
NewLiveConsole wraps out. The region shows up to lines job lines; size reports the terminal size (0 or less means unknown).
func (*LiveConsole) Begin ¶ added in v0.28.0
func (c *LiveConsole) Begin(id, logPath string) io.Writer
Begin starts the tail for a job and replaces a tail that is still shown.
func (*LiveConsole) Close ¶ added in v0.28.0
func (c *LiveConsole) Close()
Close removes the region; call it before the process exits.
func (*LiveConsole) End ¶ added in v0.28.0
func (c *LiveConsole) End(failed bool)
End removes the region. After a failure the last lines are printed as normal text.
func (*LiveConsole) Hold ¶ added in v0.28.0
func (c *LiveConsole) Hold(on bool)
Hold hides the region while the operator types an answer, so redraws do not overwrite the input. Holds nest.
type LiveTail ¶ added in v0.28.0
type LiveTail interface {
// Begin starts showing a job; output written to the returned writer appears in the tail.
Begin(id, logPath string) io.Writer
// End removes the tail. A failed job leaves its last lines in the scrollback.
End(failed bool)
}
LiveTail shows the newest output of the running job on the gateway terminal.
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
EmbeddedData 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 {
Name string
OS string
Type string
Arch string
Engine string
Address netip.Addr
NetworkMode string
Protocol string
Port int
Username string
Password string
// InstanceID is the hypervisor's VM identifier; empty when the engine has none.
InstanceID string
}
ManagedVM is a VM that sailwright created and that an agent may reach.
type ManagedVMResolver ¶
type ManagedVMResolver interface {
// Resolve may return a briefly cached result (repeated MCP calls).
Resolve(ctx context.Context, osName, osType, arch string, names ...string) (ManagedVM, error)
// ResolveFresh always queries current state (tunnel creation).
ResolveFresh(ctx context.Context, osName, osType, arch string, names ...string) (ManagedVM, error)
// Identify reports which VM instance exists, also for a stopped VM.
Identify(ctx context.Context, osName, osType, arch string, names ...string) (VMIdentity, error)
}
ManagedVMResolver resolves sailwright-managed VMs and their addresses. The /tunnel endpoint only connects to addresses returned here, never to addresses supplied by the agent. Some engines report addresses through the guest (for example the libvirt guest agent or Hyper-V integration services), so a guest controlled by the agent can influence them; allowedTunnelAddress and the port allowlist bound what such an address can reach.
type Operation ¶
type Operation struct {
Name string
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
// LiveTail shows the newest lines of the running job on the terminal; FollowOutput
// takes precedence.
LiveTail LiveTail
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 ¶
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. A redactor derived with With or WithRequired also applies its parent's current secrets, so secrets the parent learns later (AddRequired) are hidden in derived output too.
func NewRedactor ¶
NewRedactor builds a redactor; very short values are ignored to avoid mangling output.
func (*Redactor) AddRequired ¶ added in v0.27.0
AddRequired registers newly resolved guest secrets for subsequent audit and job output.
func (*Redactor) With ¶
With returns a redactor that also hides the given secrets, keeping r's minimum length.
func (*Redactor) WithRequired ¶
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 RegisteredWorkspace ¶ added in v0.28.0
type RegisteredWorkspace struct {
Agent string `json:"agent"`
Host string `json:"host"`
RegisteredAt time.Time `json:"registered_at"`
ApprovalID string `json:"approval_id,omitempty"`
}
RegisteredWorkspace is a workspace mapping added at runtime, either by the operator with `sailwright-gateway workspace add` or by an approved workspace_register call. Registered workspaces live in <state dir>/agent_workspaces.json, never in gateway.yaml.
func AddRegisteredWorkspace ¶ added in v0.28.0
func AddRegisteredWorkspace(cfg Config, mapping WorkspaceMapping, approvalID string) (RegisteredWorkspace, error)
AddRegisteredWorkspace validates mapping as a new agent-writable workspace and appends it to the registered workspaces. The host path is stored resolved.
func LoadRegisteredWorkspaces ¶ added in v0.28.0
func LoadRegisteredWorkspaces(cfg Config) ([]RegisteredWorkspace, error)
LoadRegisteredWorkspaces reads and validates the registered workspaces of cfg's state dir. A missing file means none.
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.
type ScreenFrame ¶
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 MCP and VM tunnels.
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, workspace WorkspaceMapping, rel string, displayRoot string, stagingRoot string, limits SnapshotLimits) (Snapshot, error)
CreateConfinedSnapshot snapshots the directory rel below the 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 ¶
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 ¶
AcquireStateLock takes the lock without blocking. It returns ErrStateLocked if another process holds it.
type Target ¶
type Target struct {
Name string `json:"name"`
OS string `json:"os"`
Type string `json:"type"`
Arch string `json:"arch"`
Engine string `json:"engine"`
Fields map[string]string `json:"fields,omitempty"`
// Exists is reported by `create list` (nil from CLIs before it was added).
Exists *bool `json:"exists,omitempty"`
}
Target is one entry of `<command> list --json` reported by the pinned binary.
func ParseTargetListing ¶
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 VMIdentity ¶ added in v0.27.0
VMIdentity tells which VM instance exists for a target; stopped VMs included.
type VMInfoOutput ¶ added in v0.27.0
type VMInfoOutput struct {
Name string `json:"name"`
OS string `json:"os"`
Type string `json:"type"`
Arch string `json:"arch"`
Engine string `json:"engine"`
Address string `json:"address"`
NetworkMode string `json:"network_mode"`
Protocol string `json:"protocol"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
SSHConfig string `json:"ssh_config"`
AnsibleInventory string `json:"ansible_inventory"`
ListenCommand string `json:"listen_command,omitempty"`
}
VMInfoOutput contains guest-only credentials and controller configuration.
type VMTarget ¶ added in v0.27.0
type VMTarget struct {
OS, Type, Arch, Name string
}
VMTarget names one VM the way the CLI does: Type is empty for OSes without types.
type WorkspaceMapping ¶
type WorkspaceMapping struct {
Agent string `yaml:"agent"`
Host string `yaml:"host"`
// Registered marks a mapping from agent_workspaces.json. The agent chose its host
// path, which may lie below its mount, so the path is pinned: it must still be
// the same real directory (no symlink anywhere) whenever it is used.
Registered bool `yaml:"-"`
}
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.
func ValidateNewWorkspace ¶ added in v0.28.0
func ValidateNewWorkspace(cfg Config, mapping WorkspaceMapping) (WorkspaceMapping, error)
ValidateNewWorkspace checks a mapping that is added at runtime. Besides the gateway.yaml rules, the host directory must exist and must not be a filesystem root or contain the user's home directory. The returned host path is resolved.
Source Files
¶
- approval.go
- audit.go
- become.go
- clean.go
- compatibility.go
- config.go
- disk_unix.go
- echo_linux.go
- echo_unix.go
- env.go
- exec.go
- exec_unix.go
- grammar.go
- httpmux.go
- instance_limit.go
- jobs.go
- listen.go
- liveconsole.go
- liveconsole_other.go
- lock.go
- lock_unix.go
- output.go
- ownership.go
- pin.go
- redact.go
- risk.go
- screens.go
- server.go
- snapshot.go
- targets.go
- token.go
- tools.go
- tunnel.go
- view.go
- vm_info.go
- vmresolver.go
- workspaces.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package client connects agents to a sailwright-gateway on the same machine or through a mounted agent directory in a devcontainer.
|
Package client connects agents to a sailwright-gateway on the same machine or through a mounted agent directory in a devcontainer. |
|
Package gatewaytest starts a real sailwright-gateway against a fake sailwright CLI.
|
Package gatewaytest starts a real sailwright-gateway against a fake sailwright CLI. |