mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
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.
295 lines
11 KiB
Go
295 lines
11 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// TestDockerSandboxE2EContainment exercises real artex-worker:local and
|
|
// artex-egress-proxy:local containers via DockerBackend.
|
|
// Enable with ARTEX_SANDBOX_DOCKER_TEST=1 after building the local images.
|
|
func TestDockerSandboxE2EContainment(t *testing.T) {
|
|
if os.Getenv("ARTEX_SANDBOX_DOCKER_TEST") != "1" {
|
|
t.Skip("set ARTEX_SANDBOX_DOCKER_TEST=1 to run live Docker worker isolation tests")
|
|
}
|
|
|
|
wsRoot := t.TempDir()
|
|
auditRoot := t.TempDir()
|
|
_ = os.Chmod(wsRoot, 0o755)
|
|
_ = os.Chmod(auditRoot, 0o755)
|
|
backend := NewDockerBackend(DockerConfig{
|
|
SocketPath: "/var/run/docker.sock",
|
|
WorkerImage: DefaultWorkerImage,
|
|
ProxyImage: DefaultProxyImage,
|
|
WorkspaceRoot: wsRoot,
|
|
HostWorkspaceRoot: wsRoot,
|
|
AuditRoot: auditRoot,
|
|
HostAuditRoot: auditRoot,
|
|
TaskNetPrefix: "artex-test-task-",
|
|
EgressNet: "artex-test-egress-net",
|
|
})
|
|
ctx := context.Background()
|
|
if err := backend.Ping(ctx); err != nil {
|
|
t.Fatalf("docker ping failed: %v", err)
|
|
}
|
|
|
|
taskA := fmt.Sprintf("e2ea-%d", time.Now().Unix()%100000)
|
|
taskB := fmt.Sprintf("e2eb-%d", time.Now().Unix()%100000)
|
|
t.Cleanup(func() {
|
|
_ = backend.Delete(context.Background(), taskA)
|
|
_ = backend.Delete(context.Background(), taskB)
|
|
backend.removeNetwork(context.Background(), "artex-test-egress-net")
|
|
})
|
|
|
|
// Pre-create taskA workspace and proxy-only audit dir writable by uid 10001
|
|
// when the test runs as a non-root host user.
|
|
taskADir := filepath.Join(wsRoot, taskA)
|
|
taskAAuditDir := filepath.Join(auditRoot, taskA)
|
|
for _, dir := range []string{taskADir, taskAAuditDir} {
|
|
if err := os.MkdirAll(dir, 0o777); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_ = os.Chmod(dir, 0o777)
|
|
}
|
|
|
|
// Seed a secret marker file in taskB's workspace to verify cross-task isolation.
|
|
taskBDir := filepath.Join(wsRoot, taskB)
|
|
if err := os.MkdirAll(taskBDir, 0o775); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(taskBDir, "secret-b.txt"), []byte("TASK_B_ONLY_SECRET"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// 1) UID/GID 10001, read-only rootfs, no keys/config/DB env.
|
|
res, err := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", `
|
|
id -u; id -g
|
|
test ! -e /app/keys/jwt.key && echo "NO_JWT_KEY"
|
|
test ! -e /app/keys/secret.key && echo "NO_SECRET_KEY"
|
|
test ! -e /app/config.json && echo "NO_CONFIG_JSON"
|
|
touch /etc/should-fail 2>/dev/null || echo "ROOTFS_RO"
|
|
env | grep -iE '^(ARTEX_|PG|AWS_|GCP_|AZURE_)|(_KEY|_TOKEN|_PASSWORD|_SECRET)=' || echo "ENV_CLEAN"
|
|
`},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 30000,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("exec containment check failed: %v", err)
|
|
}
|
|
t.Logf("worker containment stdout:\n%s", res.Stdout)
|
|
for _, want := range []string{"10001", "NO_JWT_KEY", "NO_SECRET_KEY", "NO_CONFIG_JSON", "ROOTFS_RO", "ENV_CLEAN"} {
|
|
if !strings.Contains(res.Stdout, want) {
|
|
t.Fatalf("missing containment assertion %q in stdout:\n%s\nstderr:\n%s", want, res.Stdout, res.Stderr)
|
|
}
|
|
}
|
|
|
|
// 2) Cannot reach metadata (169.254.169.254), arbitrary IP (1.1.1.1), SOCKS5, or direct IP bypass.
|
|
netRes, err := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", fmt.Sprintf(`
|
|
code_imds=$(curl -sS -m 5 -o /dev/null -w '%%{http_code}' http://169.254.169.254/latest/meta-data/ 2>/dev/null || echo "ERR")
|
|
echo "IMDS=$code_imds"
|
|
code_arb=$(curl -sS -m 5 -o /dev/null -w '%%{http_code}' http://1.1.1.1/ 2>/dev/null || echo "ERR")
|
|
echo "ARB=$code_arb"
|
|
if curl -sS -m 5 --proxy socks5h://artex-egress-%s:1080 -o /dev/null http://169.254.169.254/latest/meta-data/ 2>/dev/null; then
|
|
echo "SOCKS=OK"
|
|
else
|
|
echo "SOCKS=DENIED"
|
|
fi
|
|
if curl --noproxy '*' -sS -m 3 -o /dev/null http://1.1.1.1/ 2>/dev/null; then
|
|
echo "DIRECT=OK"
|
|
else
|
|
echo "DIRECT=BLOCKED"
|
|
fi
|
|
`, taskA)},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 30000,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("exec network check failed: %v", err)
|
|
}
|
|
t.Logf("worker network check stdout:\n%s", netRes.Stdout)
|
|
if !strings.Contains(netRes.Stdout, "IMDS=403") {
|
|
t.Fatalf("expected HTTP proxy 403 for IMDS, got: %s (stderr: %s)", netRes.Stdout, netRes.Stderr)
|
|
}
|
|
if !strings.Contains(netRes.Stdout, "ARB=403") {
|
|
t.Fatalf("expected HTTP proxy 403 for arbitrary IP, got: %s (stderr: %s)", netRes.Stdout, netRes.Stderr)
|
|
}
|
|
if !strings.Contains(netRes.Stdout, "SOCKS=DENIED") {
|
|
t.Fatalf("expected SOCKS5 proxy denial for IMDS, got: %s", netRes.Stdout)
|
|
}
|
|
if !strings.Contains(netRes.Stdout, "DIRECT=BLOCKED") {
|
|
t.Fatalf("worker bypassed proxy via direct IP: %s", netRes.Stdout)
|
|
}
|
|
|
|
// 2b) Tamper-proof audit log: proxy writes to proxy-only /audit/egress.jsonl,
|
|
// and worker cannot see, truncate, or forge it.
|
|
auditLogPath := filepath.Join(taskAAuditDir, "egress.jsonl")
|
|
auditBefore, err := os.ReadFile(auditLogPath)
|
|
if err != nil {
|
|
t.Fatalf("missing proxy-only egress.jsonl audit log at %s: %v", auditLogPath, err)
|
|
}
|
|
if !strings.Contains(string(auditBefore), `"decision":"deny"`) || !strings.Contains(string(auditBefore), `"169.254.169.254"`) || !strings.Contains(string(auditBefore), `"1.1.1.1"`) {
|
|
t.Fatalf("unexpected proxy-only egress.jsonl contents:\n%s", string(auditBefore))
|
|
}
|
|
tamperRes, err := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", `
|
|
test ! -e /audit/egress.jsonl && echo "NO_AUDIT_MOUNT"
|
|
test ! -e /workspace/egress.jsonl && echo "NO_WS_AUDIT"
|
|
echo '{"forged":true}' > /workspace/egress.jsonl
|
|
rm -f /workspace/egress.jsonl
|
|
`},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 15000,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("tamper check exec failed: %v", err)
|
|
}
|
|
if !strings.Contains(tamperRes.Stdout, "NO_AUDIT_MOUNT") || !strings.Contains(tamperRes.Stdout, "NO_WS_AUDIT") {
|
|
t.Fatalf("worker saw audit log mount: %s", tamperRes.Stdout)
|
|
}
|
|
auditAfter, err := os.ReadFile(auditLogPath)
|
|
if err != nil || len(auditAfter) < len(auditBefore) || strings.Contains(string(auditAfter), `"forged"`) {
|
|
t.Fatalf("worker tampered with audit log: err=%v after=%s", err, string(auditAfter))
|
|
}
|
|
|
|
// 3) Cannot see another task's workspace.
|
|
wsRes, err := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", fmt.Sprintf(`
|
|
echo "TASK_A_DATA" > /workspace/a.txt
|
|
test ! -e /workspace/secret-b.txt && echo "NO_TASK_B_IN_WS"
|
|
test ! -e /app/data/tasks/%s/secret-b.txt && echo "NO_TASK_B_HOSTPATH"
|
|
`, taskB)},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 30000,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("exec workspace isolation failed: %v", err)
|
|
}
|
|
if !strings.Contains(wsRes.Stdout, "NO_TASK_B_IN_WS") || !strings.Contains(wsRes.Stdout, "NO_TASK_B_HOSTPATH") {
|
|
t.Fatalf("cross-task isolation check failed:\n%s", wsRes.Stdout)
|
|
}
|
|
|
|
// 4) Adversarial Kill-switch: setsid, rm -rf /tmp/.artex-pgids /tmp/*, nohup,
|
|
// nested double-fork ignoring SIGTERM, and an active setsid egress loop.
|
|
// Assert ALL non-PID-1 uid-10001 processes are dead in <= 5s AND zero
|
|
// new egress hits reach the proxy after Kill.
|
|
egressLines := func() int {
|
|
raw, err := os.ReadFile(auditLogPath)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
n := 0
|
|
for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
|
|
if strings.TrimSpace(line) != "" {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
linesBeforeAttack := egressLines()
|
|
|
|
doneCh := make(chan ExecResponse, 1)
|
|
go func() {
|
|
r, _ := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", `
|
|
rm -rf /tmp/.artex-pgids /tmp/* 2>/dev/null || true
|
|
setsid sh -c 'sleep 300' </dev/null >/dev/null 2>&1 &
|
|
nohup sh -c 'sleep 300' </dev/null >/dev/null 2>&1 &
|
|
sh -c '(setsid sh -c "trap "" TERM; sleep 300" </dev/null >/dev/null 2>&1 &)'
|
|
setsid sh -c 'while true; do curl -sS -m 1 http://1.1.1.1/ >/dev/null 2>&1; sleep 0.05; done' </dev/null >/dev/null 2>&1 &
|
|
sleep 300
|
|
`},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 60000,
|
|
})
|
|
doneCh <- r
|
|
}()
|
|
|
|
// Wait until the setsid egress loop produces at least 2 proxy log entries.
|
|
waitDeadline := time.Now().Add(5 * time.Second)
|
|
for time.Now().Before(waitDeadline) && egressLines() < linesBeforeAttack+2 {
|
|
time.Sleep(50 * time.Millisecond)
|
|
}
|
|
if got := egressLines(); got < linesBeforeAttack+2 {
|
|
t.Fatalf("expected setsid egress loop to log >=2 attempts before Kill, got before=%d now=%d", linesBeforeAttack, got)
|
|
}
|
|
|
|
killStart := time.Now()
|
|
if err := backend.Kill(ctx, taskA); err != nil {
|
|
t.Fatalf("Kill(%s) failed: %v", taskA, err)
|
|
}
|
|
select {
|
|
case <-doneCh:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("escaped daemons inside worker survived Kill past 5s")
|
|
}
|
|
killElapsed := time.Since(killStart)
|
|
if killElapsed > 5*time.Second {
|
|
t.Fatalf("Kill took %s (> 5s)", killElapsed)
|
|
}
|
|
t.Logf("adversarial kill-switch (setsid + rm /tmp + nohup + trap-TERM daemon + egress loop) completed in %s", killElapsed)
|
|
|
|
// Verify ZERO non-PID-1 uid-10001 processes remain in the worker container (excluding our ps check itself).
|
|
psRes, err := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", `ps -eo pid=,uid=,stat=,comm= | awk '$1 != 1 && $2 == 10001 && $3 !~ /^[ZX]/ && $4 != "artex-exec-wrap" && $4 != "bash" && $4 != "ps" && $4 != "awk" { print }'`},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 15000,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("post-Kill ps check failed: %v", err)
|
|
}
|
|
if strings.TrimSpace(psRes.Stdout) != "" {
|
|
t.Fatalf("surviving uid-10001 processes after Kill:\n%s", psRes.Stdout)
|
|
}
|
|
|
|
// Verify ZERO egress attempts occur after Kill.
|
|
time.Sleep(100 * time.Millisecond)
|
|
linesSettled := egressLines()
|
|
time.Sleep(500 * time.Millisecond)
|
|
if linesLater := egressLines(); linesLater != linesSettled {
|
|
t.Fatalf("egress continued after Kill: audit lines grew from %d to %d", linesSettled, linesLater)
|
|
}
|
|
t.Logf("post-Kill egress audit lines stable at %d (zero post-Kill egress)", linesSettled)
|
|
|
|
// Reuse same container + workspace after Kill.
|
|
reuseRes, err := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", "cat /workspace/a.txt"},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 15000,
|
|
})
|
|
if err != nil || strings.TrimSpace(reuseRes.Stdout) != "TASK_A_DATA" {
|
|
t.Fatalf("reuse after Kill failed: res=%+v err=%v", reuseRes, err)
|
|
}
|
|
|
|
// 4b) Dead worker auto-recreation: externally remove worker container, next Exec recreates it.
|
|
backend.mu.Lock()
|
|
deadWorkerID := backend.tasks[taskA].workerID
|
|
backend.mu.Unlock()
|
|
backend.removeContainer(ctx, deadWorkerID)
|
|
|
|
recRes, err := backend.Exec(ctx, taskA, ExecRequest{
|
|
Argv: []string{"bash", "-c", "cat /workspace/a.txt"},
|
|
Workdir: "/workspace",
|
|
TimeoutMS: 15000,
|
|
})
|
|
if err != nil || strings.TrimSpace(recRes.Stdout) != "TASK_A_DATA" {
|
|
t.Fatalf("exec after external worker removal failed to recreate worker: res=%+v err=%v", recRes, err)
|
|
}
|
|
|
|
// 5) Delete removes containers/network while keeping evidence and audit log on disk.
|
|
if err := backend.Delete(ctx, taskA); err != nil {
|
|
t.Fatalf("Delete(%s) failed: %v", taskA, err)
|
|
}
|
|
if raw, err := os.ReadFile(filepath.Join(wsRoot, taskA, "a.txt")); err != nil || strings.TrimSpace(string(raw)) != "TASK_A_DATA" {
|
|
t.Fatalf("task evidence missing after Delete: raw=%q err=%v", raw, err)
|
|
}
|
|
if raw, err := os.ReadFile(auditLogPath); err != nil || len(raw) == 0 {
|
|
t.Fatalf("proxy audit log missing after Delete: err=%v", err)
|
|
}
|
|
}
|