isolation

package
v2.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 14 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 isolation builds the per-agent-process sandbox a session or task attempt can run inside, as a fast, no-clone alternative to the full LXC clone in internal/sandbox: bubblewrap (no daemon, Linux only) or a disposable Docker container.

internal/sandbox's "container IS the isolation" tier stays the strongest guarantee lectern offers — a whole disposable machine. This package is the tier competitors actually ship for every agent turn (agent-deck, Sculptor: one Docker container per agent; Codex/Cursor: a microVM): sub-second to start, filesystem-scoped, with network egress either left alone or routed through an allowlist. See docs/isolation.md for the threat model this buys and, just as importantly, does not.

Index

Constants

View Source
const DefaultDockerImage = "debian:bookworm-slim"

DefaultDockerImage is used when a Docker isolation config names none. It only needs a shell; the agent binary itself is expected to reach the container through the workdir/config mounts (a project that wants its own toolchain baked in sets docker_image explicitly).

View Source
const DefaultRuntimeDir = "/tmp/lectern-isolation"

DefaultRuntimeDir holds every session's egress-proxy unix socket. It is unrelated to any project's working tree on purpose — a bwrap sandbox's bind mounts should not have to reach outside the workdir to find it, and a stray socket file must never end up inside a git worktree.

Variables

View Source
var AgentHomePaths = map[string][]string{
	"claude": {".claude", ".claude.json"},
	"codex":  {".codex"},
	"gemini": {".gemini", ".config/gemini"},
}

AgentHomePaths is the explicit, per-agent list of $HOME entries an agent keeps its own login/auth/config in, bound read-write into the sandbox so an already-authenticated CLI keeps working and any token refresh persists. This is deliberately a fixed, reviewed list rather than "the whole home directory": that is the entire point of the sandbox. A custom agent name not listed here gets no extra bind — see docs/isolation.md.

View Source
var Modes = []Mode{None, Bwrap, Docker}

Modes lists every valid Mode, for validation and the UI's picker.

Networks lists every valid NetworkPolicy.

Functions

func BuildBwrapArgv

func BuildBwrapArgv(cfg Config, o WrapOpts) ([]string, error)

BuildBwrapArgv renders the bubblewrap invocation up to (not including) the trailing `-- <command>`. It is a pure function of its inputs: no file- or environment-probing, so it is safe to unit test without a real bwrap binary. $HOME-relative binds use a literal "$HOME/..." shell token, expanded by bash at run time on whichever machine actually executes the command — this package never assumes it knows the target's home directory.

The system paths mirror tools/run-isolated-tests.sh's own bwrap profile (a reviewed, working reference for this exact repo's Debian hosts): --ro-bind-try tolerates a host missing /lib64 or /sbin (e.g. non-x86_64) rather than failing the whole launch over an optional path.

func BuildDockerArgv

func BuildDockerArgv(cfg Config, o WrapOpts) ([]string, error)

BuildDockerArgv renders `docker run` up to (not including) the trailing `bash -c <command>`. Like BuildBwrapArgv it is a pure function of its inputs. $HOME-relative mounts use a literal "$HOME/..." shell token so the same command works whichever machine's docker daemon actually runs it — see BuildBwrapArgv's comment.

Network policy: allow leaves Docker's own default bridge network in place (the agent reaches the internet exactly as an unisolated launch would); deny is `--network none` — real, kernel-enforced, and total. There is no egress-proxy bridge for Docker in this release (see NetworkDeny's doc comment and docs/isolation.md), so a denied Docker session has no network at all, not even its own model API. Callers that want network=deny with a reachable model API should use bwrap on a local target instead.

func DefaultAllowHosts

func DefaultAllowHosts(agent, hookURL string) []string

DefaultAllowHosts is the baseline egress allowlist under network=deny, before any project-specific AllowHosts: this agent's own model API, the package registries an agent-driven build commonly reaches for, and — whenever hookURL is non-empty — the Lectern host that session's own hooks call back to. Omitting that last one silently kills the statusline and Stop/UserPromptSubmit events for every isolated session (docs/agent-events.md).

func HomePaths

func HomePaths(agent string) []string

HomePaths returns agent's explicit list of $HOME entries, or nil for an agent this package does not know the config layout of.

func ValidateForTarget

func ValidateForTarget(c Config, targetKind string) error

ValidateForTarget additionally rejects combinations that are only deployable on the machine lectern's own control process runs on. Network deny needs its allowlist proxy reachable by an operator-local unix-domain socket (bwrap) or `--network none` (docker); neither of those crosses a network to an ssh/pct target. Isolation on a "sandbox" target is also rejected — that target IS a disposable container already; wrapping it again buys nothing and only adds friction. See docs/isolation.md.

func Wrap

func Wrap(invocation string, cfg Config, o WrapOpts) (string, error)

Wrap renders one already-built agent invocation (the env-prefixed command line a caller would otherwise have run directly) as it should actually run under cfg. None returns invocation unchanged — every existing launch path keeps behaving exactly as it does today.

The caller is responsible for the surrounding "cd workdir && ...; exec bash"/redirection wrapping that sessions.Spec.LaunchCommand and agents.Launcher.Command already build: Wrap only replaces the command that runs, not how its stdio is captured or how the pane exits.

Types

type AllowlistProxy

type AllowlistProxy struct {
	// Allow is the set of hostnames (bare, e.g. "api.anthropic.com") or
	// "*.suffix" wildcards this proxy accepts. Checked case-insensitively.
	Allow []string
	// Dial defaults to a plain net.Dialer; tests override it to point at a
	// fixture without touching a real socket.
	Dial func(ctx context.Context, network, addr string) (net.Conn, error)
}

AllowlistProxy is the "deny" network policy's one egress path. A sandboxed process reaches it over HTTP_PROXY/HTTPS_PROXY convention (both plain-HTTP forwarding and HTTPS CONNECT tunneling are handled), and only a host in Allow is let through. Everything else gets 403 before a single byte crosses the boundary.

This is deliberately a plain host allowlist, not a full egress firewall: it does not inspect TLS SNI against the CONNECT target (they are the same value here, since the client names the host in the CONNECT line itself, but a process that lies about its own CONNECT target and then speaks TLS to a different SNI inside the tunnel is not caught). See docs/isolation.md.

func NewAllowlistProxy

func NewAllowlistProxy(allow []string) *AllowlistProxy

NewAllowlistProxy builds a proxy that only accepts the given hosts.

func (*AllowlistProxy) Serve

func (p *AllowlistProxy) Serve(l net.Listener) error

Serve runs the proxy on l until it is closed. It never returns a nil error: use errors.Is(err, net.ErrClosed) (or a Close from the caller) to tell a deliberate shutdown from a real failure.

func (*AllowlistProxy) ServeHTTP

func (p *AllowlistProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler: CONNECT tunnels (HTTPS and anything else that CONNECTs first); every other request is treated as a standard forward-proxy request with an absolute-URI request line, which is how curl/npm/pip and Go's own http.Transport all speak to HTTP_PROXY for a plain-http:// target — the path the session's own hook callback uses.

type Config

type Config struct {
	Mode    Mode          `json:"mode,omitempty"`
	Network NetworkPolicy `json:"network,omitempty"`
	// DockerImage is only meaningful when Mode is Docker.
	DockerImage string `json:"docker_image,omitempty"`
	// AllowHosts are additional hostnames the egress proxy accepts CONNECT
	// and forwarded requests for when Network is deny, layered on top of
	// DefaultAllowHosts. Ignored otherwise.
	AllowHosts []string `json:"allow_hosts,omitempty"`
}

Config is one session or task's isolation choice. It is small and JSON stable on purpose: it rides inside sessions.LaunchConfiguration and agents.TaskLaunchConfig so a resume/relaunch reproduces it exactly, and inside store.Project as that project's default for new launches.

func (Config) Normalized

func (c Config) Normalized() Config

Normalized fills in defaults and clears fields that mean nothing for the chosen mode, so two configs that behave identically also compare equal.

func (Config) Validate

func (c Config) Validate() error

Validate rejects a config this package cannot honestly build a wrapper for, independent of which target it would run on.

type Mode

type Mode string

Mode selects how an agent process is contained. The zero value, None, is today's behaviour: the agent runs directly on the target, unsandboxed.

const (
	None   Mode = ""
	Bwrap  Mode = "bwrap"
	Docker Mode = "docker"
)

type NetworkPolicy

type NetworkPolicy string

NetworkPolicy controls egress once a session is isolated.

const (
	// NetworkAllow leaves networking exactly as the target already has it —
	// the same as an unisolated launch. This is the default: most agents are
	// useless without their model API.
	NetworkAllow NetworkPolicy = "allow"
	// NetworkDeny routes every request through Lectern's own allowlist proxy
	// (proxy.go). For bwrap this is real, kernel-enforced network denial
	// (--unshare-net) with only the bridged proxy path left open, and it
	// requires a local target — see ValidateForTarget and docs/isolation.md.
	// Docker's network=deny is `--network none`: no proxy bridge exists for
	// Docker in this release, so a denied Docker session has no network at
	// all, including its own model API. That is a deliberate, documented v1
	// limit, not an oversight.
	NetworkDeny NetworkPolicy = "deny"
)

type ProxyRegistry

type ProxyRegistry struct {
	// Dir overrides DefaultRuntimeDir; tests point it at a temp directory.
	Dir string
	// contains filtered or unexported fields
}

ProxyRegistry keeps one AllowlistProxy alive per session or attempt for as long as its bwrap network=deny sandbox is running, and tears it down when the caller reports it ended. A launch's proxy outlives the tmux-launch call that started it — tmux sessions are detached and long-running, so the proxy has to be too.

func NewProxyRegistry

func NewProxyRegistry(log *slog.Logger) *ProxyRegistry

NewProxyRegistry builds an empty registry.

func (*ProxyRegistry) Running

func (r *ProxyRegistry) Running(id int64) bool

Running reports whether id currently has a live proxy — tests use this to confirm Stop actually tore one down.

func (*ProxyRegistry) Start

func (r *ProxyRegistry) Start(id int64, allow []string) (socketPath string, err error)

Start opens id's egress proxy on a fresh unix socket and begins serving in the background. The returned path is what the sandbox's bind mount and BuildBwrapArgv's ProxySocket both need. Calling Start again for an id that already has one replaces it — a relaunch or resume gets a fresh proxy.

func (*ProxyRegistry) Stop

func (r *ProxyRegistry) Stop(id int64)

Stop closes id's proxy, if one is running, and removes its socket file. It is always safe to call, including for an id with no live proxy or on a nil registry (a Manager built without sessions.New's constructor never started one, so this is a deliberate no-op rather than a crash).

type WrapOpts

type WrapOpts struct {
	// EnvironmentFile is a private, read-only launch environment staged by the caller.
	EnvironmentFile string
	// Agent selects AgentHomePaths.
	Agent string
	// Workdir is bind-mounted read-write and is where the sandboxed shell
	// starts. Required.
	Workdir string
	// ProxySocket is the host-side unix socket path an already-running
	// AllowlistProxy is serving on (see registry.go). Required when the
	// config's Network is deny for bwrap; ignored otherwise.
	ProxySocket string
}

WrapOpts is what Wrap needs beyond the Config to build one command.

Jump to

Keyboard shortcuts

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