ARTEX/agent/sandbox_test.go
BaaRai 643e814ad6 security: isolate task execution in per-task sandbox worker and egress proxy
Introduce the sandbox MVP architecture separating panel credentials and
PostgreSQL access from model-controlled tool execution:

- Runner service (cmd/artex-runner, sandbox/) owning /var/run/docker.sock
  behind bearer-token auth (ARTEX_RUNNER_TOKEN) with POST /v1/tasks/{id}/exec,
  POST /v1/tasks/{id}/kill, DELETE /v1/tasks/{id}, and GET /v1/health.
- Strict input and env validation (400 on forbidden secret/DB/cloud env
  patterns or values > 8192 bytes, strict task ID and /workspace workdir).
- Hardened per-task worker containers (Dockerfile.worker, artex-worker:local,
  cmd/artex-exec-wrap): uid/gid 10001, artex-exec-wrap --init PID 1 zombie
  reaper, read-only rootfs, cap-drop ALL, no-new-privileges, pids/mem/cpu
  limits, tmpfs /tmp and /home/exec, only /app/data/tasks/<id>:/workspace:rw,
  only verified internal=true runner-labeled network artex-task-<id>.
- Kernel-backed kill-switch (zero agent-writable state): Kill executes
  artex-exec-wrap --kill-uid 10001 as uid 10001 scanning /proc directly
  (defeating setsid, nohup, nested double-forked trap-TERM daemons, and /tmp
  tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls
  back to force-removing the worker container if any check fails. Dead
  workers/proxies are recreated automatically when startContainer fails.
- Operator-only scope approval (migration 0023_task_scope_operator_approval.sql):
  adds task_scope.approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE, set
  true exclusively by operator API/UI (AddOperatorScope) and operator-selected
  TaskCreateOptions.CompanyIDs (insertTaskCompanies). AddAgentScope and
  AddAutoScope leave it false (coverage-only). taskSandboxRunInfo reads only
  approved, non-expanded rows (and expands company scope only for approved
  company rows); tasks with no approved scope deny all egress.
- Per-task egress proxy (cmd/artex-egress-proxy, Dockerfile.egress-proxy,
  artex-egress-proxy:local): HTTP/HTTPS CONNECT (:3128) and SOCKS5 (:1080),
  deny-by-default allowlist with strict domain suffix enforcement, blocks
  RFC1918/loopback/link-local/IMDS and IPv6 unless in scope CIDRs, DNS
  pinning, and tamper-proof JSONL audit logging to a proxy-only mount
  (/app/data/egress-audit/<id>:/audit:rw) never mounted into the worker.
- Panel integration (agent/sandbox.go, agent/webfetch.go, server/sandbox.go,
  server/sharedbrowser_guard.go, server/assembly.go, server/customtool.go,
  docker-compose.sandbox.yml): ARTEX_SANDBOX defaults to required (fail closed,
  no local fallback), WebFetch and opt-in shared browser inherit the
  operator-approved sandbox.EgressPolicy (with target_gate or explicit proxy
  required for shared browser), custom script tools staged via symlink-confined
  workspace files (avoiding argv E2BIG), Pause/Stop/Delete wired to runner
  Kill/Delete.
- Documented breaking change and hardening details in docs/SANDBOX.md,
  README.md, and CHANGELOG.md.
2026-11-30 19:09:32 +01:00

72 lines
2.4 KiB
Go

package agent
import (
"context"
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Autumn-27/artex/sandbox"
actool "github.com/Autumn-27/norma/tool"
)
// TestSandboxWebFetchBlocksNonScopeIP verifies that in ARTEX_SANDBOX=required
// mode WebFetch blocks requests to non-scope IPs (IMDS, arbitrary public IP,
// and un-scoped loopback servers) while allowing explicitly scoped targets.
func TestSandboxWebFetchBlocksNonScopeIP(t *testing.T) {
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { SetSandboxExecutor(nil) })
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("LOCAL_CANARY_BODY"))
}))
t.Cleanup(srv.Close)
host, _, err := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://"))
if err != nil {
t.Fatal(err)
}
// Empty-scope task: IMDS, 1.1.1.1, and local loopback server must ALL be blocked.
ctxUnscoped := WithSandboxRunInfo(context.Background(), SandboxRunInfo{
TaskID: "wf-block",
ScopeDomains: []string{"allowed.example.com"},
})
tools := withWebFetch(ctxUnscoped, nil, "", "")
wf := tools[len(tools)-1]
for _, target := range []string{
"http://169.254.169.254/latest/meta-data/",
"http://1.1.1.1/",
srv.URL + "/secret",
} {
raw, _ := json.Marshal(map[string]any{"url": target})
res, callErr := wf.Call(ctxUnscoped, raw, &actool.ToolContext{})
if callErr != nil {
t.Fatalf("WebFetch(%s) unexpected error: %v", target, callErr)
}
if !res.IsError || !strings.Contains(res.Flatten(), "sandbox WebFetch blocked") {
t.Fatalf("WebFetch(%s) should have been blocked, got isError=%v text=%q", target, res.IsError, res.Flatten())
}
}
// Explicitly scoped to srv's IP/32: allowed.
ctxScoped := WithSandboxRunInfo(context.Background(), SandboxRunInfo{
TaskID: "wf-allow",
ScopeCIDRs: []string{host + "/32"},
})
toolsAllowed := withWebFetch(ctxScoped, nil, "", "")
wfAllowed := toolsAllowed[len(toolsAllowed)-1]
rawOK, _ := json.Marshal(map[string]any{"url": srv.URL + "/ok"})
resOK, err := wfAllowed.Call(ctxScoped, rawOK, &actool.ToolContext{})
if err != nil {
t.Fatalf("scoped WebFetch error: %v", err)
}
if resOK.IsError || !strings.Contains(resOK.Flatten(), "LOCAL_CANARY_BODY") {
t.Fatalf("expected scoped WebFetch to succeed, got isError=%v text=%q", resOK.IsError, resOK.Flatten())
}
}