mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
egress-guard reads hand-edited lists/scope-domains.txt and scope-cidrs.txt, while the sandbox egress proxy builds its policy from PostgreSQL. Nothing connected the two, so the overlay could drift from the approved scope (#421). egress-guard/export-scope.sh regenerates both lists through the new artex -export-egress-guard-scope. The export calls taskSandboxRunInfoChecked (the error-returning form of taskSandboxRunInfo) and sandbox.NewEgressPolicy, the derivation and parser of the per-task proxy, so only operator-approved task scope, frozen company grants and operator task allow rules are exported. Agent-added, auto-added and expanded rows are not. Fail closed: taskSandboxRunInfoChecked reports the read errors the proxy path ignores, any error fails the whole export, and the script touches neither list until a complete, well-formed export was read; each list is then replaced by rename. An empty export is refused unless --allow-empty, because empty lists with EGRESS_MODE unset make the guard fall back to monitor. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
218 lines
7.8 KiB
Go
218 lines
7.8 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/Autumn-27/artex/agent"
|
|
"github.com/Autumn-27/artex/db"
|
|
"github.com/Autumn-27/artex/sandbox"
|
|
)
|
|
|
|
// SandboxClient is the subset of *sandbox.Client used by the panel server & engine.
|
|
type SandboxClient interface {
|
|
Health(ctx context.Context) (sandbox.HealthResponse, error)
|
|
Exec(ctx context.Context, taskID string, req sandbox.ExecRequest) (sandbox.ExecResponse, error)
|
|
Kill(ctx context.Context, taskID string) (sandbox.KillResponse, error)
|
|
Delete(ctx context.Context, taskID string) (sandbox.DeleteResponse, error)
|
|
}
|
|
|
|
// pauseTaskForSandboxFailure shares the task-control transition so runtime, UI
|
|
// and persisted pause state agree. Deletion/terminal guards still apply.
|
|
func (s *Server) pauseTaskForSandboxFailure(taskID string, runnerErr error) {
|
|
task, ok := s.m.Task(taskID)
|
|
if !ok {
|
|
return
|
|
}
|
|
log.Printf("[sandbox] runner unavailable for task %s (%v): pausing task (no local fallback)", taskID, runnerErr)
|
|
if _, err := s.applyTaskControlWithCause(task, "pause", agent.AbortSandboxUnavailable); err != nil {
|
|
log.Printf("[sandbox] task %s pause: %v", taskID, err)
|
|
}
|
|
}
|
|
|
|
// WithSandbox configures the panel's sandbox execution mode ("required" or "off")
|
|
// and its artex-runner client (CONTRACT.md §6).
|
|
func WithSandbox(client SandboxClient, mode string) Option {
|
|
return func(s *Server) {
|
|
s.sandboxClient = client
|
|
s.sandboxMode = mode
|
|
}
|
|
}
|
|
|
|
// LogSandboxOffBanner logs one prominent startup warning when ARTEX_SANDBOX=off
|
|
// is explicitly selected (CONTRACT.md §6).
|
|
func LogSandboxOffBanner() {
|
|
bar := strings.Repeat("!", 78)
|
|
log.Print("[sandbox] " + bar)
|
|
log.Print("[sandbox] !! WARNING: SANDBOX IS OFF (ARTEX_SANDBOX=off) — EXPLICIT DEGRADED MODE.")
|
|
log.Print("[sandbox] !! Agent commands will execute locally on the panel container instead of")
|
|
log.Print("[sandbox] !! isolated per-task artex-worker containers. Do not use with untrusted targets.")
|
|
log.Print("[sandbox] " + bar)
|
|
}
|
|
|
|
// checkSandboxReady verifies artex-runner is reachable and connected to Docker
|
|
// before starting a task in ARTEX_SANDBOX=required mode.
|
|
func (s *Server) checkSandboxReady(ctx context.Context) error {
|
|
if s.sandboxMode != sandbox.ModeRequired {
|
|
return nil
|
|
}
|
|
if s.sandboxClient == nil {
|
|
return fmt.Errorf("%w: ARTEX_SANDBOX=required but no runner client is configured (set ARTEX_RUNNER_URL and ARTEX_RUNNER_TOKEN)", sandbox.ErrRunnerUnavailable)
|
|
}
|
|
hctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
h, err := s.sandboxClient.Health(hctx)
|
|
if err != nil {
|
|
return fmt.Errorf("cannot start task: sandbox runner unavailable (%w)", err)
|
|
}
|
|
if !h.OK || !h.Docker {
|
|
return fmt.Errorf("cannot start task: %w (health ok=%v docker=%v)", sandbox.ErrDockerUnavailable, h.OK, h.Docker)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// taskSandboxRunInfo builds the per-task sandbox metadata (including scope
|
|
// domains and CIDRs for the per-task egress proxy) from PostgreSQL.
|
|
func taskSandboxRunInfo(pg *db.DB, dataDir, taskID string) agent.SandboxRunInfo {
|
|
// A read error leaves the scope narrower, which the deny-by-default proxy
|
|
// turns into a denial, so the error is not needed here.
|
|
info, _ := taskSandboxRunInfoChecked(pg, dataDir, taskID)
|
|
return info
|
|
}
|
|
|
|
// taskSandboxRunInfoChecked is taskSandboxRunInfo plus the read errors it met.
|
|
// The returned scope is the same either way; a caller that persists the scope
|
|
// (the egress-guard export) uses the error to refuse a partial result.
|
|
func taskSandboxRunInfoChecked(pg *db.DB, dataDir, taskID string) (agent.SandboxRunInfo, error) {
|
|
info := agent.SandboxRunInfo{
|
|
TaskID: taskID,
|
|
TaskDir: filepath.Join(dataDir, "tasks", taskID),
|
|
}
|
|
if pg == nil {
|
|
return info, errors.New("no database")
|
|
}
|
|
tid, err := strconv.ParseInt(taskID, 10, 64)
|
|
if err != nil || tid <= 0 {
|
|
return info, fmt.Errorf("invalid task id %q", taskID)
|
|
}
|
|
var errs []error
|
|
seenDom := map[string]bool{}
|
|
seenCIDR := map[string]bool{}
|
|
addDom := func(d string) {
|
|
d = strings.ToLower(strings.TrimSpace(d))
|
|
d = strings.TrimPrefix(d, "*.")
|
|
d = strings.TrimPrefix(d, ".")
|
|
if d != "" && !seenDom[d] {
|
|
seenDom[d] = true
|
|
info.ScopeDomains = append(info.ScopeDomains, d)
|
|
}
|
|
}
|
|
addCIDR := func(c string) {
|
|
c = strings.TrimSpace(c)
|
|
if c != "" && !seenCIDR[c] {
|
|
seenCIDR[c] = true
|
|
info.ScopeCIDRs = append(info.ScopeCIDRs, c)
|
|
}
|
|
}
|
|
var companyIDs []int64
|
|
seenComp := map[int64]bool{}
|
|
if rows, err := pg.Query(`SELECT kind, COALESCE(domain,''), COALESCE(net::text,''), COALESCE(value,''), COALESCE(company_id,0) FROM task_scope WHERE task_id=$1 AND approved_by_operator=true AND COALESCE(expanded,false)=false`, tid); err == nil {
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var kind, dom, netStr, val string
|
|
var compID int64
|
|
if err := rows.Scan(&kind, &dom, &netStr, &val, &compID); err != nil {
|
|
errs = append(errs, fmt.Errorf("task_scope: %w", err))
|
|
} else {
|
|
switch kind {
|
|
case "company":
|
|
if compID > 0 && !seenComp[compID] {
|
|
seenComp[compID] = true
|
|
companyIDs = append(companyIDs, compID)
|
|
}
|
|
case "domain", "root_domain", "subdomain":
|
|
if dom != "" {
|
|
addDom(dom)
|
|
} else {
|
|
addDom(val)
|
|
}
|
|
case "cidr", "ip", "ip_range":
|
|
if netStr != "" {
|
|
addCIDR(netStr)
|
|
} else {
|
|
addCIDR(val)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
errs = append(errs, fmt.Errorf("task_scope: %w", err))
|
|
}
|
|
} else {
|
|
errs = append(errs, fmt.Errorf("task_scope: %w", err))
|
|
}
|
|
// Company grants are frozen at operator-approval time in task_scope_egress.
|
|
// Reading live company_scope/assets here let the planner's add_company_scope
|
|
// widen an approved task's egress without a new operator decision.
|
|
for _, cid := range companyIDs {
|
|
entries, err := pg.CompanyEgressForTask(tid, cid)
|
|
if err != nil {
|
|
errs = append(errs, fmt.Errorf("task_scope_egress: %w", err))
|
|
continue
|
|
}
|
|
for _, e := range entries {
|
|
switch e.Kind {
|
|
case "domain":
|
|
addDom(e.Value)
|
|
case "cidr":
|
|
addCIDR(e.Value)
|
|
}
|
|
}
|
|
}
|
|
if rows, err := pg.Query(`SELECT kind, pattern FROM task_intercept_rules WHERE task_id=$1 AND enabled=true AND action='allow'`, tid); err == nil {
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var kind, pat string
|
|
if err := rows.Scan(&kind, &pat); err != nil {
|
|
errs = append(errs, fmt.Errorf("task_intercept_rules: %w", err))
|
|
} else {
|
|
switch kind {
|
|
case "exact_domain", "domain_suffix":
|
|
addDom(pat)
|
|
// The single-address kind is exact_ip (asset_intercept_match.go);
|
|
// NewEgressPolicy reads a bare address as a host prefix.
|
|
case "cidr", "exact_ip":
|
|
addCIDR(pat)
|
|
}
|
|
}
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
errs = append(errs, fmt.Errorf("task_intercept_rules: %w", err))
|
|
}
|
|
} else {
|
|
errs = append(errs, fmt.Errorf("task_intercept_rules: %w", err))
|
|
}
|
|
return info, errors.Join(errs...)
|
|
}
|
|
|
|
// emptyEgressScopeWarning describes the chat-spawn scope trap (#830): the task
|
|
// carries task_scope rows, but none of them widen the sandbox egress
|
|
// allowlist (agent-stamped rows are coverage-only until an operator approves
|
|
// them), so the per-task proxy starts empty and denies every connection. ""
|
|
// when there is nothing to warn about.
|
|
func emptyEgressScopeWarning(pg *db.DB, tid int64, info agent.SandboxRunInfo) string {
|
|
if pg == nil || tid <= 0 || len(info.ScopeDomains) > 0 || len(info.ScopeCIDRs) > 0 {
|
|
return ""
|
|
}
|
|
var n int
|
|
if err := pg.QueryRow(`SELECT count(*) FROM task_scope WHERE task_id=$1`, tid).Scan(&n); err != nil || n == 0 {
|
|
return ""
|
|
}
|
|
return fmt.Sprintf("sandbox egress empty: this task has %d scope row(s), but none currently grant egress, so every connection from the sandbox will be denied. Agent-added scope is coverage-only until an operator approves it; once the scope is approved, the egress proxy is recreated with the new allowlist without restarting the task.", n)
|
|
}
|