Files
ARTEX-chixuweihu/internal/sandbox/types.go
T
ji ruo 9c43e694a3 feat(sandbox): isolate worker/chat execution in Docker containers with lifecycle UI
- Add Docker sandbox manager, non-root sandbox image, compose isolation, and host firewall script (#217)
- Route Bash, custom commands/scripts, stdio MCP, chat sessions, MainAgent chat, and task-scoped reporter screenshots into sandbox containers with per-task browser concurrency gate
- Enforce proxy SSRF guard against loopback, metadata, internal services, and admin port
- Add dedicated /system/sandbox management page, /chat session sandbox control, and task detail sandbox popover with progressive stats loading
2026-12-01 21:13:21 +08:00

313 lines
9.1 KiB
Go

package sandbox
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Mode controls whether agent execution runs locally or inside isolated Docker containers.
type Mode string
const (
ModeLocal Mode = "local"
ModeDocker Mode = "docker"
)
// Scope identifies what owns a sandbox container.
type Scope string
const (
ScopeTask Scope = "task"
ScopeSession Scope = "session"
ScopeEphemeral Scope = "ephemeral"
)
// ContainerWorkDir is the canonical workspace mount point inside every sandbox container.
const ContainerWorkDir = "/workspace"
// ContainerCACertPath is where the recording MITM proxy CA cert is mounted read-only.
const ContainerCACertPath = "/etc/artex/ca.crt"
// Target identifies a logical sandbox instance.
type Target struct {
Scope Scope
OwnerID string
}
func (t Target) Valid() bool {
return t.Scope != "" && strings.TrimSpace(t.OwnerID) != ""
}
func (t Target) Key() string {
return string(t.Scope) + ":" + t.OwnerID
}
// Config configures the sandbox manager. Env vars supply startup defaults;
// persisted DB settings can override mutable runtime fields via ApplyOverrides.
type Config struct {
Mode Mode
DockerHost string
Image string
Network string
Runtime string
DataDir string
HostDataDir string
ProxyURL string
CACertPath string
MemoryMB int
CPUs float64
PidsLimit int
ShmSizeMB int
TmpSizeMB int
User string
AutoStopOnComplete bool
SessionIdleMinutes int
InstanceID string
}
// RuntimeOverrides carries settings editable from the Settings UI / API.
type RuntimeOverrides struct {
Image *string `json:"image,omitempty"`
MemoryMB *int `json:"memory_mb,omitempty"`
CPUs *float64 `json:"cpus,omitempty"`
PidsLimit *int `json:"pids_limit,omitempty"`
ShmSizeMB *int `json:"shm_size_mb,omitempty"`
Runtime *string `json:"runtime,omitempty"`
AutoStopOnComplete *bool `json:"auto_stop_on_complete,omitempty"`
SessionIdleMinutes *int `json:"session_idle_minutes,omitempty"`
}
// ConfigFromEnv builds a Config from environment variables with safe defaults.
func ConfigFromEnv(dataDir, caCertPath string) Config {
mode := Mode(strings.ToLower(strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_MODE"))))
if mode != ModeDocker {
mode = ModeLocal
}
dockerHost := strings.TrimSpace(os.Getenv("ARTEX_DOCKER_HOST"))
if dockerHost == "" {
dockerHost = strings.TrimSpace(os.Getenv("DOCKER_HOST"))
}
if dockerHost == "" {
dockerHost = "unix:///var/run/docker.sock"
}
hostDataDir := strings.TrimSpace(os.Getenv("ARTEX_HOST_DATA_DIR"))
if hostDataDir == "" {
hostDataDir = dataDir
}
image := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_IMAGE"))
if image == "" {
image = "ruoji6/artex-sandbox:latest"
}
network := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_NETWORK"))
if network == "" {
network = "artex-sandbox"
}
user := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_USER"))
if user == "" {
user = "1000:1000"
}
instanceID := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_INSTANCE"))
if instanceID == "" {
sum := sha256.Sum256([]byte(filepath.Clean(hostDataDir)))
instanceID = hex.EncodeToString(sum[:4])
}
return Config{
Mode: mode,
DockerHost: dockerHost,
Image: image,
Network: network,
Runtime: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_RUNTIME")),
DataDir: filepath.Clean(dataDir),
HostDataDir: filepath.Clean(hostDataDir),
ProxyURL: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_PROXY_URL")),
CACertPath: strings.TrimSpace(caCertPath),
MemoryMB: envInt("ARTEX_SANDBOX_MEMORY_MB", 2048, 256),
CPUs: envFloat("ARTEX_SANDBOX_CPUS", 2.0, 0.25),
PidsLimit: envInt("ARTEX_SANDBOX_PIDS_LIMIT", 256, 32),
ShmSizeMB: envInt("ARTEX_SANDBOX_SHM_MB", 512, 64),
TmpSizeMB: envInt("ARTEX_SANDBOX_TMP_MB", 512, 64),
User: user,
AutoStopOnComplete: envBool("ARTEX_SANDBOX_AUTO_STOP", true),
SessionIdleMinutes: envInt("ARTEX_SANDBOX_SESSION_IDLE_MIN", 20, 1),
InstanceID: instanceID,
}
}
func envInt(key string, def, min int) int {
raw := strings.TrimSpace(os.Getenv(key))
if raw == "" {
return def
}
v, err := strconv.Atoi(raw)
if err != nil || v < min {
return def
}
return v
}
func envFloat(key string, def, min float64) float64 {
raw := strings.TrimSpace(os.Getenv(key))
if raw == "" {
return def
}
v, err := strconv.ParseFloat(raw, 64)
if err != nil || v < min {
return def
}
return v
}
func envBool(key string, def bool) bool {
raw := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
switch raw {
case "1", "true", "yes", "on":
return true
case "0", "false", "no", "off":
return false
default:
return def
}
}
// ContainerInfo describes one sandbox container for API/UI reporting.
type ContainerInfo struct {
Scope Scope `json:"scope"`
OwnerID string `json:"owner_id"`
OwnerTitle string `json:"owner_title,omitempty"`
TaskRunning bool `json:"task_running,omitempty"`
Name string `json:"name"`
ContainerID string `json:"container_id,omitempty"`
ShortID string `json:"short_id,omitempty"`
Image string `json:"image"`
State string `json:"state"` // running | exited | created | missing | local | error
StatusText string `json:"status_text,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
StartedAt string `json:"started_at,omitempty"`
ActiveRuns int `json:"active_runs"`
CPUPercent float64 `json:"cpu_percent,omitempty"`
MemUsageBytes uint64 `json:"mem_usage_bytes,omitempty"`
MemLimitBytes uint64 `json:"mem_limit_bytes,omitempty"`
PidsCurrent uint64 `json:"pids_current,omitempty"`
WorkDirContainer string `json:"work_dir_container"`
Network string `json:"network,omitempty"`
Runtime string `json:"runtime,omitempty"`
Error string `json:"error,omitempty"`
}
// GlobalStatus is returned by GET /api/sandbox/status.
type GlobalStatus struct {
Mode Mode `json:"mode"`
Enabled bool `json:"enabled"`
Available bool `json:"available"`
Error string `json:"error,omitempty"`
Image string `json:"image"`
Network string `json:"network"`
Runtime string `json:"runtime"`
MemoryMB int `json:"memory_mb"`
CPUs float64 `json:"cpus"`
PidsLimit int `json:"pids_limit"`
ShmSizeMB int `json:"shm_size_mb"`
AutoStopOnComplete bool `json:"auto_stop_on_complete"`
SessionIdleMinutes int `json:"session_idle_minutes"`
Containers []ContainerInfo `json:"containers"`
}
// ExecSpec describes one command invocation inside a sandbox container.
type ExecSpec struct {
Cmd []string
WorkDir string // container path; defaults to ContainerWorkDir
Env []string
Stdin []byte
Timeout time.Duration
MaxOutput int
KillOnAbort bool // wrap with PGID tracking so cancel/timeout kills child tree
}
// ExecResult captures the result of a foreground sandbox Exec.
type ExecResult struct {
Output string
OutputTruncated bool
ExitCode int
TimedOut bool
Err error
}
// StreamSession represents a live bidirectional stdio exec inside a sandbox.
type StreamSession struct {
Stdin io.WriteCloser
Stdout io.ReadCloser
Stderr io.ReadCloser
waitFn func() (int, error)
closeFn func() error
}
func (s *StreamSession) Wait() (int, error) {
if s == nil || s.waitFn == nil {
return 0, nil
}
return s.waitFn()
}
func (s *StreamSession) Close() error {
if s == nil || s.closeFn == nil {
return nil
}
return s.closeFn()
}
type targetCtxKey struct{}
// WithTarget attaches a sandbox Target to ctx.
func WithTarget(ctx context.Context, t Target) context.Context {
if !t.Valid() {
return ctx
}
return context.WithValue(ctx, targetCtxKey{}, t)
}
// TargetFrom extracts the sandbox Target from ctx, if present.
func TargetFrom(ctx context.Context) (Target, bool) {
if ctx == nil {
return Target{}, false
}
t, ok := ctx.Value(targetCtxKey{}).(Target)
if !ok || !t.Valid() {
return Target{}, false
}
return t, true
}
// ContainerName returns a deterministic, Docker-safe container name for target.
func (c Config) ContainerName(t Target) string {
cleanID := sanitizeToken(t.OwnerID)
return fmt.Sprintf("artex-sbx-%s-%s-%s", c.InstanceID, string(t.Scope), cleanID)
}
func sanitizeToken(s string) string {
var b strings.Builder
for _, r := range strings.ToLower(strings.TrimSpace(s)) {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
b.WriteRune(r)
} else {
b.WriteByte('-')
}
}
out := strings.Trim(b.String(), "-")
if out == "" {
return "0"
}
if len(out) > 48 {
out = out[:48]
}
return out
}