Files
ARTEX-chixuweihu/internal/sandbox/types.go
T
ji ruo d786de90af feat(traffic,sandbox): add TUN/netstack transparent gateway, egress controls, CAP_NET_RAW hardening, and i18n fixes
- Implement full-traffic transparent gateway (cmd/artex-gateway, traffic/netstack.go, traffic/transparent.go) using Linux TUN + gVisor netstack deferred TCP handshakes (eliminating nmap/nc false-positive open ports), real ICMPv4 Echo proxying, UDP/DNS interception, and per-container upstream proxy overrides.
- Add egress blacklist + asset-intercept sync, non-HTTP flow/DNS SQLite persistence and APIs, and /system/proxy & /function/traffic TCP/UDP/DNS UI panels.
- Fix sandbox Playwright MCP browser loopback --proxy-server rewrite and NODE_EXTRA_CA_CERTS override in server/mcpstdio.go.
- Strip all SUID/SGID binaries in Dockerfile.sandbox, grant minimal cap_net_raw+ep to nmap/nping/ping with ARTEX_SANDBOX_ALLOW_NET_RAW toggle, and enforce IPv4/IPv6 anti-spoofing in iptables and netstack.
- Remove hardcoded Chinese "(全局)" from GET /api/proxy/routes, localize ContainerRoutesTab / NonHTTPTrafficPanel labels, and expose reactive locale/isEn from useLiveTranslation for React Compiler compatibility.
2026-12-02 02:51:36 +08:00

334 lines
10 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"
// ContainerSystemCABundlePath is where the merged system + ARTEX MITM CA bundle
// is mounted read-only so static Go binaries and system TLS libraries trust the
// recording proxy without needing root or runtime update-ca-certificates (#218 Phase 3).
const ContainerSystemCABundlePath = "/etc/ssl/certs/ca-certificates.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
SystemCABundlePath string
TransparentGateway bool
GatewayDNSIP string
MemoryMB int
CPUs float64
PidsLimit int
ShmSizeMB int
TmpSizeMB int
User string
AllowNetRaw bool
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),
TransparentGateway: envBool("ARTEX_SANDBOX_TRANSPARENT", true),
GatewayDNSIP: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_DNS")),
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,
AllowNetRaw: envBool("ARTEX_SANDBOX_ALLOW_NET_RAW", true),
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 ContainerIdentity struct {
Scope Scope `json:"scope"`
OwnerID string `json:"owner_id"`
ContainerID string `json:"container_id"`
ShortID string `json:"short_id"`
ContainerName string `json:"container_name"`
IP string `json:"ip"`
}
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"`
IPAddress string `json:"ip_address,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
}