Documentation
¶
Overview ¶
Package sshdemo is the supervisor of the public SSH demo of the DataTug terminal workspace (`datatug demo ssh-server`): a Charmbracelet Wish server that serves only interactive PTY sessions and runs each one as a separate child process of the same executable (`datatug demo ssh-session`) under its own slot uid, with per-session workspace, limits and cleanup. It also holds the edge forwarder and allow-listing egress proxy (`datatug demo ssh-edge`).
Design: spec/features/ssh-demo/README.md. Nothing here renders a UI or knows about DataTug projects beyond preparing the read-only template.
Index ¶
- Constants
- Variables
- func BuildChildArgs(cfg Config, workspace, templateDir, sessionID string, deadline time.Time) []string
- func BuildChildEnv(homeDir, term, colorTerm, egressProxy string) []string
- func BuildCleanupArgs(workspace string) []string
- func BuildPrepareTemplateArgs(templateDir, projectDir string) []string
- func CheckHealth(ctx context.Context, addr string, timeout time.Duration) error
- func CheckHealthProxyLocal(ctx context.Context, addr string, timeout time.Duration) error
- func ClampWindow(w ssh.Window) ssh.Window
- func CleanWorkspaceContents(path string, progress func()) error
- func EncodeProxyV2(src, dst net.Addr) []byte
- func EnterSlot(entry SlotEntry) error
- func FormatHostKey(signer gossh.Signer) string
- func LoadOrGenerateHostKey(path string) (gossh.Signer, error)
- func PrepareTemplate(ctx context.Context, cfg TemplateConfig) (string, error)
- func PrintHostKey(path string, w io.Writer) error
- func RunEdge(ctx context.Context, cfg EdgeConfig) error
- func RunServer(ctx context.Context, cfg Config, opts ...ServerOption) error
- type Config
- type Edge
- type EdgeConfig
- type Server
- type ServerOption
- type Slot
- type SlotEntry
- type SlotManager
- type SysOps
- type TemplateConfig
Constants ¶
const ( CleanupProgress = "\x01" CleanupInvariant = "\x02" )
Cleanup helper stdout protocol. The helper reports progress on its first deletion, so the supervisor can observe it even after a timeout or OOM kill.
const ( DefaultListen = ":2222" DefaultStateDir = "/var/lib/datatug-demo" DefaultSessionsDir = "/run/datatug-demo/sessions" DefaultCgroupRoot = "/sys/fs/cgroup" DefaultRepo = "https://github.com/datatug/datatug-demo-project" DefaultProjectDir = "demo-project-1" DefaultMaxSessions = 6 DefaultMaxQueue = 20 DefaultMaxQueueWait = 30 * time.Minute DefaultMaxSessionsPerIP = 2 DefaultIdleTimeout = 15 * time.Minute DefaultMaxSessionDuration = 60 * time.Minute DefaultHandshakeTimeout = 20 * time.Second DefaultShellStartTimeout = 30 * time.Second DefaultSessionMemQuota = 384 << 20 DefaultSessionDiskQuota = 160 << 20 DefaultWatchdogInterval = time.Second DefaultUIDBase = 20000 DefaultGitHubClientID = "Ov23liAIKfguW2oYiore" DefaultSaveBranch = "datatug-demo" IsolationUID = "uid" IsolationProcess = "process" DefaultShutdownGrace = 10 * time.Second DefaultCleanupTimeout = 120 * time.Second DefaultCleanupMemLimit = 96 << 20 DefaultCleanupPIDsLimit = 32 DefaultSlotReuseMemoryThreshold = 16 << 20 // Child rlimit defaults (spec D3). RlimitAS = 8589934592 // 8 GiB of address space for the cgo binary (Go + DuckDB) RlimitCPU = 900 // 900 s RlimitFSize = 67108864 // 64 MiB RlimitNoFile = 512 // ChildGoMemLimit is the GOMEMLIMIT of every session child. ChildGoMemLimit = "256MiB" RlimitNProc = 256 // per uid; Linux counts threads too (Go runtime + DuckDB) // PTY initial dimension bounds (spec D3). MinPTYWidth = 1 MinPTYHeight = 1 MaxPTYWidth = 500 MaxPTYHeight = 200 // Health check defaults. DefaultHealthAddr = "127.0.0.1:2222" DefaultHealthTimeout = 5 * time.Second // Edge forwarder and proxy defaults. DefaultEdgeListen = ":2222" DefaultEdgeUpstream = "demo:2222" DefaultEdgeProxyListen = "/run/datatug-demo/proxy/connect.sock" DefaultEdgeMaxConns = 256 DefaultEdgeMaxConnsPerIP = 8 DefaultEdgeMaxTunnels = 64 DefaultEdgeMaxTunnelsPerIP = DefaultEdgeMaxTunnels DefaultProxyMaxConns = 128 DefaultSessionMaxTunnels = 8 DefaultRelaySocketsPerUID = 16 DefaultEdgeIdleTimeout = 5 * time.Minute )
Default configuration values matching spec/features/ssh-demo/README.md.
const ( // Session end reasons logged in structured JSON output. EndReasonClientExit = "client-exit" EndReasonClientDrop = "client-drop" EndReasonIdle = "idle" EndReasonMaxDuration = "max-duration" EndReasonFull = "full" EndReasonShutdown = "shutdown" EndReasonChildCrash = "child-crash" EndReasonMemQuota = "memory-quota" )
const SlotReadyFD = 3
SlotReadyFD is the first extra file passed by the supervisor. After successful slot entry, the child writes one byte and closes it.
Variables ¶
var ( // ErrGlobalLimit is returned when all session slots are occupied. ErrGlobalLimit = errors.New("sshdemo: global session limit reached") // ErrPerIPLimit is returned when a client IP reached its concurrent session cap. ErrPerIPLimit = errors.New("sshdemo: per-ip session limit reached") )
var DefaultEdgeAllow = []string{
"github.com",
"api.github.com",
"codeload.github.com",
"cloud.openvaultdb.com",
}
DefaultEdgeAllow is the default allow-list of hosts reachable via the edge HTTP CONNECT proxy (spec D4).
var ErrCleanupBoundary = errors.New("cleanup left the workspace device or root")
ErrCleanupBoundary identifies an invariant violation in workspace traversal.
Functions ¶
func BuildChildArgs ¶
func BuildChildArgs(cfg Config, workspace, templateDir, sessionID string, deadline time.Time) []string
BuildChildArgs constructs the exact argument list for `demo ssh-session`.
func BuildChildEnv ¶
BuildChildEnv returns a clean, minimal environment for the session child. It never inherits the supervisor's environment.
func BuildCleanupArgs ¶
BuildCleanupArgs constructs the argument list for `demo ssh-session --cleanup`.
func BuildPrepareTemplateArgs ¶
BuildPrepareTemplateArgs constructs the exact argument list for `demo ssh-session --prepare-template <dir> --project-dir <rel>`.
func CheckHealth ¶
CheckHealth dials addr over TCP and verifies that the server answers with a banner line starting with "SSH-2.0-".
func CheckHealthProxyLocal ¶
CheckHealthProxyLocal probes a server that listens with --proxy-protocol: it first sends a PROXY v2 LOCAL header, the command the PROXY protocol defines for health checks (the server keeps the connection's real address).
func ClampWindow ¶
ClampWindow clamps PTY dimensions to [MinPTYWidth..MaxPTYWidth] x [MinPTYHeight..MaxPTYHeight].
func CleanWorkspaceContents ¶
CleanWorkspaceContents empties a drained workspace using only directory descriptors and single entry names. The caller removes the workspace itself.
func EncodeProxyV2 ¶
EncodeProxyV2 builds a PROXY protocol v2 binary header carrying src and dst TCP addresses. If either address is not a TCP address, it encodes a valid LOCAL/UNSPEC v2 header.
func EnterSlot ¶
EnterSlot migrates the calling process to its slot and permanently drops privileges on all threads. The child must exit on any error.
func FormatHostKey ¶
FormatHostKey formats the public key line (`ssh-ed25519 AAAA...`) and its SHA256 fingerprint (`SHA256:...`) on two lines.
func LoadOrGenerateHostKey ¶
LoadOrGenerateHostKey loads an SSH host key from path, refusing unreadable, invalid, or group/world-accessible files without ever overwriting them. When path does not exist, it generates an ed25519 key once and writes it atomically with mode 0600.
func PrepareTemplate ¶
func PrepareTemplate(ctx context.Context, cfg TemplateConfig) (string, error)
PrepareTemplate clones cfg.Repo at cfg.Ref (default branch when empty) with go-git (depth 1, no submodules) into <state-dir>/template.tmp, verifies <project-dir>/datatug-project.json exists, writes the bundled Chinook SQLite fixture to <project-dir>/.demo-data/chinook.sqlite when absent, runs template preparation (scanning local catalogs and committing prepared metadata), ensures the tree is world-readable without removing any existing mode bits, and atomically replaces <state-dir>/template only after the new tree is complete.
func PrintHostKey ¶
PrintHostKey loads (or generates once when absent) the host key at path and writes its public key and SHA256 fingerprint to w.
Types ¶
type Config ¶
type Config struct {
Listen string
ProxyProtocol bool
ProxyProtocolTrust []string
HostKey string
StateDir string
SessionsDir string
Repo string
Ref string
ProjectDir string
MaxSessions int
MaxQueue int // zero disables the queue
MaxQueueWait time.Duration
MaxSessionsPerIP int
MaxConnections int // zero defaults to MaxSessions + MaxQueue, with headroom
IdleTimeout time.Duration
MaxSessionDuration time.Duration
HandshakeTimeout time.Duration
ShellStartTimeout time.Duration
SessionMemQuota uint64
SessionDiskQuota uint64
Isolation string
UIDBase int
AllowInsecureIsolation bool
GitHubClientID string
SaveBranch string
EgressProxy string
CgroupRoot string
MaxRelaySocketsPerUID int
MaxSessionTunnels int
MaxEgressTunnels int
CleanupMemLimit uint64
CleanupPIDsLimit int
SlotReuseMemoryThreshold uint64
// Optional overrides for logging, lifecycle tuning and tests.
Logger *slog.Logger
Executable string
ExecPrefixArgs []string
ShutdownGrace time.Duration
CleanupTimeout time.Duration
WatchdogInterval time.Duration
SkipTemplate bool
}
Config configures the SSH demo supervisor server (`datatug demo ssh-server`).
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config populated with the specification defaults.
func (Config) ResolvedHostKey ¶
ResolvedHostKey returns the effective host key path after applying defaults.
func (Config) Validate ¶
Validate checks that the configuration satisfies all safety and sanity rules.
func (Config) WithDefaults ¶
WithDefaults returns a copy of c with zero-valued fields replaced by defaults.
type Edge ¶
type Edge struct {
// contains filtered or unexported fields
}
Edge runs the TCP PROXY-v2 SSH forwarder and the allow-listing HTTP CONNECT proxy.
func (*Edge) ProxyHandler ¶
ProxyHandler returns the http.Handler implementing the allow-listing CONNECT proxy.
func (*Edge) Run ¶
Run starts both the TCP forwarder and the HTTP CONNECT proxy and blocks until ctx is canceled or either server returns a fatal error.
func (*Edge) Serve ¶
Serve runs the TCP forwarder on fwdLn and the HTTP CONNECT proxy on proxyLn until ctx is canceled.
func (*Edge) ServeForwarder ¶
ServeForwarder accepts TCP connections on ln, dials e.cfg.Upstream, writes a PROXY protocol v2 header, and splices both ways. Loopback uses a reserved pool and a LOCAL header so health checks work at public capacity.
type EdgeConfig ¶
type EdgeConfig struct {
Listen string
Upstream string
ProxyListen string
Allow []string
MaxConns int
MaxConnsPerIP int
MaxTunnels int
MaxTunnelsPerIP int // zero defaults to MaxTunnels
MaxProxyConns int
IdleTimeout time.Duration
DialTimeout time.Duration
Logger *slog.Logger
LookupIPAddr func(ctx context.Context, host string) ([]net.IPAddr, error)
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
}
EdgeConfig configures `datatug demo ssh-edge` (spec D4).
func DefaultEdgeConfig ¶
func DefaultEdgeConfig() EdgeConfig
DefaultEdgeConfig returns an EdgeConfig populated with specification defaults. WithDefaults resolves the per-IP tunnel cap from the configured global cap.
func (EdgeConfig) WithDefaults ¶
func (c EdgeConfig) WithDefaults() EdgeConfig
WithDefaults returns a copy of c with zero-valued fields replaced by defaults.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the Wish-backed SSH demo supervisor.
func NewServer ¶
NewServer prepares the host key, sessions directory, template clone, and Wish SSH server according to cfg.
func (*Server) HostSigner ¶
HostSigner returns the loaded or generated SSH host signer.
func (*Server) Shutdown ¶
Shutdown stops accepting new connections, signals active sessions to finish (waiting up to ShutdownGrace before killing and cleaning up every session), and waits for all session cleanups to finish.
func (*Server) TemplateDir ¶
TemplateDir returns the prepared template directory path.
type ServerOption ¶
type ServerOption func(*Server)
ServerOption customizes Server construction (primarily for tests).
func WithChinookBytes ¶
func WithChinookBytes(b []byte) ServerOption
WithChinookBytes overrides the Chinook bytes written into the template.
func WithPanicHookForTest ¶
func WithPanicHookForTest(fn func()) ServerOption
WithPanicHookForTest injects a callback invoked inside handleSession right after workspace allocation so tests can verify panic recovery & cleanup.
func WithSysOps ¶
func WithSysOps(ops SysOps) ServerOption
WithSysOps overrides the OS-level seams used for uid isolation.
type Slot ¶
type Slot struct {
Index int
UID int
GID int
ClientIP string
// contains filtered or unexported fields
}
Slot identifies one reserved session slot and its Unix credentials.
type SlotManager ¶
type SlotManager struct {
// contains filtered or unexported fields
}
SlotManager tracks concurrent session slots and per-IP caps.
func NewSlotManager ¶
func NewSlotManager(maxSessions, maxPerIP, uidBase int, isolation string) *SlotManager
NewSlotManager creates a SlotManager for the given limits and isolation mode.
func (*SlotManager) Acquire ¶
func (m *SlotManager) Acquire(clientIP string) (Slot, error)
Acquire reserves a free slot for clientIP or returns ErrPerIPLimit / ErrGlobalLimit.
func (*SlotManager) ActiveCount ¶
func (m *SlotManager) ActiveCount() int
ActiveCount returns the number of currently occupied slots.
func (*SlotManager) InSlotRange ¶
func (m *SlotManager) InSlotRange(uid int) bool
InSlotRange reports whether uid falls within [uidBase, uidBase+maxSessions).
func (*SlotManager) Release ¶
func (m *SlotManager) Release(slot Slot)
Release frees a previously acquired slot. A stale reservation cannot free the slot after it has been handed to another visitor. The client IP stays charged for the slot until it is usable again: a slot awaiting cleanup or memory release, or quarantined, still counts against its last visitor.
type SysOps ¶
type SysOps struct {
FilesystemCapacity func(string) (size, inodes uint64, err error)
Stat func(string) (os.FileInfo, error) // Lstat semantics for session paths.
InterfaceAddrs func() ([]net.Addr, error) // The container's own addresses, refused as SSH clients.
Chown func(string, int, int) error
Kill func(int, syscall.Signal) error
FileUID func(os.FileInfo) (int, bool)
FileGID func(os.FileInfo) (int, bool)
// contains filtered or unexported fields
}
SysOps groups OS-level operations used for uid isolation so unit tests can verify uid-mode paths without running as root.
func DefaultSysOps ¶
func DefaultSysOps() SysOps
DefaultSysOps returns production OS operations backed by Linux syscalls and cgroupfs.
type TemplateConfig ¶
type TemplateConfig struct {
StateDir string
Repo string
Ref string
ProjectDir string
EgressProxy string
Executable string
ExecPrefixArgs []string
// PrepareFunc optionally overrides invoking Executable with
// `demo ssh-session --prepare-template` (seam for tests).
PrepareFunc func(ctx context.Context, templateDir, projectDir string) error
// ChinookBytes optionally overrides the embedded Chinook SQLite fixture
// (useful in tests to keep test I/O tiny).
ChinookBytes []byte
}
TemplateConfig controls how PrepareTemplate clones and prepares the read-only demo project template.
Source Files
¶
- capacity.go
- cgroup.go
- cleanup_dir_linux.go
- cleanup_protocol.go
- cleanup_queue.go
- config.go
- connect.go
- doc.go
- edge.go
- health.go
- hostkey.go
- inet_diag_linux.go
- log.go
- memory_notice.go
- mount_linux.go
- proxy_protocol.go
- queue_channel.go
- relay.go
- relay_uid.go
- seccomp_linux.go
- server.go
- session.go
- slot_entry.go
- slot_entry_linux.go
- slots.go
- template.go
- waiting_queue.go