package server import ( "context" "encoding/json" "log" "net" "net/http" "net/url" "os" "strings" "time" "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/artex/traffic" ) const settingSandboxOverrides = "sandbox_settings_json" // initSandbox wires the global sandbox manager, applies persisted UI overrides, // reconciles orphan containers on startup, starts the idle session reaper, and // configures the recording proxy SSRF guard. func (s *Server) initSandbox() { caCert := "" if s.m.traffic != nil { caCert = s.m.traffic.CACertPath() } cfg := sandbox.ConfigFromEnv(s.dataDir, caCert) mgr, err := sandbox.New(cfg) if err != nil { log.Printf("[sandbox] init failed (falling back to local): %v", err) cfg.Mode = sandbox.ModeLocal mgr, _ = sandbox.New(cfg) } if s.m.pg != nil { if raw, ok, _ := s.m.pg.GetSetting(settingSandboxOverrides); ok && strings.TrimSpace(raw) != "" { var ov sandbox.RuntimeOverrides if json.Unmarshal([]byte(raw), &ov) == nil { mgr.ApplyOverrides(ov) } } } sandbox.SetDefault(mgr) // Build merged system + MITM CA bundle so sandbox containers trust the recording // proxy at the system CA store level (/etc/ssl/certs/ca-certificates.crt) without root. if s.m.traffic != nil { if bundle := s.m.traffic.EnsureSystemCABundle(); bundle != "" { mgr.SetSystemCABundlePath(bundle) } s.m.traffic.SetGatewayToken(os.Getenv("ARTEX_GATEWAY_TOKEN")) } // Always load persisted egress blacklist rules, per-container proxy routes, // gateway settings, and task-level egress checker (works in both local & Docker modes). s.syncEgressBlacklist() s.initProxyRoutesAndGateway() if s.m.traffic != nil { s.m.traffic.SetTaskBlacklistChecker(s.checkTaskEgressBlacklist) } s.startEmbeddedTransparentGatewayIfConfigured() if !mgr.Enabled() { log.Printf("[sandbox] mode=local (set ARTEX_SANDBOX_MODE=docker to enable container isolation)") return } validTasks := map[string]bool{} for _, t := range s.m.List() { validTasks[t.ID] = true } var validSessions map[string]bool if s.m.pg != nil { if convs, err := s.m.pg.ListConversations(); err == nil { validSessions = make(map[string]bool, len(convs)) for _, c := range convs { validSessions[s.convBusyKey(c.ID)] = true } } } rctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) defer cancel() if err := mgr.ReconcileOnStartup(rctx, validTasks, validSessions); err != nil { log.Printf("[sandbox] startup reconcile warning: %v", err) } else { log.Printf("[sandbox] mode=docker image=%s network=%s runtime=%q mem=%dMiB cpus=%.2f", mgr.Config().Image, mgr.Config().Network, mgr.Config().Runtime, mgr.Config().MemoryMB, mgr.Config().CPUs) } mgr.StartBackgroundReaper(s.ctx) // Enable SSRF guard on the recording proxy so sandbox containers cannot pivot // through :8788 to reach :8787, postgres, docker-socket-proxy, or cloud metadata. if s.m.traffic != nil { blockedHosts := []string{"artex", "postgres", "docker-socket-proxy"} if pgHost := parsePGHostFromEnv(); pgHost != "" { blockedHosts = append(blockedHosts, pgHost) } blockPrivate := strings.EqualFold(strings.TrimSpace(os.Getenv("ARTEX_PROXY_BLOCK_PRIVATE")), "true") || strings.TrimSpace(os.Getenv("ARTEX_PROXY_BLOCK_PRIVATE")) == "1" s.m.traffic.EnableSSRFGuard(traffic.SSRFGuardConfig{ Enabled: true, BlockPrivate: blockPrivate, BlockedHosts: blockedHosts, BlockedCIDRs: mgr.SandboxSubnets(), InfraIPs: parseProtectIPs(os.Getenv("ARTEX_PROXY_PROTECT_IPS")), }) s.m.traffic.SetSourceResolver(func(srcIP string) (traffic.SourceIdentity, bool) { id, ok := mgr.ResolveContainerByIP(srcIP) if !ok { return traffic.SourceIdentity{}, false } return traffic.SourceIdentity{ Scope: string(id.Scope), OwnerID: id.OwnerID, ContainerID: id.ContainerID, SrcIP: srcIP, }, true }) } } func parseProtectIPs(raw string) []net.IP { var out []net.IP for _, part := range strings.FieldsFunc(raw, func(r rune) bool { return r == ',' || r == ';' || r == ' ' || r == '\n' || r == '\t' }) { if ip := net.ParseIP(strings.TrimSpace(part)); ip != nil { out = append(out, ip) } } return out } func parsePGHostFromEnv() string { dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) if dsn == "" { return "" } if u, err := url.Parse(dsn); err == nil && u.Hostname() != "" { return u.Hostname() } return "" } // blockSandboxAdminAccess rejects HTTP requests to :8787 coming from inside the // isolated sandbox Docker network. func (s *Server) blockSandboxAdminAccess(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if mgr := sandbox.Default(); mgr != nil && mgr.IsSandboxSourceIP(r.RemoteAddr) { http.Error(w, "forbidden: sandbox container cannot access ARTEX management API", http.StatusForbidden) return } next.ServeHTTP(w, r) }) } func (s *Server) enrichSandboxContainer(ci *sandbox.ContainerInfo) { if ci == nil { return } if ci.Scope == sandbox.ScopeTask { if t, ok := s.m.Task(ci.OwnerID); ok { title := strings.TrimSpace(t.Name) if title == "" { title = strings.TrimSpace(t.Description) } ci.OwnerTitle = title ci.TaskRunning = s.resolvedTaskStatus(t) == "running" } } } // GET /api/sandbox/status func (s *Server) sandboxStatus(w http.ResponseWriter, r *http.Request) { mgr := sandbox.Default() if mgr == nil { writeJSON(w, 200, sandbox.GlobalStatus{Mode: sandbox.ModeLocal, Available: true, Containers: []sandbox.ContainerInfo{}}) return } withStats := r.URL.Query().Get("stats") == "1" ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) defer cancel() st := mgr.StatusWithStats(ctx, withStats) for i := range st.Containers { s.enrichSandboxContainer(&st.Containers[i]) } writeJSON(w, 200, st) } // PUT /api/sandbox/settings func (s *Server) updateSandboxSettings(w http.ResponseWriter, r *http.Request) { var ov sandbox.RuntimeOverrides if err := json.NewDecoder(r.Body).Decode(&ov); err != nil { writeErr(w, 400, "bad json: "+err.Error()) return } if ov.MemoryMB != nil && (*ov.MemoryMB < 256 || *ov.MemoryMB > 65536) { writeErr(w, 400, "内存上限必须在 256 到 65536 MiB 之间") return } if ov.CPUs != nil && (*ov.CPUs < 0.25 || *ov.CPUs > 64) { writeErr(w, 400, "CPU 上限必须在 0.25 到 64 之间") return } if ov.PidsLimit != nil && (*ov.PidsLimit < 32 || *ov.PidsLimit > 8192) { writeErr(w, 400, "进程数上限必须在 32 到 8192 之间") return } if ov.ShmSizeMB != nil && (*ov.ShmSizeMB < 64 || *ov.ShmSizeMB > 8192) { writeErr(w, 400, "共享内存上限必须在 64 到 8192 MiB 之间") return } if ov.SessionIdleMinutes != nil && (*ov.SessionIdleMinutes < 1 || *ov.SessionIdleMinutes > 1440) { writeErr(w, 400, "对话空闲停机时间必须在 1 到 1440 分钟之间") return } if mgr := sandbox.Default(); mgr != nil { mgr.ApplyOverrides(ov) if s.m.pg != nil { cfg := mgr.Config() persisted := sandbox.RuntimeOverrides{ Image: &cfg.Image, MemoryMB: &cfg.MemoryMB, CPUs: &cfg.CPUs, PidsLimit: &cfg.PidsLimit, ShmSizeMB: &cfg.ShmSizeMB, Runtime: &cfg.Runtime, AutoStopOnComplete: &cfg.AutoStopOnComplete, SessionIdleMinutes: &cfg.SessionIdleMinutes, } if b, err := json.Marshal(persisted); err == nil { _ = s.m.pg.SetSetting(settingSandboxOverrides, string(b)) } } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() writeJSON(w, 200, mgr.Status(ctx)) return } writeJSON(w, 200, sandbox.GlobalStatus{Mode: sandbox.ModeLocal, Available: true, Containers: []sandbox.ContainerInfo{}}) } // POST /api/sandbox/prune func (s *Server) pruneSandboxContainers(w http.ResponseWriter, r *http.Request) { mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeJSON(w, 200, map[string]any{"removed": 0}) return } ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() removed, err := mgr.PruneStopped(ctx) if err != nil { writeErr(w, 500, err.Error()) return } writeJSON(w, 200, map[string]any{"removed": removed}) } // GET /api/sandbox/containers/{scope}/{id} func (s *Server) getSandboxContainer(w http.ResponseWriter, r *http.Request) { target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) { writeErr(w, 400, "无效的沙箱目标") return } mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeJSON(w, 200, sandbox.ContainerInfo{ Scope: target.Scope, OwnerID: target.OwnerID, State: "local", WorkDirContainer: sandbox.ContainerWorkDir, }) return } withStats := r.URL.Query().Get("stats") != "0" ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) defer cancel() info, _ := mgr.Inspect(ctx, target, withStats) s.enrichSandboxContainer(&info) writeJSON(w, 200, info) } // POST /api/sandbox/containers/{scope}/{id}/start func (s *Server) startSandboxContainer(w http.ResponseWriter, r *http.Request) { mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeErr(w, 400, "沙箱容器模式未开启") return } target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) { writeErr(w, 400, "无效的沙箱目标") return } mgr.ClearIdleStop(target) ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() if _, err := mgr.Ensure(ctx, target); err != nil { writeErr(w, 500, err.Error()) return } info, _ := mgr.Inspect(ctx, target, true) s.enrichSandboxContainer(&info) writeJSON(w, 200, info) } // POST /api/sandbox/containers/{scope}/{id}/recreate func (s *Server) recreateSandboxContainer(w http.ResponseWriter, r *http.Request) { mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeErr(w, 400, "沙箱容器模式未开启") return } target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) { writeErr(w, 400, "无效的沙箱目标") return } var req struct { PauseTask bool `json:"pause_task"` ClearWorkspace bool `json:"clear_workspace"` } _ = json.NewDecoder(r.Body).Decode(&req) if target.Scope == sandbox.ScopeTask { if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" { if !req.PauseTask { writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再重建容器") return } _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) } } mgr.ClearIdleStop(target) ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() info, err := mgr.Recreate(ctx, target, req.ClearWorkspace) if err != nil { writeErr(w, 500, err.Error()) return } s.enrichSandboxContainer(&info) writeJSON(w, 200, info) } // POST /api/sandbox/containers/{scope}/{id}/stop func (s *Server) stopSandboxContainer(w http.ResponseWriter, r *http.Request) { mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeErr(w, 400, "沙箱容器模式未开启") return } target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} if !target.Valid() { writeErr(w, 400, "无效的沙箱目标") return } if target.Scope == sandbox.ScopeTask { if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" { _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) } } ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() if err := mgr.Stop(ctx, target); err != nil { writeErr(w, 500, err.Error()) return } info, _ := mgr.Inspect(ctx, target, false) s.enrichSandboxContainer(&info) writeJSON(w, 200, info) } // DELETE /api/sandbox/containers/{scope}/{id} func (s *Server) removeSandboxContainer(w http.ResponseWriter, r *http.Request) { mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeErr(w, 400, "沙箱容器模式未开启") return } target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")} if !target.Valid() { writeErr(w, 400, "无效的沙箱目标") return } if target.Scope == sandbox.ScopeTask { if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" { _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) } } ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() if err := mgr.Remove(ctx, target); err != nil { writeErr(w, 500, err.Error()) return } writeJSON(w, 200, map[string]any{"removed": target.Key()}) } // GET /api/tasks/{id}/sandbox func (s *Server) getTaskSandbox(w http.ResponseWriter, r *http.Request) { t, ok := s.m.Task(r.PathValue("id")) if !ok { writeErr(w, 404, "task not found") return } mgr := sandbox.Default() target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} if mgr == nil || !mgr.Enabled() { writeJSON(w, 200, sandbox.ContainerInfo{ Scope: sandbox.ScopeTask, OwnerID: t.ID, State: "local", WorkDirContainer: sandbox.ContainerWorkDir, }) return } withStats := r.URL.Query().Get("stats") != "0" ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) defer cancel() info, _ := mgr.Inspect(ctx, target, withStats) writeJSON(w, 200, info) } // POST /api/tasks/{id}/sandbox/start func (s *Server) startTaskSandbox(w http.ResponseWriter, r *http.Request) { t, ok := s.m.Task(r.PathValue("id")) if !ok { writeErr(w, 404, "task not found") return } mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeErr(w, 400, "沙箱容器模式未开启") return } target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} mgr.ClearIdleStop(target) ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() if _, err := mgr.Ensure(ctx, target); err != nil { writeErr(w, 500, err.Error()) return } info, _ := mgr.Inspect(ctx, target, true) writeJSON(w, 200, info) } // POST /api/tasks/{id}/sandbox/stop func (s *Server) stopTaskSandbox(w http.ResponseWriter, r *http.Request) { t, ok := s.m.Task(r.PathValue("id")) if !ok { writeErr(w, 404, "task not found") return } mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeErr(w, 400, "沙箱容器模式未开启") return } var req struct { PauseTask bool `json:"pause_task"` } _ = json.NewDecoder(r.Body).Decode(&req) status := s.resolvedTaskStatus(t) if status == "running" { if !req.PauseTask { writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再停止容器") return } _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) } target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() if err := mgr.Stop(ctx, target); err != nil { writeErr(w, 500, err.Error()) return } info, _ := mgr.Inspect(ctx, target, false) writeJSON(w, 200, info) } // POST /api/tasks/{id}/sandbox/recreate func (s *Server) recreateTaskSandbox(w http.ResponseWriter, r *http.Request) { t, ok := s.m.Task(r.PathValue("id")) if !ok { writeErr(w, 404, "task not found") return } mgr := sandbox.Default() if mgr == nil || !mgr.Enabled() { writeErr(w, 400, "沙箱容器模式未开启") return } var req struct { PauseTask bool `json:"pause_task"` ClearWorkspace bool `json:"clear_workspace"` } _ = json.NewDecoder(r.Body).Decode(&req) if s.resolvedTaskStatus(t) == "running" { if !req.PauseTask { writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再重建容器") return } _, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser) } target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID} mgr.ClearIdleStop(target) ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() info, err := mgr.Recreate(ctx, target, req.ClearWorkspace) if err != nil { writeErr(w, 500, err.Error()) return } writeJSON(w, 200, info) }