sshdemo

package
v0.160.7 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 50 Imported by: 1 module, 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 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

View Source
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.

View Source
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.

View Source
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"
)
View Source
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

View Source
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")
)
View Source
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).

View Source
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

func BuildChildEnv(homeDir, term, colorTerm, egressProxy string) []string

BuildChildEnv returns a clean, minimal environment for the session child. It never inherits the supervisor's environment.

func BuildCleanupArgs

func BuildCleanupArgs(workspace string) []string

BuildCleanupArgs constructs the argument list for `demo ssh-session --cleanup`.

func BuildPrepareTemplateArgs

func BuildPrepareTemplateArgs(templateDir, projectDir string) []string

BuildPrepareTemplateArgs constructs the exact argument list for `demo ssh-session --prepare-template <dir> --project-dir <rel>`.

func CheckHealth

func CheckHealth(ctx context.Context, addr string, timeout time.Duration) error

CheckHealth dials addr over TCP and verifies that the server answers with a banner line starting with "SSH-2.0-".

func CheckHealthProxyLocal

func CheckHealthProxyLocal(ctx context.Context, addr string, timeout time.Duration) error

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

func ClampWindow(w ssh.Window) ssh.Window

ClampWindow clamps PTY dimensions to [MinPTYWidth..MaxPTYWidth] x [MinPTYHeight..MaxPTYHeight].

func CleanWorkspaceContents

func CleanWorkspaceContents(path string, progress func()) error

CleanWorkspaceContents empties a drained workspace using only directory descriptors and single entry names. The caller removes the workspace itself.

func EncodeProxyV2

func EncodeProxyV2(src, dst net.Addr) []byte

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

func EnterSlot(entry SlotEntry) error

EnterSlot migrates the calling process to its slot and permanently drops privileges on all threads. The child must exit on any error.

func FormatHostKey

func FormatHostKey(signer gossh.Signer) string

FormatHostKey formats the public key line (`ssh-ed25519 AAAA...`) and its SHA256 fingerprint (`SHA256:...`) on two lines.

func LoadOrGenerateHostKey

func LoadOrGenerateHostKey(path string) (gossh.Signer, error)

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

func PrintHostKey(path string, w io.Writer) error

PrintHostKey loads (or generates once when absent) the host key at path and writes its public key and SHA256 fingerprint to w.

func RunEdge

func RunEdge(ctx context.Context, cfg EdgeConfig) error

RunEdge constructs an Edge from cfg and runs it until ctx is canceled.

func RunServer

func RunServer(ctx context.Context, cfg Config, opts ...ServerOption) error

RunServer creates a Server, listens on cfg.Listen, serves until ctx is canceled, then gracefully shuts down all sessions.

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

func (c Config) ResolvedHostKey() string

ResolvedHostKey returns the effective host key path after applying defaults.

func (Config) Validate

func (c Config) Validate() error

Validate checks that the configuration satisfies all safety and sanity rules.

func (Config) WithDefaults

func (c Config) WithDefaults() Config

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 NewEdge

func NewEdge(cfg EdgeConfig) *Edge

NewEdge constructs an Edge instance from cfg.

func (*Edge) ProxyHandler

func (e *Edge) ProxyHandler() http.Handler

ProxyHandler returns the http.Handler implementing the allow-listing CONNECT proxy.

func (*Edge) Run

func (e *Edge) Run(ctx context.Context) error

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

func (e *Edge) Serve(ctx context.Context, fwdLn, proxyLn net.Listener) error

Serve runs the TCP forwarder on fwdLn and the HTTP CONNECT proxy on proxyLn until ctx is canceled.

func (*Edge) ServeForwarder

func (e *Edge) ServeForwarder(ctx context.Context, ln net.Listener) error

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

func NewServer(ctx context.Context, cfg Config, opts ...ServerOption) (*Server, error)

NewServer prepares the host key, sessions directory, template clone, and Wish SSH server according to cfg.

func (*Server) HostSigner

func (s *Server) HostSigner() gossh.Signer

HostSigner returns the loaded or generated SSH host signer.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve accepts SSH connections on ln until Shutdown or Close is called.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

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

func (s *Server) TemplateDir() string

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 SlotEntry

type SlotEntry struct {
	CgroupDir string
	UID       int
	GID       int
}

SlotEntry identifies the cgroup and credentials for a UID-isolated session child.

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.
	StatSharedTemp func(string) (os.FileInfo, error) // Stat follows links to shared temporary directories.
	ChmodShared    func(string, os.FileMode) error   // Chmod locks shared device entry points to root.
	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.

Jump to

Keyboard shortcuts

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