ARTEX/server/sandbox_test.go
BaaRai de16c16bdc security: fail closed on DNS errors and dual-A answers in sandbox egress
EgressPolicy.CheckURL, the check WebFetch, the shared browser and the
custom http tool run on a URL under ARTEX_SANDBOX=required, was fail-open
in two ways:
- a lookup error (or an empty answer) for a name in scope returned nil,
  so the URL was allowed;
- a name answering several addresses was allowed as soon as one of them
  was public, the others being private, loopback, IPv6 or the cloud
  metadata address (169.254.169.254).

CheckURL pins nothing. On a direct call the sandbox dialer resolves again
and pins an allowed address, but through an explicit proxy the panel only
dials the proxy, which resolves the target itself and may pick any answer
(or reach a name the panel could not resolve); the shared browser
resolves on its own as well. For those paths CheckURL is the only check
on the target.

CheckURL now denies a lookup error or an empty answer, and requires every
answer to be allowed (in the scope CIDRs, or outside the default deny
list): a dual-A [IMDS, public] answer is refused, in either order. The
dialer path (ResolveAndCheck, also used by the egress proxy) is
unchanged: it already fails closed on a lookup error and dials only the
allowed address it pinned.

sandboxHTTPTransport now turns keep-alive off on every transport it
returns, not only on the one it builds when httpToolTransport returned
nil: an operator proxy, or the recording proxy setting without a CA file,
kept idle connections to the proxy.

Two existing tests expected an in-scope name that does not resolve to be
allowed, which only the fail-open lookup gave them: the scope drift test
(its resolver reached the proxy policy only, not the policy WebFetch and
the browser build) and the shared browser navigation test. Both now pass
an offline resolver through the context (sandbox.WithResolver); their
assertions are unchanged.
2026-12-01 22:40:10 +01:00

348 lines
12 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
actool "github.com/Autumn-27/norma/tool"
)
type stubSandboxClient struct {
mu sync.Mutex
health sandbox.HealthResponse
healthEr error
execResp sandbox.ExecResponse
execErr error
execFn func(context.Context, string, sandbox.ExecRequest) (sandbox.ExecResponse, error)
execs []sandbox.ExecRequest
kills []string
deletes []string
}
func (c *stubSandboxClient) Health(context.Context) (sandbox.HealthResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
return c.health, c.healthEr
}
func (c *stubSandboxClient) Exec(ctx context.Context, taskID string, req sandbox.ExecRequest) (sandbox.ExecResponse, error) {
c.mu.Lock()
c.execs = append(c.execs, req)
fn := c.execFn
resp, err := c.execResp, c.execErr
c.mu.Unlock()
if fn != nil {
return fn(ctx, taskID, req)
}
return resp, err
}
func (c *stubSandboxClient) Kill(_ context.Context, taskID string) (sandbox.KillResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.kills = append(c.kills, taskID)
return sandbox.KillResponse{Killed: true}, nil
}
func (c *stubSandboxClient) Delete(_ context.Context, taskID string) (sandbox.DeleteResponse, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.deletes = append(c.deletes, taskID)
return sandbox.DeleteResponse{Deleted: true}, nil
}
func TestSandboxRequiredRoutesBashAndPausesWhenRunnerDown(t *testing.T) {
prev := agent.CurrentSandboxExecutor()
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
stub := &stubSandboxClient{
health: sandbox.HealthResponse{OK: true, Docker: true},
execResp: sandbox.ExecResponse{ExitCode: 0, Stdout: "uid=10001(exec)\n"},
}
var pausedTask string
agent.SetSandboxExecutor(&agent.SandboxExecutor{
Mode: sandbox.ModeRequired,
Runner: stub,
OnUnavailable: func(taskID string, _ error) {
pausedTask = taskID
},
})
ctx := agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
TaskID: "77",
TaskDir: "/app/data/tasks/77",
ScopeDomains: []string{"example.test"},
})
resp, err := agent.ExecInSandbox(ctx, []string{"bash", "-c", "id"}, "/app/data/tasks/77/i1", 30000, []string{"FOO=bar", "ARTEX_SECRET_KEY=leaked"})
if err != nil || !strings.Contains(resp.Stdout, "10001") {
t.Fatalf("ExecInSandbox = %+v err=%v", resp, err)
}
if len(stub.execs) != 1 || stub.execs[0].Workdir != "/workspace/i1" {
t.Fatalf("unexpected runner request: %+v", stub.execs)
}
if _, leaked := stub.execs[0].Env["ARTEX_SECRET_KEY"]; leaked {
t.Fatalf("ARTEX_SECRET_KEY leaked into runner env: %+v", stub.execs[0].Env)
}
// Simulate runner down -> must fail closed and trigger pause callback (no local fallback).
stub.execErr = sandbox.ErrRunnerUnavailable
if _, err := agent.ExecInSandbox(ctx, []string{"bash", "-c", "id"}, "", 30000, nil); !errors.Is(err, sandbox.ErrRunnerUnavailable) {
t.Fatalf("expected ErrRunnerUnavailable, got %v", err)
}
if pausedTask != "77" {
t.Fatalf("pausedTask = %q, want 77", pausedTask)
}
}
func TestSandboxRequiredRefusesTaskStartWhenRunnerDown(t *testing.T) {
stub := &stubSandboxClient{healthEr: sandbox.ErrRunnerUnavailable}
s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: stub}
if err := s.checkSandboxReady(context.Background()); err == nil {
t.Fatal("checkSandboxReady succeeded when runner was unavailable")
}
// Also verify Engine.Pause calls runner.Kill.
e := NewEngine(nil)
e.SetSandbox(stub, sandbox.ModeRequired, "/app/data")
e.Pause("88", agent.AbortPausedByUser)
if len(stub.kills) != 1 || stub.kills[0] != "88" {
t.Fatalf("Engine.Pause did not call runner.Kill: %+v", stub.kills)
}
// Verify ModeFromEnv defaults to required.
t.Setenv(sandbox.EnvSandboxMode, "")
if m, err := sandbox.ModeFromEnv(); err != nil || m != sandbox.ModeRequired {
t.Fatalf("ModeFromEnv() = %q %v, want required", m, err)
}
t.Setenv(sandbox.EnvSandboxMode, "bogus")
if _, err := sandbox.ModeFromEnv(); err == nil {
t.Fatal("ModeFromEnv accepted invalid mode")
}
}
func TestSandboxOffLogsLoudBanner(t *testing.T) {
out := captureLog(t, func() {
LogSandboxOffBanner()
})
for _, want := range []string{"SANDBOX IS OFF", "ARTEX_SANDBOX=off", "DEGRADED MODE"} {
if !strings.Contains(out, want) {
t.Errorf("LogSandboxOffBanner missing %q:\n%s", want, out)
}
}
}
func TestSandboxCustomCommandRoutesThroughRunner(t *testing.T) {
prev := agent.CurrentSandboxExecutor()
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
stub := &stubSandboxClient{
execResp: sandbox.ExecResponse{ExitCode: 0, Stdout: "sandboxed-custom-cmd"},
}
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired, Runner: stub})
s := &Server{sandboxMode: sandbox.ModeRequired, sandboxClient: stub}
ctx := agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
TaskID: "99",
TaskDir: "/app/data/tasks/99",
})
spec, _ := json.Marshal(commandExec{Command: "echo {{arg}}"})
res, err := s.runCommandTool(ctx, "my_tool", spec, map[string]any{"arg": "hi"}, &actool.ToolContext{WorkingDir: "/app/data/tasks/99"})
if err != nil || res.IsError || !strings.Contains(res.Flatten(), "sandboxed-custom-cmd") {
t.Fatalf("runCommandTool = %+v err=%v", res, err)
}
if len(stub.execs) != 1 || stub.execs[0].Argv[0] != "bash" {
t.Fatalf("custom command did not route through runner: %+v", stub.execs)
}
}
// TestSandboxSharedBrowserBlocksNonScopeNavigation verifies that in
// ARTEX_SANDBOX=required mode sharedBrowserTool blocks navigation to non-scope
// IPs (IMDS, 1.1.1.1, RFC1918, loopback) and non-HTTP schemes before calling
// the underlying browser MCP, while permitting in-scope URLs.
func TestSandboxSharedBrowserBlocksNonScopeNavigation(t *testing.T) {
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { agent.SetSandboxExecutor(nil) })
called := 0
inner := actool.Build(actool.Spec{
Name: "browser_navigate",
Description: "navigate browser",
Run: func(_ context.Context, _ json.RawMessage, _ *actool.ToolContext) (actool.Result, error) {
called++
return actool.Text("NAVIGATED"), nil
},
})
wrapped := &sharedBrowserTool{CoreTool: inner}
ctx := agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
TaskID: "br-1",
ScopeDomains: []string{"app.example.com"},
ScopeCIDRs: []string{"203.0.113.10/32"},
})
// The in-scope name resolves offline (a failed lookup is a denial).
ctx = sandbox.WithResolver(ctx, dnsTable(map[string][]string{"sub.app.example.com": {"203.0.113.10"}}))
blockedURLs := []string{
"http://169.254.169.254/latest/meta-data/",
"http://1.1.1.1/",
"http://10.0.0.1/admin",
"http://127.0.0.1:8787/",
"https://evil.attacker.invalid/exfil",
"file:///etc/passwd",
}
for _, u := range blockedURLs {
in, _ := json.Marshal(map[string]any{"url": u})
res, err := wrapped.Call(ctx, in, &actool.ToolContext{})
if err != nil {
t.Fatalf("Call(%s) err=%v", u, err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "sandbox browser navigation blocked") {
t.Fatalf("expected browser navigation to %s to be blocked, got isError=%v text=%q", u, res.IsError, res.Flatten())
}
}
if called != 0 {
t.Fatalf("underlying browser tool was invoked %d times on blocked URLs", called)
}
// In-scope URLs must pass the gate and invoke the underlying browser tool.
for _, u := range []string{"https://sub.app.example.com/login", "http://203.0.113.10/dashboard"} {
in, _ := json.Marshal(map[string]any{"url": u})
res, err := wrapped.Call(ctx, in, &actool.ToolContext{})
if err != nil || res.IsError || res.Flatten() != "NAVIGATED" {
t.Fatalf("expected in-scope navigation %s to succeed, got isError=%v text=%q err=%v", u, res.IsError, res.Flatten(), err)
}
}
if called != 2 {
t.Fatalf("expected 2 allowed navigations, got %d", called)
}
}
// TestTaskSandboxRunInfoIncludesCompanyScope verifies that task_scope.kind='company'
// rows expand the operator-approved company_scope domains/CIDRs into the task's
// sandbox egress allowlist, and that attributed company assets do not: the agent
// can write assets, so an asset host needs its own company or task scope rule.
func TestTaskSandboxRunInfoIncludesCompanyScope(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
if dsn == "" {
t.Skip("ARTEX_PG_DSN not set")
}
pg, err := db.Open(dsn)
if err != nil {
db.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { _ = pg.Close() })
suffix := strconv.FormatInt(time.Now().UnixNano(), 10)
scopeDom := "corp-" + suffix + ".example.com"
rootDom := "extra-" + suffix + ".example.com"
subDom := "api." + rootDom
compID, _, _, _, _, err := pg.Companies().CreateCompanyWithScope(
"Sandbox Co "+suffix,
"",
[]db.ScopeInput{
{Kind: "domain", Value: scopeDom},
{Kind: "cidr", Value: "198.51.100.0/24"},
},
"test",
true,
)
if err != nil {
t.Fatalf("CreateCompanyWithScope: %v", err)
}
if _, err := pg.Exec(`INSERT INTO assets(type, domain, root_domain, ip, company_id, last_seen) VALUES ('subdomain', $1, $2, '203.0.113.42', $3, now())`, subDom, rootDom, compID); err != nil {
t.Fatalf("insert company asset: %v", err)
}
task, err := pg.CreateTaskWithOptions("company scoped sandbox task", "goal", db.TaskCreateOptions{
CompanyIDs: []int64{compID},
})
if err != nil {
t.Fatalf("CreateTaskWithOptions: %v", err)
}
info := taskSandboxRunInfo(pg, t.TempDir(), strconv.FormatInt(task.ID, 10))
domJoined := strings.Join(info.ScopeDomains, ",")
cidrJoined := strings.Join(info.ScopeCIDRs, ",")
if !strings.Contains(domJoined, scopeDom) {
t.Fatalf("expected company domain %q in ScopeDomains=%v", scopeDom, info.ScopeDomains)
}
if !strings.Contains(cidrJoined, "198.51.100.0/24") {
t.Fatalf("expected company CIDR %q in ScopeCIDRs=%v", "198.51.100.0/24", info.ScopeCIDRs)
}
for _, asset := range []string{subDom, rootDom} {
if strings.Contains(domJoined, asset) {
t.Fatalf("attributed asset domain %q reached ScopeDomains=%v", asset, info.ScopeDomains)
}
}
if strings.Contains(cidrJoined, "203.0.113.42") {
t.Fatalf("attributed asset IP reached ScopeCIDRs=%v", info.ScopeCIDRs)
}
}
// TestSandboxCustomScriptToolAvoidsArgvE2BIG verifies that execScriptInSandbox
// stages large Python script code and JSON parameters via temporary workspace
// files rather than argv (preventing E2BIG) and removes the temp files afterward.
func TestSandboxCustomScriptToolAvoidsArgvE2BIG(t *testing.T) {
taskDir := t.TempDir()
largeCode := "# " + strings.Repeat("A", 256*1024) + "\nprint('OK')\n"
largeParams := []byte(`{"blob":"` + strings.Repeat("B", 256*1024) + `"}`)
var capturedReq sandbox.ExecRequest
var stagedScriptBytes, stagedParamsBytes int
fake := &stubSandboxClient{
execFn: func(_ context.Context, _ string, req sandbox.ExecRequest) (sandbox.ExecResponse, error) {
capturedReq = req
if len(req.Argv) >= 5 {
pPath := filepath.Join(taskDir, strings.TrimPrefix(req.Argv[3], "/workspace/"))
sPath := filepath.Join(taskDir, strings.TrimPrefix(req.Argv[4], "/workspace/"))
if raw, err := os.ReadFile(pPath); err == nil {
stagedParamsBytes = len(raw)
}
if raw, err := os.ReadFile(sPath); err == nil {
stagedScriptBytes = len(raw)
}
}
return sandbox.ExecResponse{ExitCode: 0, Stdout: "OK\n"}, nil
},
}
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired, Runner: fake})
t.Cleanup(func() { agent.SetSandboxExecutor(nil) })
ctx := agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
TaskID: "script-e2big",
TaskDir: taskDir,
})
resp, err := execScriptInSandbox(ctx, "big_tool", largeCode, largeParams, taskDir, 30000, nil)
if err != nil {
t.Fatalf("execScriptInSandbox failed: %v", err)
}
if resp.ExitCode != 0 {
t.Fatalf("unexpected exit code %d", resp.ExitCode)
}
totalArgvBytes := 0
for _, a := range capturedReq.Argv {
totalArgvBytes += len(a)
}
if totalArgvBytes > 1024 {
t.Fatalf("argv too large (%d bytes) — script/params leaked into argv instead of workspace files", totalArgvBytes)
}
if stagedScriptBytes != len(largeCode) || stagedParamsBytes != len(largeParams) {
t.Fatalf("staged file sizes mismatch: script=%d/%d params=%d/%d", stagedScriptBytes, len(largeCode), stagedParamsBytes, len(largeParams))
}
// Verify temporary staged files were cleaned up after execution.
entries, err := os.ReadDir(taskDir)
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("expected temp script/params files cleaned up, found %d leftover entries", len(entries))
}
}