From e3a54ef3ea21d0c60e031b216d62174705dd5550 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:52:35 +0100 Subject: [PATCH 1/3] sec(p0): fail-closed startup, atomic secret rotation, scoped target-gate backfill, and kernel kill-switch - Startup fail-closed: LockDownKeyDir explicitly chmods 0700 an existing key dir (counteracting host bind mounts) and 0600 existing key files; adds keys/ itself alongside jwt.key, secret.key, and config.json to IsolationSelfTest; makes IsolationSelfTest fatal unless ARTEX_ALLOW_UNISOLATED=1 is set. - Secret rotation: adds db.RotateSecretKey (single atomic transaction re-encrypting all sealed columns/settings and bumping auth.password_version), cmd/artex -rotate-secrets, scripts/rotate-secrets.sh, and OPS/SECURITY docs. - Scoped defaults, backfill & posture warnings: TargetGate defaults ON for tasks with CompanyIDs or InterceptRules (explicit opt-out persisted in tasks.target_gate_opt_out); migration 0022_target_gate_backfill.sql backfills existing active scoped tasks that did not explicitly opt out; egress-guard defaults to EGRESS_MODE=enforce when scope lists exist; loud startup warning when target gate or egress enforcement is off. - Kernel-backed local kill-switch: enables PR_SET_CHILD_SUBREAPER and scans /proc (without trusting agent-writable state) on Engine.Pause/BeginDelete to kill escaped setsid, nohup, and nested double-fork daemons (plus all execPriv.UID processes in isolated mode) within <= 5s with zero post-pause egress. --- SECURITY.md | 11 + cmd/artex/main.go | 91 ++++- cmd/artex/rotate_secrets_test.go | 79 +++++ db/migrations/0022_target_gate_backfill.sql | 14 + db/schema.sql | 1 + db/secrets.go | 113 ++++++ db/secrets_rotate_test.go | 150 ++++++++ db/target_gate_backfill_test.go | 115 +++++++ db/tasks.go | 22 +- docker-compose.egress.yml | 5 +- docs/OPS.md | 26 ++ egress-guard/README.md | 13 +- egress-guard/entrypoint.sh | 21 +- egress-guard/test_entrypoint_shim.sh | 33 ++ scripts/rotate-secrets.sh | 124 +++++++ server/auth.go | 3 + server/engine.go | 21 ++ server/isolation.go | 90 ++++- server/isolation_other.go | 10 + server/isolation_test.go | 45 +-- server/isolation_unix.go | 34 +- server/isolation_unix_test.go | 2 +- server/killswitch_other.go | 7 + server/killswitch_unix.go | 230 +++++++++++++ server/killswitch_unix_test.go | 364 ++++++++++++++++++++ server/p0_failclosed_test.go | 94 +++++ server/server.go | 3 +- server/target_gate_flag_test.go | 3 +- 28 files changed, 1655 insertions(+), 69 deletions(-) create mode 100644 cmd/artex/rotate_secrets_test.go create mode 100644 db/migrations/0022_target_gate_backfill.sql create mode 100644 db/secrets_rotate_test.go create mode 100644 db/target_gate_backfill_test.go create mode 100755 scripts/rotate-secrets.sh create mode 100644 server/killswitch_other.go create mode 100644 server/killswitch_unix.go create mode 100644 server/killswitch_unix_test.go create mode 100644 server/p0_failclosed_test.go diff --git a/SECURITY.md b/SECURITY.md index adbeb3bcb..6f90a1b97 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -97,3 +97,14 @@ We welcome ethical security research. If you follow this policy and test only wi - If you do not receive a response within a reasonable time, please ping the contact channel above before disclosing. Thank you for helping make ARTEX safer. + +## Key rotation & fail-closed startup + +- **Fail-closed startup**: ARTEX tightens the key directory to `0700` on startup + (counteracting host bind mounts that mask the image's `0700`), verifies in + `IsolationSelfTest` that `keys/`, `jwt.key`, `secret.key`, and `config.json` + are unreadable by the executor UID, and refuses to start if isolation checks + fail unless `ARTEX_ALLOW_UNISOLATED=1` is explicitly set. +- **Secret rotation**: Use `scripts/rotate-secrets.sh` (see `docs/OPS.md`) to + atomically rotate `jwt.key` and `secret.key`, re-encrypt all database secrets + at rest in one transaction, and invalidate all active JWT sessions. diff --git a/cmd/artex/main.go b/cmd/artex/main.go index 3093e9fd7..80b101fb9 100644 --- a/cmd/artex/main.go +++ b/cmd/artex/main.go @@ -6,6 +6,7 @@ package main import ( "context" "encoding/json" + "errors" "flag" "fmt" "log" @@ -22,6 +23,7 @@ import ( "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/config" + "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/egress" "github.com/Autumn-27/artex/server" ) @@ -116,11 +118,19 @@ func run() int { // Disabled by default so each agent run keeps its own private headless browser. sharedBrowser = flag.Bool("shared-browser", envBool("ARTEX_SHARED_BROWSER", false), "opt-in: run a shared browser with live view and operator take-over in the web UI; default false gives each agent run a private headless browser (env ARTEX_SHARED_BROWSER)") sharedBrowserLockTimeout = flag.Duration("shared-browser-lock-timeout", envDuration("ARTEX_SHARED_BROWSER_LOCK_TIMEOUT", server.DefaultSharedBrowserLockTimeout), "how long an idle operator take-over or ask_operator hold keeps the shared browser before automatically expiring (env ARTEX_SHARED_BROWSER_LOCK_TIMEOUT)") - // Development escape of the isolation self-test, off by default. - devNoIsolation = flag.Bool(server.DevNoIsolationFlag, false, "DEVELOPMENT ONLY: on Linux as root, start even when the agent isolation self-test fails; agent processes and file tools may then read the server's keys, config and database credentials") + // Development escape of the isolation self-test, off by default (prefer ARTEX_ALLOW_UNISOLATED=1). + devNoIsolation = flag.Bool(server.DevNoIsolationFlag, false, "DEVELOPMENT ONLY: start even when the agent isolation self-test fails (legacy alias for ARTEX_ALLOW_UNISOLATED=1); agent processes and file tools may then read the server's keys, config and database credentials") + // Offline/atomic secret rotation helper invoked by scripts/rotate-secrets.sh. + rotateSecrets = flag.Bool("rotate-secrets", false, "re-encrypt database secrets from -rotate-old-secret-file to -rotate-new-secret-file, invalidate active JWT sessions, and exit") + rotateOldSecretFile = flag.String("rotate-old-secret-file", "", "path to current secret.key (used with -rotate-secrets)") + rotateNewSecretFile = flag.String("rotate-new-secret-file", "", "path to staged new secret.key (used with -rotate-secrets)") ) flag.Parse() + if *rotateSecrets { + return runRotateSecrets(*rotateOldSecretFile, *rotateNewSecretFile) + } + // hand the build version and source revision to the server package so // GET /api/health can report them to the frontend top bar. server.BuildVersion = version @@ -201,13 +211,20 @@ func run() int { slog.Error("[config] install bash shim failed", "err", err) return 1 } + // Tighten an existing key directory before running the isolation self-test: + // a host bind mount (typically 0755) masks the image's 0700. + keyLockErr := server.LockDownKeyDir(keyDir) // Before the stores open and any agent runs: check that the isolation above holds - // (server/isolation.go). On Linux as root a failure stops the start unless the - // escape is set; elsewhere the server starts degraded and says so. + // (server/isolation.go). Startup is fail-closed unless ARTEX_ALLOW_UNISOLATED=1 + // (or -dev-insecure-no-isolation) is explicitly set. selfTest := server.IsolationSelfTest(priv, server.IsolationTargets{ DataDir: *dataDir, KeyDir: keyDir, ConfigPath: cfgPath, SkillDir: skillDir, DSN: dsn, }) - isolation, err := server.EnforceIsolation(runtime.GOOS, priv, selfTest, *devNoIsolation) + if keyLockErr != nil { + selfTest = errors.Join(keyLockErr, selfTest) + } + allowUnisolated := server.AllowUnisolatedFromEnv() || *devNoIsolation + isolation, err := server.EnforceIsolation(runtime.GOOS, priv, selfTest, allowUnisolated) if err != nil { slog.Error("[config] enforce isolation failed", "err", err) return 1 @@ -224,6 +241,20 @@ func run() int { } defer mgr.Close() + // Emit prominent startup warnings if egress enforcement is off or active tasks run without target_gate. + ungatedActive := 0 + if tasks, err := mgr.PG().ListTasks(); err == nil { + for _, t := range tasks { + if t.Status != "completed" && t.Status != "failed" && t.Status != "stopped" && !t.TargetGate { + ungatedActive++ + } + } + } + server.LogSecurityStartupWarnings(server.SecurityPostureCheck{ + EgressMode: os.Getenv("EGRESS_MODE"), + UngatedActiveTasks: ungatedActive, + }) + srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv), server.WithIsolationStatus(isolation), server.WithSharedBrowser(*sharedBrowser), server.WithSharedBrowserLockTimeout(*sharedBrowserLockTimeout)) // ReadTimeout bounds how long the request headers and body may take to arrive. // It does not limit how long a handler runs, so an event stream stays open. @@ -296,6 +327,56 @@ func envBool(name string, def bool) bool { return v } +// runRotateSecrets atomically re-encrypts database secrets from oldPath to +// newPath and increments auth.password_version to invalidate active sessions. +func runRotateSecrets(oldPath, newPath string) int { + if strings.TrimSpace(oldPath) == "" || strings.TrimSpace(newPath) == "" { + slog.Error("[rotate-secrets] both -rotate-old-secret-file and -rotate-new-secret-file are required") + return 2 + } + oldRaw, err := os.ReadFile(oldPath) + if err != nil { + slog.Error("[rotate-secrets] read old secret key failed", "path", oldPath, "err", err) + return 1 + } + newRaw, err := os.ReadFile(newPath) + if err != nil { + slog.Error("[rotate-secrets] read new secret key failed", "path", newPath, "err", err) + return 1 + } + oldKey, err := db.ParseSecretKey(string(oldRaw)) + if err != nil { + slog.Error("[rotate-secrets] invalid old secret key", "err", err) + return 1 + } + newKey, err := db.ParseSecretKey(string(newRaw)) + if err != nil { + slog.Error("[rotate-secrets] invalid new secret key", "err", err) + return 1 + } + dsn, _, err := config.PostgresDSN() + if err != nil { + slog.Error("[rotate-secrets] database DSN unavailable", "err", err) + return 1 + } + pg, err := db.Open(dsn) + if err != nil { + slog.Error("[rotate-secrets] open database failed", "err", err) + return 1 + } + defer pg.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + rotated, pwdVer, err := pg.RotateSecretKey(ctx, oldKey, newKey, true) + if err != nil { + slog.Error("[rotate-secrets] database secret rotation failed", "err", err) + return 1 + } + slog.Info("[rotate-secrets] completed", "rotated_values", rotated, "auth_password_version", pwdVer) + return 0 +} + // envDuration reads a Go duration environment variable (or integer seconds), // returning def when unset or invalid. func envDuration(name string, def time.Duration) time.Duration { diff --git a/cmd/artex/rotate_secrets_test.go b/cmd/artex/rotate_secrets_test.go new file mode 100644 index 000000000..c65b7e82f --- /dev/null +++ b/cmd/artex/rotate_secrets_test.go @@ -0,0 +1,79 @@ +//go:build unix + +package main + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/Autumn-27/artex/db" +) + +func TestRotateSecretsScriptAtomicFilesAndPermissions(t *testing.T) { + if _, err := exec.LookPath("bash"); err != nil { + t.Skip("bash not available") + } + script := filepath.Join("..", "..", "scripts", "rotate-secrets.sh") + keyDir := filepath.Join(t.TempDir(), "keys") + // Simulate a host bind mount with overly permissive 0755 mode. + if err := os.MkdirAll(keyDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(keyDir, 0o755); err != nil { + t.Fatal(err) + } + oldJWT := "oldjwtkey0123456789abcdef0123456789" + oldSec := "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n" + if err := os.WriteFile(filepath.Join(keyDir, "jwt.key"), []byte(oldJWT), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(keyDir, "secret.key"), []byte(oldSec), 0o644); err != nil { + t.Fatal(err) + } + + cmd := exec.Command("bash", script, "--key-dir", keyDir, "--files-only") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("rotate-secrets.sh failed: %v\n%s", err, out) + } + + fi, err := os.Stat(keyDir) + if err != nil || fi.Mode().Perm() != 0o700 { + t.Fatalf("keyDir mode = %v err=%v, want 0700", fi.Mode().Perm(), err) + } + newJWTBytes, err := os.ReadFile(filepath.Join(keyDir, "jwt.key")) + if err != nil { + t.Fatal(err) + } + newJWT := strings.TrimSpace(string(newJWTBytes)) + if len(newJWT) < 32 || newJWT == oldJWT { + t.Fatalf("jwt.key not rotated properly: len=%d", len(newJWT)) + } + newSecBytes, err := os.ReadFile(filepath.Join(keyDir, "secret.key")) + if err != nil { + t.Fatal(err) + } + if string(newSecBytes) == oldSec { + t.Fatal("secret.key was not rotated") + } + if _, err := db.ParseSecretKey(string(newSecBytes)); err != nil { + t.Fatalf("rotated secret.key invalid: %v", err) + } + for _, name := range []string{"jwt.key", "secret.key"} { + st, err := os.Stat(filepath.Join(keyDir, name)) + if err != nil || st.Mode().Perm() != 0o600 { + t.Fatalf("%s mode = %#o err=%v, want 0600", name, st.Mode().Perm(), err) + } + } + // Ensure no staged temp files were left behind. + entries, err := os.ReadDir(keyDir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 2 { + t.Fatalf("unexpected extra files in keyDir: %v", entries) + } +} diff --git a/db/migrations/0022_target_gate_backfill.sql b/db/migrations/0022_target_gate_backfill.sql new file mode 100644 index 000000000..b16db2122 --- /dev/null +++ b/db/migrations/0022_target_gate_backfill.sql @@ -0,0 +1,14 @@ +-- Backfill target_gate=true on existing active scoped tasks that did not +-- explicitly opt out, and persist explicit opt-out on tasks.target_gate_opt_out. +ALTER TABLE tasks ADD COLUMN IF NOT EXISTS target_gate_opt_out BOOLEAN NOT NULL DEFAULT FALSE; + +UPDATE tasks t +SET target_gate = TRUE +WHERE t.target_gate = FALSE + AND t.target_gate_opt_out = FALSE + AND t.deleted_at IS NULL + AND t.status NOT IN ('done', 'failed', 'timeout') + AND ( + EXISTS (SELECT 1 FROM task_scope ts WHERE ts.task_id = t.id) + OR EXISTS (SELECT 1 FROM task_intercept_rules tir WHERE tir.task_id = t.id) + ); diff --git a/db/schema.sql b/db/schema.sql index 62331a3e9..c9674482e 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -562,6 +562,7 @@ ALTER TABLE tasks ADD COLUMN IF NOT EXISTS plan_heartbeat_seconds INTEGER NOT NU ALTER TABLE tasks ADD COLUMN IF NOT EXISTS plan_quiet_mode BOOLEAN NOT NULL DEFAULT true; -- Approval gate for asset targets, opt-in per task; backfills old databases. false (default) = no gate, behaviour unchanged. ALTER TABLE tasks ADD COLUMN IF NOT EXISTS target_gate BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE tasks ADD COLUMN IF NOT EXISTS target_gate_opt_out BOOLEAN NOT NULL DEFAULT false; ALTER TABLE tasks ADD COLUMN IF NOT EXISTS llm_rotate BOOLEAN NOT NULL DEFAULT false; -- Concurrency-limit hold state; backfills old databases. true=queued due to the concurrency limit, auto-starts when a slot frees up. ALTER TABLE tasks ADD COLUMN IF NOT EXISTS queued BOOLEAN NOT NULL DEFAULT false; diff --git a/db/secrets.go b/db/secrets.go index 770549380..4d730256e 100644 --- a/db/secrets.go +++ b/db/secrets.go @@ -352,6 +352,9 @@ func loadSecretKey(ctx context.Context, conn *sql.Conn, keyDir string) ([]byte, if err := os.MkdirAll(keyDir, 0o700); err != nil { return nil, fmt.Errorf("create secret key dir: %w", err) } + if err := os.Chmod(keyDir, 0o700); err != nil { + return nil, fmt.Errorf("chmod secret key dir: %w", err) + } f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) // never overwrite a key if err != nil { return nil, fmt.Errorf("write secret key: %w", err) @@ -421,3 +424,113 @@ func backfillSecrets(ctx context.Context, conn *sql.Conn, box *secretBox) (int, } return total, nil } + +// ParseSecretKey parses a 32-byte base64- or hex-encoded secret key. +func ParseSecretKey(s string) ([]byte, error) { + return parseSecretKey(s) +} + +// RotateSecretKey decrypts every sealed secret across all secretColumns with +// oldKey, re-encrypts them under newKey with fresh nonces, and optionally +// increments auth.password_version to invalidate all existing JWT sessions, all +// inside one atomic database transaction under the schema advisory lock. +func (d *DB) RotateSecretKey(ctx context.Context, oldKey, newKey []byte, invalidateSessions bool) (rotated int, newPwdVersion int64, err error) { + oldBox, err := newSecretBox(oldKey) + if err != nil { + return 0, 0, fmt.Errorf("old secret key: %w", err) + } + newBox, err := newSecretBox(newKey) + if err != nil { + return 0, 0, fmt.Errorf("new secret key: %w", err) + } + err = withSchemaMigrationLock(ctx, d.DB, func(conn *sql.Conn) error { + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() //nolint:errcheck + + for _, c := range secretColumns { + type rowUpdate struct { + id any + oldRaw string + newValue string + } + var updates []rowUpdate + rows, err := tx.QueryContext(ctx, `SELECT `+c.idCol()+`, `+c.col+`::text FROM `+c.table+` WHERE `+c.col+` IS NOT NULL`+c.rowFilter()) + if err != nil { + return fmt.Errorf("scan %s: %w", c.aad(), err) + } + for rows.Next() { + var id any + var raw string + if err := rows.Scan(&id, &raw); err != nil { + rows.Close() + return fmt.Errorf("scan %s: %w", c.aad(), err) + } + var plain string + if isSealed(c, raw) { + plain, err = oldBox.open(c, raw) + if err != nil { + rows.Close() + return fmt.Errorf("decrypt %s id=%v with old key: %w", c.aad(), id, err) + } + } else { + plain = raw + } + resealed, err := newBox.seal(c, plain) + if err != nil { + rows.Close() + return fmt.Errorf("re-encrypt %s id=%v with new key: %w", c.aad(), id, err) + } + if isSealed(c, resealed) { + updates = append(updates, rowUpdate{id: id, oldRaw: raw, newValue: resealed}) + } + } + if err := rows.Err(); err != nil { + rows.Close() + return fmt.Errorf("iterate %s: %w", c.aad(), err) + } + rows.Close() + + cast := "" + if c.json { + cast = "::jsonb" + } + for _, u := range updates { + res, err := tx.ExecContext(ctx, `UPDATE `+c.table+` SET `+c.col+`=$1`+cast+` WHERE `+c.idCol()+`=$2 AND `+c.col+`::text=$3`, u.newValue, u.id, u.oldRaw) + if err != nil { + return fmt.Errorf("update %s id=%v: %w", c.aad(), u.id, err) + } + if n, _ := res.RowsAffected(); n > 0 { + rotated++ + } + } + } + + if invalidateSessions { + var rawVer string + var cur int64 + err := tx.QueryRowContext(ctx, `SELECT value FROM settings WHERE key='auth.password_version'`).Scan(&rawVer) + if err != nil && err != sql.ErrNoRows { + return fmt.Errorf("read auth.password_version: %w", err) + } + if err == nil { + _, _ = fmt.Sscan(strings.TrimSpace(rawVer), &cur) + } + newPwdVersion = cur + 1 + if _, err := tx.ExecContext(ctx, `INSERT INTO settings(key, value) VALUES ('auth.password_version', $1) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`, fmt.Sprintf("%d", newPwdVersion)); err != nil { + return fmt.Errorf("bump auth.password_version: %w", err) + } + } + + if err := tx.Commit(); err != nil { + return err + } + activeSecretBox.Store(newBox) + sub := deriveSubKey(newKey, trafficTraceDomain) + trafficTraceKey.Store(&sub) + return nil + }) + return rotated, newPwdVersion, err +} diff --git a/db/secrets_rotate_test.go b/db/secrets_rotate_test.go new file mode 100644 index 000000000..a734e4540 --- /dev/null +++ b/db/secrets_rotate_test.go @@ -0,0 +1,150 @@ +package db + +import ( + "context" + "crypto/rand" + "encoding/base64" + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +func TestRotateSecretKeyAtomicallyReencryptsAndInvalidatesSessions(t *testing.T) { + // Use a dedicated scratch database and restore the package-level secret box + // so rotating to a random key never affects other tests sharing testSecretKey. + prevBox := activeSecretBox.Load() + prevTrace := trafficTraceKey.Load() + t.Cleanup(func() { + activeSecretBox.Store(prevBox) + trafficTraceKey.Store(prevTrace) + }) + + d, err := Open(scratchDSN(t, "rotate_secrets")) + if err != nil { + t.Fatal(err) + } + defer d.Close() + + keyDir := t.TempDir() + keyA := make([]byte, 32) + keyB := make([]byte, 32) + if _, err := rand.Read(keyA); err != nil { + t.Fatal(err) + } + if _, err := rand.Read(keyB); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(keyDir, "secret.key"), []byte(base64.StdEncoding.EncodeToString(keyA)+"\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("ARTEX_SECRET_KEY", "") + if err := d.InitSecrets(keyDir); err != nil { + t.Fatalf("InitSecrets(keyA): %v", err) + } + + // Insert encrypted secrets across tables and settings. + task, err := d.CreateTask("rotate-fixture", "verify key rotation", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(task.ID) }) + if _, err := d.UpsertTaskCredential(task.ID, TaskCredentialInput{ + Domain: "rotate.example.test", Username: "alice", Password: "super-secret-rotate-pw", Source: "user", + }); err != nil { + t.Fatal(err) + } + if err := d.SetSetting("global_proxy", "http://u:rotate-proxy-pass@127.0.0.1:8080"); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.SetSetting("global_proxy", "") }) + + rotated, newVer, err := d.RotateSecretKey(context.Background(), keyA, keyB, true) + if err != nil { + t.Fatalf("RotateSecretKey: %v", err) + } + if rotated < 2 { + t.Fatalf("rotated=%d, want >= 2", rotated) + } + if newVer < 1 { + t.Fatalf("newPwdVersion=%d, want >= 1", newVer) + } + + // Old key A must now fail InitSecrets check. + if err := d.InitSecrets(keyDir); err == nil { + t.Fatal("InitSecrets with old keyA succeeded after rotation; expected failure") + } + + // New key B must pass InitSecrets and decrypt every secret cleanly. + if err := os.WriteFile(filepath.Join(keyDir, "secret.key"), []byte(base64.StdEncoding.EncodeToString(keyB)+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := d.InitSecrets(keyDir); err != nil { + t.Fatalf("InitSecrets(keyB): %v", err) + } + creds, err := d.TaskCredentials(task.ID) + if err != nil || len(creds) != 1 || creds[0].Password != "super-secret-rotate-pw" { + t.Fatalf("credentials after rotation = %+v err=%v", creds, err) + } + proxyVal, ok, err := d.GetSetting("global_proxy") + if err != nil || !ok || proxyVal != "http://u:rotate-proxy-pass@127.0.0.1:8080" { + t.Fatalf("global_proxy after rotation = %q ok=%v err=%v", proxyVal, ok, err) + } +} + +func TestTaskTargetGateDefaultsOnWhenScoped(t *testing.T) { + d, err := Open(testDSN(t)) + if err != nil { + SkipPGUnavailable(t, err) + } + defer d.Close() + + // Unscoped task defaults OFF. + unscoped, err := d.CreateTaskWithOptions("unscoped", "goal", TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(unscoped.ID) }) + if unscoped.TargetGate { + t.Fatal("unscoped task unexpectedly defaulted TargetGate=true") + } + + // Task scoped with InterceptRules defaults ON. + rules := []TaskInterceptRuleInput{{Enabled: true, Action: "allow", Kind: "exact_domain", Pattern: "scoped.example.test"}} + byRules, err := d.CreateTaskWithOptions("scoped-rules", "goal", TaskCreateOptions{InterceptRules: rules}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(byRules.ID) }) + if !byRules.TargetGate { + t.Fatal("task with InterceptRules should default TargetGate=true") + } + + // Explicit opt-out on scoped task turns TargetGate OFF. + off := false + optedOut, err := d.CreateTaskWithOptions("scoped-optout", "goal", TaskCreateOptions{InterceptRules: rules, TargetGate: &off}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(optedOut.ID) }) + if optedOut.TargetGate { + t.Fatal("explicit TargetGate=false opt-out on scoped task was ignored") + } + + // Task scoped with CompanyIDs defaults ON. + compName := fmt.Sprintf("Scoped Target Gate Co %d", time.Now().UnixNano()) + compID, _, _, _, _, err := d.Companies().CreateCompanyWithScope(compName, "", []ScopeInput{{Kind: "domain", Value: "co.example.test"}}, "test") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.Companies().DeleteCompany(compID) }) + byCompany, err := d.CreateTaskWithOptions("scoped-company", "goal", TaskCreateOptions{CompanyIDs: []int64{compID}}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.DeleteTask(byCompany.ID) }) + if !byCompany.TargetGate { + t.Fatal("task with CompanyIDs should default TargetGate=true") + } +} diff --git a/db/target_gate_backfill_test.go b/db/target_gate_backfill_test.go new file mode 100644 index 000000000..f8df4655a --- /dev/null +++ b/db/target_gate_backfill_test.go @@ -0,0 +1,115 @@ +package db + +import ( + "database/sql" + "testing" +) + +// TestTargetGateBackfillMigration0022 proves that migration 0022 backfills +// target_gate=true on existing active scoped tasks (company, intercept rules, +// or task_scope) while leaving finished/unscoped tasks and explicitly opted-out +// tasks with target_gate=false. +func TestTargetGateBackfillMigration0022(t *testing.T) { + dsn := scratchDSN(t, "tg_backfill_0022") + + d, err := Open(dsn) + if err != nil { + t.Fatalf("initial Open: %v", err) + } + coID, _, _, _, _, err := d.Companies().CreateCompanyWithScope("Backfill Target Corp", "", []ScopeInput{{Kind: "domain", Value: "backfill.example.com"}}, "test") + if err != nil { + t.Fatalf("create company: %v", err) + } + + off := false + // 1) Active company-scoped task + tCompany, err := d.CreateTaskWithOptions("active-company", "goal", TaskCreateOptions{CompanyIDs: []int64{coID}}) + if err != nil { + t.Fatalf("create company task: %v", err) + } + // 2) Active intercept-rule-scoped task + tRule, err := d.CreateTaskWithOptions("active-rule", "goal", TaskCreateOptions{ + InterceptRules: []TaskInterceptRuleInput{{Kind: "exact_domain", Pattern: "target.example.com", Action: "allow", Enabled: true}}, + }) + if err != nil { + t.Fatalf("create rule task: %v", err) + } + // 3) Active task_scope-scoped task + tScope, err := d.CreateTaskWithOptions("active-task-scope", "goal", TaskCreateOptions{}) + if err != nil { + t.Fatalf("create scope task: %v", err) + } + if _, err := d.Exec(`INSERT INTO task_scope(task_id, kind, domain, source) VALUES ($1, 'root_domain', 'scoped.example.com', 'manual')`, tScope.ID); err != nil { + t.Fatalf("insert task_scope: %v", err) + } + // 4) Finished scoped task -> must stay false + tDone, err := d.CreateTaskWithOptions("done-company", "goal", TaskCreateOptions{CompanyIDs: []int64{coID}}) + if err != nil { + t.Fatalf("create done task: %v", err) + } + // 5) Unscoped active task -> must stay false + tUnscoped, err := d.CreateTaskWithOptions("active-unscoped", "goal", TaskCreateOptions{}) + if err != nil { + t.Fatalf("create unscoped task: %v", err) + } + // 6) Explicitly opted-out active scoped task -> must stay false + tOptOut, err := d.CreateTaskWithOptions("explicit-opt-out", "goal", TaskCreateOptions{ + CompanyIDs: []int64{coID}, + TargetGate: &off, + }) + if err != nil { + t.Fatalf("create opt-out task: %v", err) + } + // 7) Active scoped task later explicitly turned off via UpdateTask -> must stay false + tUpdatedOff, err := d.CreateTaskWithOptions("updated-opt-out", "goal", TaskCreateOptions{CompanyIDs: []int64{coID}}) + if err != nil { + t.Fatalf("create updated-opt-out task: %v", err) + } + if _, err := d.UpdateTask(tUpdatedOff.ID, TaskPatch{TargetGate: &off}); err != nil { + t.Fatalf("UpdateTask opt-out: %v", err) + } + + // Simulate legacy pre-0022 state for tasks 1..5 (target_gate=false, opt_out=false, done on #4). + for _, id := range []int64{tCompany.ID, tRule.ID, tScope.ID, tDone.ID, tUnscoped.ID} { + if _, err := d.Exec(`UPDATE tasks SET target_gate=FALSE, target_gate_opt_out=FALSE WHERE id=$1`, id); err != nil { + t.Fatalf("reset legacy task %d: %v", id, err) + } + } + if _, err := d.Exec(`UPDATE tasks SET status='done' WHERE id=$1`, tDone.ID); err != nil { + t.Fatalf("mark done: %v", err) + } + // Remove migration 0022 marker so Open(dsn) re-runs 0022_target_gate_backfill.sql. + if _, err := d.Exec(`DELETE FROM schema_migrations WHERE version = 22`); err != nil { + t.Fatalf("delete migration 22 marker: %v", err) + } + d.Close() + + // Re-open: migration 0022 executes. + d2, err := Open(dsn) + if err != nil { + t.Fatalf("re-Open with migration 0022: %v", err) + } + defer d2.Close() + + check := func(name string, id int64, wantGate, wantOptOut bool) { + t.Helper() + var gate, optOut bool + if err := d2.QueryRow(`SELECT target_gate, target_gate_opt_out FROM tasks WHERE id=$1`, id).Scan(&gate, &optOut); err != nil { + if err == sql.ErrNoRows { + t.Fatalf("%s: missing row", name) + } + t.Fatalf("%s: query: %v", name, err) + } + if gate != wantGate || optOut != wantOptOut { + t.Errorf("%s (id=%d): got target_gate=%v opt_out=%v, want %v %v", name, id, gate, optOut, wantGate, wantOptOut) + } + } + + check("active-company", tCompany.ID, true, false) + check("active-rule", tRule.ID, true, false) + check("active-task-scope", tScope.ID, true, false) + check("done-company", tDone.ID, false, false) + check("active-unscoped", tUnscoped.ID, false, false) + check("explicit-opt-out", tOptOut.ID, false, true) + check("updated-opt-out", tUpdatedOff.ID, false, true) +} diff --git a/db/tasks.go b/db/tasks.go index a5ecf1ef5..bc9bc2651 100644 --- a/db/tasks.go +++ b/db/tasks.go @@ -177,7 +177,9 @@ type TaskCreateOptions struct { // chain instead of the single active head. nil = off (default), preserving // the ordered-failover semantics. LLMRotate *bool - // TargetGate opts the task into the approval gate for asset targets; nil = off. + // TargetGate controls the approval gate for asset targets. When nil, it + // defaults ON for any task with a scope (CompanyIDs or InterceptRules) and + // OFF for unscoped tasks; pass an explicit false pointer to opt out. TargetGate *bool } @@ -258,11 +260,18 @@ VALUES ($1, 'fact', $2, 0, 'origin', 'system')`, expID, string(originPayload)); rotate = *opts.LLMRotate } t.LLMRotate = rotate - t.TargetGate = opts.TargetGate != nil && *opts.TargetGate + hasScope := len(opts.CompanyIDs) > 0 || len(opts.InterceptRules) > 0 + targetGateOptOut := false + if opts.TargetGate != nil { + t.TargetGate = *opts.TargetGate + targetGateOptOut = !*opts.TargetGate + } else { + t.TargetGate = hasScope + } if err := tx.QueryRow(` -INSERT INTO tasks(name, category_id, description, goal, exploration_id, llm_profile_id, active_llm_profile_id, timeout_seconds, plan_heartbeat_seconds, plan_quiet_mode, coverage_enabled, llm_rotate, target_gate) -VALUES ($1,$2,$3,$4,$5,$6,$6,$7,$8,$9,$10,$11,$12) -RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, description, goal, expID, active, opts.TimeoutSeconds, opts.PlanHeartbeatSeconds, quietMode, coverageEnabled, rotate, t.TargetGate).Scan(&t.ID, &t.Status, &t.Paused, &t.CreatedAt); err != nil { +INSERT INTO tasks(name, category_id, description, goal, exploration_id, llm_profile_id, active_llm_profile_id, timeout_seconds, plan_heartbeat_seconds, plan_quiet_mode, coverage_enabled, llm_rotate, target_gate, target_gate_opt_out) +VALUES ($1,$2,$3,$4,$5,$6,$6,$7,$8,$9,$10,$11,$12,$13) +RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, description, goal, expID, active, opts.TimeoutSeconds, opts.PlanHeartbeatSeconds, quietMode, coverageEnabled, rotate, t.TargetGate, targetGateOptOut).Scan(&t.ID, &t.Status, &t.Paused, &t.CreatedAt); err != nil { return nil, err } if err := insertTaskRelations(tx, t.ID, opts.SourceTaskIDs); err != nil { @@ -443,7 +452,8 @@ func (d *DB) UpdateTask(id int64, patch TaskPatch) (*Task, error) { ELSE NULL END, plan_quiet_mode = CASE WHEN $5::boolean THEN $6 ELSE plan_quiet_mode END, - target_gate = CASE WHEN $7::boolean THEN $8 ELSE target_gate END + target_gate = CASE WHEN $7::boolean THEN $8 ELSE target_gate END, + target_gate_opt_out = CASE WHEN $7::boolean THEN (NOT $8) ELSE target_gate_opt_out END WHERE id=$1 AND deleted_at IS NULL RETURNING `+taskCols, id, patch.Name != nil, patch.Name, patch.Pinned, patch.PlanQuietMode != nil, patch.PlanQuietMode, patch.TargetGate != nil, patch.TargetGate)) if err == sql.ErrNoRows { diff --git a/docker-compose.egress.yml b/docker-compose.egress.yml index 060c84b25..89b909ab2 100644 --- a/docker-compose.egress.yml +++ b/docker-compose.egress.yml @@ -22,8 +22,9 @@ services: - NET_ADMIN - NET_RAW environment: - # monitor (default, log only) | enforce (block) | off (DNS only) - EGRESS_MODE: ${EGRESS_MODE:-monitor} + # enforce (default when scope-domains.txt or scope-cidrs.txt has entries) | + # monitor (log only, default when scope lists are empty) | off (DNS only). + EGRESS_MODE: ${EGRESS_MODE:-} ARTEX_SUBNET: 172.31.250.0/24 ARTEX_GATEWAY: 172.31.250.1 UPSTREAM_DNS: ${EGRESS_UPSTREAM_DNS:-} diff --git a/docs/OPS.md b/docs/OPS.md index e14b3f726..62b5180ab 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -96,3 +96,29 @@ When Postgres is not configured, database-dependent tests skip themselves; that expected. Set `ARTEX_PG_DSN` to run them. CI uses `go test -p 1 ./...` because test packages share a Postgres service and use suffixed per-package databases (`SuffixTestDatabase`). + +## Rotating `jwt.key` and `secret.key` + +Run `scripts/rotate-secrets.sh` whenever key material may have been exposed (for +example after running unisolated or after an incident): + +```bash +# With PostgreSQL (re-encrypts all enc:v1:* rows and bumps auth.password_version atomically): +ARTEX_PG_DSN="$ARTEX_PG_DSN" scripts/rotate-secrets.sh --key-dir ./keys + +# Inside Docker Compose: +docker compose exec artex /app/scripts/rotate-secrets.sh --key-dir /app/keys --dsn "$ARTEX_PG_DSN" --artex-bin /app/artex +docker compose restart artex +``` + +What the script does: +1. Tightens `--key-dir` to `0700` and stages new `jwt.key` and `secret.key` files + in the same directory with `umask 077` (`0600`). +2. Re-encrypts every sealed column and secret setting in PostgreSQL from the old + `secret.key` to the new `secret.key` and increments `auth.password_version` + inside a single database transaction **before** moving `secret.key` into place. + If the database transaction fails, neither key file changes. +3. Atomically replaces `secret.key` and `jwt.key` via `mv` and `fsync`s the directory. +4. Invalidates all existing JWT sessions (both by replacing `jwt.key` and by + incrementing `auth.password_version`). Restart ARTEX immediately afterwards so + the running server loads the new keys. diff --git a/egress-guard/README.md b/egress-guard/README.md index accfee088..d27dd0300 100644 --- a/egress-guard/README.md +++ b/egress-guard/README.md @@ -22,13 +22,14 @@ edits the host firewall, so read this before enabling it. ## Modes (`EGRESS_MODE` in `.env`) | Mode | Effect | |---|---| -| `monitor` (default) | **observe only** — logs what would be blocked, blocks nothing | -| `enforce` | the allowlist actually blocks | -| `off` | no firewall rules; DNS redirect only | +| `enforce` (**default when scope lists exist**) | the allowlist actively blocks outbound traffic outside `scope-domains.txt` / `scope-cidrs.txt` / `base-domains.txt` | +| `monitor` (fallback only when scope lists are empty) | **observe only** — logs a loud warning and blocks nothing | +| `off` | no firewall rules; DNS redirect only (logs a loud warning) | -**The allowlist only restricts egress in `enforce`.** The default `monitor` is a -dry run for calibration — it protects nothing. Set `EGRESS_MODE=enforce` (and -bring the service up again) for the guard to have any effect. In `enforce`, +**`EGRESS_MODE=enforce` is the default whenever `lists/scope-domains.txt` or +`lists/scope-cidrs.txt` has at least one entry.** Leave `EGRESS_MODE` unset (or +set `EGRESS_MODE=enforce` explicitly) once your scope lists are populated; only +set `EGRESS_MODE=monitor` temporarily when calibrating. In `enforce`, setup is **fail-closed**: a blanket deny is installed before the allowlist is built, so if setup fails the ARTEX container loses outbound connectivity (except DNS) until the guard restarts cleanly. diff --git a/egress-guard/entrypoint.sh b/egress-guard/entrypoint.sh index 2b9383e6b..2517c9f63 100755 --- a/egress-guard/entrypoint.sh +++ b/egress-guard/entrypoint.sh @@ -17,7 +17,6 @@ # guard comes up cleanly. In monitor/off mode a setup failure is non-fatal by design (log only). set -Eeuo pipefail # -E so the ERR trap fires for failures inside functions (apply_rules) -MODE="${EGRESS_MODE:-monitor}" SUBNET="${ARTEX_SUBNET:?ARTEX_SUBNET required}" GW="${ARTEX_GATEWAY:?ARTEX_GATEWAY required}" SUBNET6="${ARTEX_SUBNET6:-}" @@ -38,11 +37,27 @@ V6_CMT="artex-egress-v6-deny" log() { echo "[egress-guard] $*"; } -case "$MODE" in monitor|enforce|off) ;; *) log "invalid EGRESS_MODE=$MODE"; exit 1;; esac - # Read a list file: strip comments/blank lines, lowercase, drop leading dots/wildcards. read_list() { [ -f "$1" ] || return 0; sed -e 's/#.*//' -e 's/[[:space:]]//g' "$1" | tr 'A-Z' 'a-z' | sed -e 's/^\*\.//' -e 's/^\.//' | grep -v '^$' || true; } +# Default EGRESS_MODE=enforce whenever scope lists contain entries; fall back to +# monitor (with a loud warning) only when scope lists are empty. +MODE="${EGRESS_MODE:-}" +if [ -z "$MODE" ]; then + if [ -n "$(read_list "$LISTS/scope-domains.txt")" ] || [ -n "$(read_list "$LISTS/scope-cidrs.txt")" ]; then + MODE="enforce" + log "EGRESS_MODE unset and scope lists are populated: defaulting to EGRESS_MODE=enforce" + else + MODE="monitor" + log "WARN: EGRESS_MODE unset and scope lists are empty: defaulting to EGRESS_MODE=monitor (NO EGRESS BLOCKING)" + fi +fi + +case "$MODE" in monitor|enforce|off) ;; *) log "invalid EGRESS_MODE=$MODE"; exit 1;; esac +if [ "$MODE" != "enforce" ]; then + log "WARNING: EGRESS_MODE=$MODE — outbound traffic is NOT blocked. Populate scope lists or set EGRESS_MODE=enforce." +fi + ensure_docker_user() { # DOCKER-USER exists whenever dockerd runs; create it only for standalone tests. $IPT -L DOCKER-USER -n >/dev/null 2>&1 || { $IPT -N DOCKER-USER; $IPT -I FORWARD -j DOCKER-USER; } diff --git a/egress-guard/test_entrypoint_shim.sh b/egress-guard/test_entrypoint_shim.sh index 30f43dd9e..ea2eccb9c 100755 --- a/egress-guard/test_entrypoint_shim.sh +++ b/egress-guard/test_entrypoint_shim.sh @@ -114,3 +114,36 @@ if ! tail -n 3 "$DIR/selftest.sh" | grep -qE 'fail.*-eq 0|exit'; then exit 1 fi echo "PASS: selftest.sh exits non-zero on failure" + +# Test 4: unset EGRESS_MODE defaults to enforce when scope lists have entries +echo "example.com" > "$TMP/lists/scope-domains.txt" +: > "$IP6_STATE" +set +e +PATH="$TMP/bin:$PATH" IPTABLES_BIN="$TMP/bin/iptables" IP6TABLES_BIN="$TMP/bin/ip6tables" \ + DNSMASQ_STARTED_FILE="$TMP/started4" \ + EGRESS_MODE="" ARTEX_SUBNET=172.31.250.0/24 ARTEX_GATEWAY=172.31.250.1 \ + ARTEX_SUBNET6=fd00:artex::/64 \ + bash "$TMP/entrypoint_test.sh" >"$TMP/t4.log" 2>&1 +set -e +if ! grep -q "defaulting to EGRESS_MODE=enforce" "$TMP/t4.log"; then + echo "FAIL: expected auto-enforce when scope-domains.txt is populated" + cat "$TMP/t4.log" + exit 1 +fi +echo "PASS: unset EGRESS_MODE defaults to enforce when scope lists exist" + +# Test 5: unset EGRESS_MODE falls back to monitor with loud warning when scope lists are empty +: > "$TMP/lists/scope-domains.txt" +: > "$TMP/lists/scope-cidrs.txt" +set +e +PATH="$TMP/bin:$PATH" IPTABLES_BIN="$TMP/bin/iptables" IP6TABLES_BIN="$TMP/bin/ip6tables" \ + DNSMASQ_STARTED_FILE="$TMP/started5" \ + EGRESS_MODE="" ARTEX_SUBNET=172.31.250.0/24 ARTEX_GATEWAY=172.31.250.1 \ + bash "$TMP/entrypoint_test.sh" >"$TMP/t5.log" 2>&1 +set -e +if ! grep -q "WARNING: EGRESS_MODE=monitor" "$TMP/t5.log"; then + echo "FAIL: expected loud warning when EGRESS_MODE falls back to monitor" + cat "$TMP/t5.log" + exit 1 +fi +echo "PASS: empty scope lists fall back to monitor with loud warning" diff --git a/scripts/rotate-secrets.sh b/scripts/rotate-secrets.sh new file mode 100755 index 000000000..4b8c06477 --- /dev/null +++ b/scripts/rotate-secrets.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# Atomically rotate ARTEX's jwt.key and secret.key, re-encrypting database +# secrets at rest and invalidating all active web/API sessions. +# +# Usage: +# scripts/rotate-secrets.sh [--key-dir DIR] [--dsn DSN] [--artex-bin PATH] [--files-only] +# +# Environment: +# ARTEX_JWT_KEY_DIR Key directory containing jwt.key and secret.key (default: ./keys) +# ARTEX_PG_DSN PostgreSQL DSN for atomic DB secret re-encryption & session invalidation +# ARTEX_BIN Path to the artex binary (default: auto-detected or `go run ./cmd/artex`) +# +# Guarantees: +# 1. Tightens KEY_DIR to 0700 and creates staged keys with umask 077 (0600). +# 2. When a database DSN is configured (and --files-only is not set), decrypts +# all encrypted DB columns with the old secret.key, re-encrypts them with +# the new secret.key, and increments auth.password_version in ONE atomic +# PostgreSQL transaction BEFORE moving the new secret.key into place. +# If the DB transaction fails, neither key file is replaced. +# 3. Replaces jwt.key and secret.key via POSIX atomic rename (mv within KEY_DIR). +# 4. Invalidates every existing JWT session (new signing key + bumped auth.password_version). +# Restart the artex server process/container after rotation so it reloads jwt.key & secret.key. +set -euo pipefail +umask 077 + +KEY_DIR="${ARTEX_JWT_KEY_DIR:-./keys}" +DSN="${ARTEX_PG_DSN:-}" +ARTEX_BIN="${ARTEX_BIN:-}" +FILES_ONLY=0 + +usage() { + sed -n '2,23p' "$0" | sed 's/^# \{0,1\}//' +} + +while [ $# -gt 0 ]; do + case "$1" in + --key-dir) KEY_DIR="$2"; shift 2 ;; + --dsn) DSN="$2"; shift 2 ;; + --artex-bin) ARTEX_BIN="$2"; shift 2 ;; + --files-only) FILES_ONLY=1; shift ;; + -h|--help) usage; exit 0 ;; + *) echo "rotate-secrets.sh: unknown argument: $1" >&2; usage >&2; exit 2 ;; + esac +done + +mkdir -p "$KEY_DIR" +chmod 0700 "$KEY_DIR" + +JWT_PATH="$KEY_DIR/jwt.key" +SECRET_PATH="$KEY_DIR/secret.key" +TMP_JWT="$KEY_DIR/.jwt.key.new.$$" +TMP_SECRET="$KEY_DIR/.secret.key.new.$$" + +cleanup() { + rm -f "$TMP_JWT" "$TMP_SECRET" +} +trap cleanup EXIT + +gen_jwt_key() { + # 32 bytes hex = 64 alphanumeric chars (satisfies loadOrCreateJWTKey >= 32 bytes) + if command -v openssl >/dev/null 2>&1; then + openssl rand -hex 32 + else + python3 -c 'import secrets; print(secrets.token_hex(32))' + fi +} + +gen_secret_key() { + # 32 random bytes base64-encoded (matches db.ParseSecretKey / loadSecretKey) + if command -v openssl >/dev/null 2>&1; then + openssl rand -base64 32 + else + python3 -c 'import base64, os; print(base64.b64encode(os.urandom(32)).decode("ascii"))' + fi +} + +# Stage new keys in the same directory as targets so rename(2) is atomic. +gen_jwt_key > "$TMP_JWT" +chmod 0600 "$TMP_JWT" + +gen_secret_key > "$TMP_SECRET" +chmod 0600 "$TMP_SECRET" + +# Re-encrypt DB secrets and invalidate active sessions BEFORE replacing secret.key on disk. +if [ "$FILES_ONLY" -eq 0 ] && [ -n "$DSN" ]; then + if [ -f "$SECRET_PATH" ]; then + OLD_SECRET_FOR_DB="$SECRET_PATH" + else + # First-time DB with no prior secret.key file: pass staged key as both old/new + # so backfill/session invalidation still runs atomically. + OLD_SECRET_FOR_DB="$TMP_SECRET" + fi + if [ -n "$ARTEX_BIN" ]; then + ARTEX_PG_DSN="$DSN" "$ARTEX_BIN" -rotate-secrets -rotate-old-secret-file "$OLD_SECRET_FOR_DB" -rotate-new-secret-file "$TMP_SECRET" + elif command -v artex >/dev/null 2>&1; then + ARTEX_PG_DSN="$DSN" artex -rotate-secrets -rotate-old-secret-file "$OLD_SECRET_FOR_DB" -rotate-new-secret-file "$TMP_SECRET" + else + REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + (cd "$REPO_ROOT" && ARTEX_PG_DSN="$DSN" go run ./cmd/artex -rotate-secrets -rotate-old-secret-file "$OLD_SECRET_FOR_DB" -rotate-new-secret-file "$TMP_SECRET") + fi +elif [ "$FILES_ONLY" -eq 0 ] && [ -f "$SECRET_PATH" ]; then + echo "[rotate-secrets] WARN: ARTEX_PG_DSN/--dsn not set; rotating key files only." >&2 + echo "[rotate-secrets] WARN: If PostgreSQL holds enc:v1:* rows sealed with the old secret.key, re-run with --dsn or restore the old secret.key before starting artex." >&2 +fi + +# Atomic POSIX rename into place; sync directory metadata if python3 is available. +mv -f "$TMP_SECRET" "$SECRET_PATH" +mv -f "$TMP_JWT" "$JWT_PATH" +chmod 0600 "$SECRET_PATH" "$JWT_PATH" +chmod 0700 "$KEY_DIR" + +if command -v python3 >/dev/null 2>&1; then + python3 - "$KEY_DIR" <<'PY' +import os, sys +fd = os.open(sys.argv[1], os.O_RDONLY) +try: + os.fsync(fd) +finally: + os.close(fd) +PY +fi + +echo "[rotate-secrets] rotated $JWT_PATH and $SECRET_PATH (mode 0600 in 0700 dir)." +echo "[rotate-secrets] all existing JWT sessions are invalidated; restart ARTEX to load the new keys." diff --git a/server/auth.go b/server/auth.go index d3f96cfd0..e218668ad 100644 --- a/server/auth.go +++ b/server/auth.go @@ -82,6 +82,9 @@ func loadOrCreateJWTKey(keyDir, dataDir string) ([]byte, error) { if err := os.MkdirAll(keyDir, 0o700); err != nil { return nil, fmt.Errorf("create jwt key dir: %w", err) } + if err := os.Chmod(keyDir, 0o700); err != nil { + return nil, fmt.Errorf("chmod jwt key dir: %w", err) + } path := filepath.Join(keyDir, jwtKeyFilename) if _, err := os.Stat(path); os.IsNotExist(err) { if err := migrateJWTKey(path, dataDir); err != nil { diff --git a/server/engine.go b/server/engine.go index d5241ce50..213a03a61 100644 --- a/server/engine.go +++ b/server/engine.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log" + "path/filepath" "strconv" "strings" "sync" @@ -109,6 +110,8 @@ type Engine struct { goalFP sync.Map // taskID -> string (sorted open-goal ids joined) paused sync.Map // taskID -> bool, user-paused (planner + workers idle but loops alive) deleting sync.Map // taskID -> bool, delete barrier (no new task-owned writes) + killDataDir string + killExecPriv ExecPrivilege dropCnt sync.Map // taskID -> *int64, running count of dropped (unpersistable) activity records // deleteMu makes installing the delete barrier atomic with registering a new @@ -185,9 +188,25 @@ func (e *Engine) nextPlannerRound(taskID string) int { // Pause stops a task: marks it paused AND cancels any in-flight planner/worker run // for it (a long worker.Execute would otherwise keep going until it finishes). +// SetKillSwitchConfig configures the data directory and executor privilege used +// by Pause/BeginDelete to terminate escaped local child trees (setsid/nohup/daemons). +func (e *Engine) SetKillSwitchConfig(dataDir string, priv ExecPrivilege) { + e.killDataDir = dataDir + e.killExecPriv = priv +} + +func (e *Engine) killLocalTask(taskID string) { + taskDir := "" + if e.killDataDir != "" && taskID != "" { + taskDir = filepath.Join(e.killDataDir, "tasks", taskID) + } + _ = KillLocalTaskProcesses(taskDir, e.killExecPriv) +} + func (e *Engine) Pause(taskID string, cause error) { e.paused.Store(taskID, true) e.cancelExec(taskID, cause) + e.killLocalTask(taskID) } // BeginDelete installs an execution barrier before task data/files are removed. @@ -203,6 +222,7 @@ func (e *Engine) BeginDelete(taskID string) bool { e.paused.Store(taskID, true) e.deleteMu.Unlock() e.cancelExec(taskID, agent.AbortTaskDeleted) + e.killLocalTask(taskID) return true } @@ -480,6 +500,7 @@ func (e *Engine) ActiveLLMCalls(taskID string) int64 { func (e *Engine) touch(taskID string) { e.lastAct.Store(taskID, time.Now().Unix()) } func NewEngine(m *Manager) *Engine { + enableLocalKillSubreaper() return &Engine{m: m, debounce: 800 * time.Millisecond, bc: NewBroadcaster(), execCancel: map[string]context.CancelCauseFunc{}, execCtx: map[string]context.Context{}, work: map[int64]*workExecution{}, steerBox: map[int64][]string{}, diff --git a/server/isolation.go b/server/isolation.go index ab5fd43db..ccc134a62 100644 --- a/server/isolation.go +++ b/server/isolation.go @@ -3,6 +3,7 @@ package server import ( "fmt" "log" + "os" "strings" ) @@ -27,9 +28,18 @@ import ( // state in GET /api/health to a signed-in caller, which the web UI shows as a // banner on every page. -// DevNoIsolationFlag is the command-line flag of the development escape. +// DevNoIsolationFlag is the legacy command-line flag alias of the development escape. const DevNoIsolationFlag = "dev-insecure-no-isolation" +// AllowUnisolatedEnv is the explicit environment opt-out that lets ARTEX start +// when IsolationSelfTest fails. Must be set to "1" to bypass fail-closed startup. +const AllowUnisolatedEnv = "ARTEX_ALLOW_UNISOLATED" + +// AllowUnisolatedFromEnv reports whether ARTEX_ALLOW_UNISOLATED=1 is set. +func AllowUnisolatedFromEnv() bool { + return strings.TrimSpace(os.Getenv(AllowUnisolatedEnv)) == "1" +} + // The isolation modes the server reports. const ( IsolationIsolated = "isolated" @@ -60,19 +70,20 @@ type IsolationTargets struct { DSN string } -// EnforceIsolation decides the start from the self-test result, the platform goos -// and the privilege drop p (see the rules above). It returns the status to report, -// or an error when the start must stop. -func EnforceIsolation(goos string, p ExecPrivilege, selfTest error, devEscape bool) (IsolationStatus, error) { +// EnforceIsolation decides the start from the self-test result. Startup is +// fail-closed on every platform and privilege mode: a failed self-test stops +// the server unless ARTEX_ALLOW_UNISOLATED=1 (or -dev-insecure-no-isolation) +// is explicitly set. +func EnforceIsolation(goos string, p ExecPrivilege, selfTest error, allowUnisolated bool) (IsolationStatus, error) { if selfTest == nil { log.Printf("[isolation] self-test passed: agent processes and file tools run as the executor and cannot reach the server's secrets") - if devEscape { - log.Printf("[isolation] -%s is set and not needed: the self-test passed", DevNoIsolationFlag) + if allowUnisolated { + log.Printf("[isolation] %s=1 / -%s is set and not needed: the self-test passed", AllowUnisolatedEnv, DevNoIsolationFlag) } return IsolationStatus{Mode: IsolationIsolated}, nil } - if isolationRequired(goos, p) && !devEscape { - return IsolationStatus{}, fmt.Errorf("agent isolation self-test failed: %v. A Linux server running as root with the privilege drop does not start without agent isolation: fix the cause above, or pass -%s for development only", selfTest, DevNoIsolationFlag) + if !allowUnisolated { + return IsolationStatus{}, fmt.Errorf("agent isolation self-test failed: %v. Startup is fail-closed: fix the isolation error above, or set %s=1 (or pass -%s) for explicit development-only opt-out", selfTest, AllowUnisolatedEnv, DevNoIsolationFlag) } logDegradedBanner(selfTest, isolationRequired(goos, p)) return IsolationStatus{Mode: IsolationDegraded, Reason: selfTest.Error()}, nil @@ -84,14 +95,13 @@ func isolationRequired(goos string, p ExecPrivilege) bool { return goos == "linux" && p.Enabled } -// degradedBanner is the warning a degraded start logs. escaped is set when the start -// went on only through the development escape. -func degradedBanner(cause error, escaped bool) []string { +// degradedBanner is the warning a degraded start logs when ARTEX_ALLOW_UNISOLATED=1 +// (or -dev-insecure-no-isolation) explicitly overrides fail-closed startup. +func degradedBanner(cause error, canIsolate bool) []string { bar := strings.Repeat("!", 78) - why := "!! This host cannot isolate agents: that needs Linux and a root server with the" + - "\n!! privilege drop (-exec-uid), as in the Docker image." - if escaped { - why = "!! -" + DevNoIsolationFlag + " is set. DEVELOPMENT ONLY." + why := "!! " + AllowUnisolatedEnv + "=1 is set (host cannot isolate agents without Linux root + -exec-uid). DEVELOPMENT ONLY." + if canIsolate { + why = "!! " + AllowUnisolatedEnv + "=1 / -" + DevNoIsolationFlag + " is set. DEVELOPMENT ONLY." } lines := []string{bar, "!! AGENT ISOLATION IS DEGRADED."} lines = append(lines, strings.Split(why, "\n")...) @@ -110,3 +120,51 @@ func logDegradedBanner(cause error, escaped bool) { log.Print("[isolation] " + line) } } + +// SecurityPostureCheck describes startup posture warnings for target gating and egress enforcement. +type SecurityPostureCheck struct { + EgressMode string + UngatedActiveTasks int + TargetGateOptedOut bool +} + +// SecurityStartupWarnings builds loud operator warnings when egress enforcement +// or target gating is disabled. Returns nil when both protections are active. +func SecurityStartupWarnings(c SecurityPostureCheck) []string { + var warnings []string + mode := strings.ToLower(strings.TrimSpace(c.EgressMode)) + if mode != "enforce" { + if mode == "" { + mode = "unset/off" + } + warnings = append(warnings, + fmt.Sprintf("EGRESS ENFORCEMENT IS OFF (EGRESS_MODE=%s): outbound connections from agent commands are not restricted by egress-guard. Enable docker-compose.egress.yml with EGRESS_MODE=enforce and populate egress-guard/lists/scope-domains.txt.", mode), + ) + } + if c.TargetGateOptedOut { + warnings = append(warnings, + "TARGET GATE IS OFF BY OPT-OUT: agent commands may contact unapproved hosts without operator confirmation.", + ) + } + if c.UngatedActiveTasks > 0 { + warnings = append(warnings, + fmt.Sprintf("TARGET GATE IS OFF ON %d ACTIVE TASK(S): those tasks can contact arbitrary hosts without target-gate approval. Enable target_gate on scoped tasks.", c.UngatedActiveTasks), + ) + } + return warnings +} + +// LogSecurityStartupWarnings logs a prominent warning banner for each active posture gap. +func LogSecurityStartupWarnings(c SecurityPostureCheck) { + warnings := SecurityStartupWarnings(c) + if len(warnings) == 0 { + return + } + bar := strings.Repeat("!", 78) + log.Print("[security] " + bar) + log.Print("[security] !! SECURITY POSTURE WARNING") + for _, w := range warnings { + log.Print("[security] !! " + w) + } + log.Print("[security] " + bar) +} diff --git a/server/isolation_other.go b/server/isolation_other.go index 0fe610577..18d0c545f 100644 --- a/server/isolation_other.go +++ b/server/isolation_other.go @@ -2,6 +2,16 @@ package server +import "os" + +// LockDownKeyDir creates keyDir if missing; POSIX chmod 0700 enforcement is Unix-only. +func LockDownKeyDir(keyDir string) error { + if keyDir == "" { + return nil + } + return os.MkdirAll(keyDir, 0o700) +} + // IsolationSelfTest fails: agent processes cannot run as another identity on this // platform, so they are never isolated from the server. func IsolationSelfTest(p ExecPrivilege, t IsolationTargets) error { diff --git a/server/isolation_test.go b/server/isolation_test.go index 46c1ec61f..3b48d7084 100644 --- a/server/isolation_test.go +++ b/server/isolation_test.go @@ -34,44 +34,35 @@ func TestEnforceIsolation(t *testing.T) { err error ) - // Hard failure: Linux, root, self-test failed, no escape. No banner: no start. - out := captureLog(t, func() { st, err = EnforceIsolation("linux", root, cause, false) }) - if err == nil || !strings.Contains(err.Error(), cause.Error()) || !strings.Contains(err.Error(), "-"+DevNoIsolationFlag) { - t.Fatalf("linux root: err = %v, want the cause and the flag named", err) - } - if st.Mode != "" || strings.Contains(out, banner) { - t.Fatalf("linux root: status %+v, banner in\n%s", st, out) - } - - // Linux, root, with the development escape: degraded, banner names the flag. - out = captureLog(t, func() { st, err = EnforceIsolation("linux", root, cause, true) }) - if err != nil || st.Mode != IsolationDegraded || st.Reason != cause.Error() { - t.Fatalf("linux root with the escape: status %+v err %v, want degraded", st, err) - } - for _, want := range []string{banner, "-" + DevNoIsolationFlag, "DEVELOPMENT ONLY", cause.Error(), "keys", "database"} { - if !strings.Contains(out, want) { - t.Errorf("escape banner lacks %q:\n%s", want, out) + // Fail-closed everywhere when self-test fails and ARTEX_ALLOW_UNISOLATED=1 is not set. + var out string + for _, c := range []struct { + goos string + p ExecPrivilege + }{{"linux", root}, {"linux", off}, {"windows", off}, {"darwin", off}, {"darwin", root}} { + out = captureLog(t, func() { st, err = EnforceIsolation(c.goos, c.p, cause, false) }) + if err == nil || !strings.Contains(err.Error(), cause.Error()) || !strings.Contains(err.Error(), AllowUnisolatedEnv+"=1") { + t.Fatalf("%s drop=%v: err = %v, want fatal error naming cause and %s=1", c.goos, c.p.Enabled, err, AllowUnisolatedEnv) + } + if st.Mode != "" || strings.Contains(out, banner) { + t.Fatalf("%s drop=%v: status %+v, unexpected banner in\n%s", c.goos, c.p.Enabled, st, out) } } - // Degraded without any flag: Linux not root (the systemd unit, dev.sh), Windows, - // macOS (root or not). The banner says why and what is exposed. + // Explicit opt-out (ARTEX_ALLOW_UNISOLATED=1): starts degraded with a loud warning banner. for _, c := range []struct { goos string p ExecPrivilege - }{{"linux", off}, {"windows", off}, {"darwin", off}, {"darwin", root}} { - out = captureLog(t, func() { st, err = EnforceIsolation(c.goos, c.p, cause, false) }) + }{{"linux", root}, {"linux", off}, {"darwin", off}} { + out := captureLog(t, func() { st, err = EnforceIsolation(c.goos, c.p, cause, true) }) if err != nil || st.Mode != IsolationDegraded || st.Reason != cause.Error() { - t.Fatalf("%s drop=%v: status %+v err %v, want a degraded start", c.goos, c.p.Enabled, st, err) + t.Fatalf("%s drop=%v with opt-out: status %+v err %v, want degraded", c.goos, c.p.Enabled, st, err) } - for _, want := range []string{banner, "cannot isolate agents", cause.Error(), "keys", "database"} { + for _, want := range []string{banner, AllowUnisolatedEnv + "=1", "DEVELOPMENT ONLY", cause.Error(), "keys", "database"} { if !strings.Contains(out, want) { - t.Errorf("%s drop=%v: banner lacks %q:\n%s", c.goos, c.p.Enabled, want, out) + t.Errorf("%s drop=%v opt-out banner lacks %q:\n%s", c.goos, c.p.Enabled, want, out) } } - if strings.Contains(out, "DEVELOPMENT ONLY") { - t.Errorf("%s drop=%v: the degraded banner is not the escape's:\n%s", c.goos, c.p.Enabled, out) - } } // A passing self-test starts isolated, escape or not, without a banner. diff --git a/server/isolation_unix.go b/server/isolation_unix.go index 41f89fe09..b162375a0 100644 --- a/server/isolation_unix.go +++ b/server/isolation_unix.go @@ -84,11 +84,43 @@ func IsolationSelfTest(p ExecPrivilege, t IsolationTargets) error { return nil } +// LockDownKeyDir ensures keyDir exists with mode 0700 and tightens an existing +// directory (such as a host bind mount whose default 0755 masks the image's +// 0700) plus any existing jwt.key / secret.key files inside it to 0600. +func LockDownKeyDir(keyDir string) error { + if strings.TrimSpace(keyDir) == "" { + return nil + } + if err := os.MkdirAll(keyDir, 0o700); err != nil { + return fmt.Errorf("create key dir %s: %w", keyDir, err) + } + if err := os.Chmod(keyDir, 0o700); err != nil { + return fmt.Errorf("chmod 0700 key dir %s: %w", keyDir, err) + } + for _, name := range []string{jwtKeyFilename, "secret.key"} { + p := filepath.Join(keyDir, name) + fi, err := os.Lstat(p) + if err != nil { + if os.IsNotExist(err) { + continue + } + return fmt.Errorf("stat key file %s: %w", p, err) + } + if fi.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("key file %s must not be a symlink", p) + } + if err := os.Chmod(p, 0o600); err != nil { + return fmt.Errorf("chmod 0600 key file %s: %w", p, err) + } + } + return nil +} + // isolationSpec builds the probe's checks from the server's paths. func isolationSpec(p ExecPrivilege, t IsolationTargets) isolationProbeSpec { spec := isolationProbeSpec{UID: p.UID, GID: p.GID, ServerPID: os.Getpid()} if t.KeyDir != "" { - spec.Unreadable = append(spec.Unreadable, filepath.Join(t.KeyDir, "jwt.key"), filepath.Join(t.KeyDir, "secret.key")) + spec.Unreadable = append(spec.Unreadable, t.KeyDir, filepath.Join(t.KeyDir, "jwt.key"), filepath.Join(t.KeyDir, "secret.key")) } if t.ConfigPath != "" { spec.Unreadable = append(spec.Unreadable, t.ConfigPath) diff --git a/server/isolation_unix_test.go b/server/isolation_unix_test.go index 8f0a0cb8b..1ec480868 100644 --- a/server/isolation_unix_test.go +++ b/server/isolation_unix_test.go @@ -262,7 +262,7 @@ func TestIsolationSpecHasNoPassword(t *testing.T) { DataDir: "/app/data", KeyDir: "/app/keys", ConfigPath: "/app/config.json", DSN: "postgres://artex:s3cr3t-pw@postgres:5432/artex?sslmode=disable", }) - for _, want := range []string{"/app/keys/jwt.key", "/app/keys/secret.key", "/app/config.json", "/app/data/traffic/_ca/mitmproxy-ca.pem"} { + for _, want := range []string{"/app/keys", "/app/keys/jwt.key", "/app/keys/secret.key", "/app/config.json", "/app/data/traffic/_ca/mitmproxy-ca.pem"} { found := false for _, p := range spec.Unreadable { found = found || p == want diff --git a/server/killswitch_other.go b/server/killswitch_other.go new file mode 100644 index 000000000..6858323d0 --- /dev/null +++ b/server/killswitch_other.go @@ -0,0 +1,7 @@ +//go:build !unix + +package server + +func enableLocalKillSubreaper() {} + +func KillLocalTaskProcesses(_ string, _ ExecPrivilege) error { return nil } diff --git a/server/killswitch_unix.go b/server/killswitch_unix.go new file mode 100644 index 000000000..f441527a4 --- /dev/null +++ b/server/killswitch_unix.go @@ -0,0 +1,230 @@ +//go:build unix + +package server + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" + "syscall" + "time" +) + +var subreaperOnce sync.Once + +// enableLocalKillSubreaper marks the panel process as a Linux child subreaper +// (PR_SET_CHILD_SUBREAPER) so orphaned descendants created via setsid, nohup, or +// double-fork are reparented to this process instead of PID 1 and remain visible +// for deterministic termination on Pause/Stop. +func enableLocalKillSubreaper() { + subreaperOnce.Do(func() { + if runtime.GOOS != "linux" { + return + } + const prSetChildSubreaper = 36 + _, _, _ = syscall.Syscall6(syscall.SYS_PRCTL, prSetChildSubreaper, 1, 0, 0, 0, 0) + }) +} + +type procEntry struct { + pid int + ppid int + pgrp int + stat string + uids []int +} + +func readProcTable() []procEntry { + entries, err := os.ReadDir("/proc") + if err != nil { + return nil + } + out := make([]procEntry, 0, len(entries)) + for _, e := range entries { + if !e.IsDir() { + continue + } + name := e.Name() + if len(name) == 0 || name[0] < '0' || name[0] > '9' { + continue + } + pid, err := strconv.Atoi(name) + if err != nil || pid <= 1 { + continue + } + statRaw, err := os.ReadFile(filepath.Join("/proc", name, "stat")) + if err != nil { + continue + } + s := string(statRaw) + rparen := strings.LastIndexByte(s, ')') + if rparen < 0 || rparen+2 >= len(s) { + continue + } + fields := strings.Fields(s[rparen+2:]) + if len(fields) < 3 { + continue + } + ppid, err1 := strconv.Atoi(fields[1]) + pgrp, err2 := strconv.Atoi(fields[2]) + if err1 != nil || err2 != nil { + continue + } + pe := procEntry{pid: pid, ppid: ppid, pgrp: pgrp, stat: fields[0]} + if statusRaw, err := os.ReadFile(filepath.Join("/proc", name, "status")); err == nil { + for _, line := range strings.Split(string(statusRaw), "\n") { + if strings.HasPrefix(line, "Uid:") { + for _, uf := range strings.Fields(line[4:]) { + if u, err := strconv.Atoi(uf); err == nil { + pe.uids = append(pe.uids, u) + } + } + break + } + } + } + out = append(out, pe) + } + return out +} + +func (p procEntry) isZombie() bool { + return p.stat == "Z" || p.stat == "X" +} + +func (p procEntry) hasUID(uid int) bool { + for _, u := range p.uids { + if u == uid { + return true + } + } + return false +} + +// reapDirectChildren is intentionally a no-op because Go's os/exec owns +// Wait4 on direct children; process liveness checks ignore Z/X zombie states. +func reapDirectChildren() {} + +// findLocalTaskPIDs scans /proc without trusting any agent-writable state. +// When priv.Enabled (isolated executor UID), every non-zombie process owning +// priv.UID is returned (cannot be escaped via setsid, nohup, env -i, or double-fork). +// When !priv.Enabled (dev/test mode with PR_SET_CHILD_SUBREAPER), every descendant +// of os.Getpid() whose process group differs from os.Getpgrp() (covering Norma's +// Setpgid shells, setsid/nohup children, and reparented double-fork daemons) is returned. +func findLocalTaskPIDs(taskDir string, priv ExecPrivilege) []int { + self := os.Getpid() + selfPGID := syscall.Getpgrp() + procs := readProcTable() + if len(procs) == 0 { + return nil + } + + if priv.Enabled && priv.UID > 0 { + var matched []int + for _, p := range procs { + if p.pid == self || p.isZombie() { + continue + } + if p.hasUID(int(priv.UID)) { + matched = append(matched, p.pid) + } + } + return matched + } + + children := make(map[int][]procEntry, len(procs)) + for _, p := range procs { + children[p.ppid] = append(children[p.ppid], p) + } + + cleanTaskDir := "" + if strings.TrimSpace(taskDir) != "" { + if abs, err := filepath.Abs(taskDir); err == nil { + cleanTaskDir = abs + } + } + var matched []int + seen := map[int]bool{} + var walk func(parent int, inheritedMatch bool) + walk = func(parent int, inheritedMatch bool) { + for _, ch := range children[parent] { + if ch.pid == self || seen[ch.pid] { + continue + } + seen[ch.pid] = true + inTask := inheritedMatch || ch.pgrp != selfPGID + if !inTask && cleanTaskDir != "" { + if cwd, err := os.Readlink(filepath.Join("/proc", strconv.Itoa(ch.pid), "cwd")); err == nil { + if cwd == cleanTaskDir || strings.HasPrefix(cwd, cleanTaskDir+string(filepath.Separator)) { + inTask = true + } + } + } + if inTask && !ch.isZombie() { + matched = append(matched, ch.pid) + } + walk(ch.pid, inTask) + } + } + walk(self, false) + return matched +} + +// KillLocalTaskProcesses terminates all live local processes belonging to a task +// (including setsid, nohup, and nested double-fork daemons) using /proc directly +// without trusting any agent-writable state. Sends SIGTERM, polls up to 2s, then +// loops SIGKILL until none remain (well within the 5s pause SLA). +func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error { + if runtime.GOOS != "linux" { + return nil + } + selfPGID := syscall.Getpgrp() + // Sweep once immediately, and if nothing matched yet, wait briefly for + // cancelExec to trigger child reparenting before declaring clean. + pids := findLocalTaskPIDs(taskDir, priv) + if len(pids) == 0 { + time.Sleep(40 * time.Millisecond) + pids = findLocalTaskPIDs(taskDir, priv) + if len(pids) == 0 { + return nil + } + } + for _, pid := range pids { + if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID { + _ = syscall.Kill(-pgid, syscall.SIGTERM) + } + _ = syscall.Kill(pid, syscall.SIGTERM) + } + + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + reapDirectChildren() + if len(findLocalTaskPIDs(taskDir, priv)) == 0 { + return nil + } + time.Sleep(25 * time.Millisecond) + } + + for round := 0; round < 15; round++ { + rem := findLocalTaskPIDs(taskDir, priv) + if len(rem) == 0 { + return nil + } + for _, pid := range rem { + if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID { + _ = syscall.Kill(-pgid, syscall.SIGKILL) + } + _ = syscall.Kill(pid, syscall.SIGKILL) + } + time.Sleep(30 * time.Millisecond) + reapDirectChildren() + } + if rem := findLocalTaskPIDs(taskDir, priv); len(rem) > 0 { + return errors.New("some local task processes survived SIGKILL") + } + return nil +} diff --git a/server/killswitch_unix_test.go b/server/killswitch_unix_test.go new file mode 100644 index 000000000..b627ca3a3 --- /dev/null +++ b/server/killswitch_unix_test.go @@ -0,0 +1,364 @@ +//go:build unix + +package server + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/Autumn-27/artex/agent" + "github.com/Autumn-27/norma/llm" + actool "github.com/Autumn-27/norma/tool" +) + +func readRecordedPIDs(path string) []int { + raw, err := os.ReadFile(path) + if err != nil { + return nil + } + var pids []int + seen := map[int]bool{} + for _, f := range strings.Fields(string(raw)) { + p, err := strconv.Atoi(f) + if err == nil && p > 1 && !seen[p] { + seen[p] = true + pids = append(pids, p) + } + } + return pids +} + +func pidAlive(pid int) bool { + if raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")); err == nil { + s := string(raw) + if rp := strings.LastIndexByte(s, ')'); rp >= 0 && rp+2 < len(s) { + fields := strings.Fields(s[rp+2:]) + if len(fields) > 0 && (fields[0] == "Z" || fields[0] == "X") { + return false + } + } + } + err := syscall.Kill(pid, 0) + return err == nil || errors.Is(err, syscall.EPERM) +} + +func waitForPIDs(t *testing.T, path string, wantCount int, timeout time.Duration) []int { + t.Helper() + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + pids := readRecordedPIDs(path) + if len(pids) >= wantCount { + return pids + } + time.Sleep(25 * time.Millisecond) + } + t.Fatalf("timed out waiting for %d PIDs in %s (got %v)", wantCount, path, readRecordedPIDs(path)) + return nil +} + +func assertAllPIDsDeadWithin(t *testing.T, pids []int, limit time.Duration) time.Duration { + t.Helper() + start := time.Now() + deadline := start.Add(limit) + for time.Now().Before(deadline) { + alive := false + for _, pid := range pids { + if pidAlive(pid) { + alive = true + break + } + } + if !alive { + return time.Since(start) + } + time.Sleep(25 * time.Millisecond) + } + var survivors []int + for _, pid := range pids { + if pidAlive(pid) { + survivors = append(survivors, pid) + _ = syscall.Kill(pid, syscall.SIGKILL) + } + } + t.Fatalf("process tree survived pause past %s: surviving PIDs=%v (all=%v)", limit, survivors, pids) + return time.Since(start) +} + +// TestKillSwitchDirectBashProcessTree runs without PostgreSQL to verify that +// cancelling a running Norma Bash tool call (both sh -c 'sleep 300' and a +// local curl | bash fixture) terminates the entire process tree in <= 5s. +func TestKillSwitchDirectBashProcessTree(t *testing.T) { + if _, err := exec.LookPath("curl"); err != nil { + t.Skip("curl not installed") + } + cases := []struct { + name string + buildCmd func(t *testing.T, pidFile string) string + wantCount int + }{ + { + name: "sh_sleep_300", + buildCmd: func(_ *testing.T, pidFile string) string { + return fmt.Sprintf(`sh -c 'echo $$ >> %q; sleep 300 & echo $! >> %q; wait'`, pidFile, pidFile) + }, + wantCount: 2, + }, + { + name: "curl_pipe_bash", + buildCmd: func(t *testing.T, pidFile string) string { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + fmt.Fprintf(w, "echo $$ >> %q\nsleep 300 &\necho $! >> %q\nwait\n", pidFile, pidFile) + })) + t.Cleanup(srv.Close) + return fmt.Sprintf(`curl -fsSL %q | bash`, srv.URL) + }, + wantCount: 2, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + workDir := t.TempDir() + pidFile := filepath.Join(workDir, "pids.txt") + cmdStr := tc.buildCmd(t, pidFile) + + tm, err := actool.NewManager("killswitch-" + tc.name) + if err != nil { + t.Fatal(err) + } + defer tm.Cleanup() + bashTool := actool.NewBash() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + rawInput, _ := json.Marshal(map[string]any{"command": cmdStr, "timeout_ms": 60000}) + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = bashTool.Call(ctx, rawInput, &actool.ToolContext{ + WorkingDir: workDir, + Tasks: tm, + }) + }() + + pids := waitForPIDs(t, pidFile, tc.wantCount, 5*time.Second) + cancel() + elapsed := assertAllPIDsDeadWithin(t, pids, 5*time.Second) + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Bash tool goroutine did not exit within 5s after cancellation") + } + t.Logf("%s: process tree %v killed in %s", tc.name, pids, elapsed) + }) + } +} + +// TestEnginePauseKillSwitchKillsProcessTrees exercises the full Engine.Pause +// kill-switch path (with PostgreSQL) during sh -c 'sleep 300' and during a +// local curl | bash fixture, asserting every process in the tree dies in <= 5s. +func TestEnginePauseKillSwitchKillsProcessTrees(t *testing.T) { + skipWithoutDSN(t) + if _, err := exec.LookPath("curl"); err != nil { + t.Skip("curl not installed") + } + + cases := []struct { + name string + buildCmd func(t *testing.T, pidFile string) string + }{ + { + name: "sh_sleep_300", + buildCmd: func(_ *testing.T, pidFile string) string { + return fmt.Sprintf(`sh -c 'echo $$ >> %q; sleep 300 & echo $! >> %q; wait'`, pidFile, pidFile) + }, + }, + { + name: "curl_pipe_bash", + buildCmd: func(t *testing.T, pidFile string) string { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + fmt.Fprintf(w, "echo $$ >> %q\nsleep 300 &\necho $! >> %q\nwait\n", pidFile, pidFile) + })) + t.Cleanup(srv.Close) + return fmt.Sprintf(`curl -fsSL %q | bash`, srv.URL) + }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, task, e := planningLoopFixture(t) + workDir := t.TempDir() + pidFile := filepath.Join(workDir, "pids.txt") + cmdStr := tc.buildCmd(t, pidFile) + + plannerProv := &planningLoopProvider{response: func(call int, _ llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return planningTool("add_intent", map[string]any{ + "summary": "Run kill-switch fixture command", + }), "tool_use", nil + } + return planningText("dispatched"), "end_turn", nil + }} + workerProv := &planningLoopProvider{response: func(call int, _ llm.CompletionRequest) (llm.Message, string, error) { + if call == 1 { + return planningTool("Bash", map[string]any{ + "command": cmdStr, + "timeout_ms": 60000, + }), "tool_use", nil + } + return planningText("done"), "end_turn", nil + }} + + p := agent.NewPlanner(plannerProv, "fixture", workDir, nil, 100000, 4) + p.SetNonStreaming(func() bool { return true }) + w := agent.NewWorker(workerProv, "fixture", workDir, nil, 100000, 4) + w.SetNonStreaming(func() bool { return true }) + e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) { return p, w }) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + e.Run(ctx, task) + defer e.StopTask(task.ID) + + pids := waitForPIDs(t, pidFile, 2, 10*time.Second) + e.Pause(task.ID, agent.AbortPausedByUser) + elapsed := assertAllPIDsDeadWithin(t, pids, 5*time.Second) + t.Logf("%s: Engine.Pause killed process tree %v in %s", tc.name, pids, elapsed) + }) + } +} + +// TestEnginePauseKillSwitchKillsEscapedDaemonsAndStopsEgress proves that +// Engine.Pause terminates escaped local process trees (setsid, nohup, nested +// double-forked daemons ignoring SIGTERM, and an active HTTP egress loop) within +// <= 5s with zero surviving PIDs and zero post-pause egress requests. +func TestEnginePauseKillSwitchKillsEscapedDaemonsAndStopsEgress(t *testing.T) { + if _, err := exec.LookPath("curl"); err != nil { + t.Skip("curl not installed") + } + enableLocalKillSubreaper() + + cases := []struct { + name string + buildCmd func(t *testing.T, pidFile string) (cmd string, wantPIDs int, checkPostPause func(t *testing.T)) + }{ + { + name: "setsid_detached", + buildCmd: func(_ *testing.T, pidFile string) (string, int, func(*testing.T)) { + cmd := fmt.Sprintf(`setsid sh -c 'echo $$ >> %q; sleep 300 & echo $! >> %q; wait' /dev/null 2>&1 & echo $! >> %q; sleep 300`, pidFile, pidFile, pidFile) + return cmd, 2, nil + }, + }, + { + name: "nohup_background", + buildCmd: func(_ *testing.T, pidFile string) (string, int, func(*testing.T)) { + cmd := fmt.Sprintf(`nohup sh -c 'echo $$ >> %q; sleep 300 & echo $! >> %q; wait' /dev/null 2>&1 & sleep 300`, pidFile, pidFile) + return cmd, 2, nil + }, + }, + { + name: "nested_double_fork_trap_term", + buildCmd: func(_ *testing.T, pidFile string) (string, int, func(*testing.T)) { + cmd := fmt.Sprintf(`sh -c '(setsid sh -c "trap \"\" TERM; echo \$\$ >> %q; sleep 300 & echo \$! >> %q; wait" /dev/null 2>&1 &)'; sleep 300`, pidFile, pidFile) + return cmd, 2, nil + }, + }, + { + name: "setsid_egress_loop_stops_after_pause", + buildCmd: func(t *testing.T, pidFile string) (string, int, func(*testing.T)) { + var hits atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + cmd := fmt.Sprintf(`setsid sh -c 'echo $$ >> %q; while true; do curl -sS -m 1 %q >/dev/null 2>&1; sleep 0.05; done' /dev/null 2>&1 & sleep 300`, pidFile, srv.URL) + verify := func(t *testing.T) { + time.Sleep(100 * time.Millisecond) + afterPause := hits.Load() + if afterPause == 0 { + t.Fatalf("expected canary to receive >=1 hit before pause") + } + time.Sleep(400 * time.Millisecond) + if got := hits.Load(); got != afterPause { + t.Fatalf("daemon kept sending egress after pause: hits grew from %d to %d", afterPause, got) + } + t.Logf("canary hits before pause=%d, after 400ms=%d (zero post-pause egress)", afterPause, hits.Load()) + } + return cmd, 1, verify + }, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dataDir := t.TempDir() + taskDir := filepath.Join(dataDir, "tasks", "ks-escaped") + if err := os.MkdirAll(taskDir, 0o755); err != nil { + t.Fatal(err) + } + pidFile := filepath.Join(taskDir, "pids.txt") + cmd, wantCount, postCheck := tc.buildCmd(t, pidFile) + + e := NewEngine(nil) + e.SetKillSwitchConfig(dataDir, ExecPrivilege{}) + + bashTool := actool.NewBash() + in, _ := json.Marshal(map[string]any{"command": cmd, "timeout_ms": 60000}) + + runCtx, cancel := context.WithCancelCause(context.Background()) + defer cancel(nil) + e.execMu.Lock() + e.execCancel["ks-escaped"] = cancel + e.execCtx["ks-escaped"] = runCtx + e.execMu.Unlock() + defer func() { + e.execMu.Lock() + delete(e.execCancel, "ks-escaped") + delete(e.execCtx, "ks-escaped") + e.execMu.Unlock() + }() + + doneCh := make(chan struct{}) + go func() { + defer close(doneCh) + _, _ = bashTool.Call(runCtx, in, &actool.ToolContext{WorkingDir: taskDir}) + }() + + pids := waitForPIDs(t, pidFile, wantCount, 5*time.Second) + time.Sleep(150 * time.Millisecond) + + pauseStart := time.Now() + e.Pause("ks-escaped", agent.AbortPausedByUser) + elapsed := assertAllPIDsDeadWithin(t, pids, 5*time.Second) + if total := time.Since(pauseStart); total > 5*time.Second { + t.Fatalf("Engine.Pause total elapsed %s > 5s", total) + } + select { + case <-doneCh: + case <-time.After(5 * time.Second): + t.Fatalf("Bash call did not return within 5s of Engine.Pause") + } + if postCheck != nil { + postCheck(t) + } + t.Logf("%s: all PIDs %v terminated in %s (total Pause=%s)", tc.name, pids, elapsed, time.Since(pauseStart)) + }) + } +} diff --git a/server/p0_failclosed_test.go b/server/p0_failclosed_test.go new file mode 100644 index 000000000..76496f408 --- /dev/null +++ b/server/p0_failclosed_test.go @@ -0,0 +1,94 @@ +package server + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestLockDownKeyDirTightensBindMountedDir(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX permission bits checked on Unix") + } + dir := filepath.Join(t.TempDir(), "keys") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o755); err != nil { + t.Fatal(err) + } + jwtPath := filepath.Join(dir, "jwt.key") + secPath := filepath.Join(dir, "secret.key") + if err := os.WriteFile(jwtPath, []byte("0123456789abcdef0123456789abcdef"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(secPath, []byte("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := LockDownKeyDir(dir); err != nil { + t.Fatalf("LockDownKeyDir: %v", err) + } + fi, err := os.Stat(dir) + if err != nil { + t.Fatal(err) + } + if got := fi.Mode().Perm(); got != 0o700 { + t.Fatalf("key dir mode = %#o, want 0700", got) + } + for _, p := range []string{jwtPath, secPath} { + fi, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + if got := fi.Mode().Perm(); got != 0o600 { + t.Fatalf("%s mode = %#o, want 0600", p, got) + } + } + + // Refuses symlinked key files. + symDir := filepath.Join(t.TempDir(), "symkeys") + if err := os.MkdirAll(symDir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink("/etc/passwd", filepath.Join(symDir, "secret.key")); err != nil { + t.Fatal(err) + } + if err := LockDownKeyDir(symDir); err == nil { + t.Fatal("LockDownKeyDir accepted symlinked secret.key") + } +} + +func TestAllowUnisolatedFromEnv(t *testing.T) { + for _, tc := range []struct { + val string + want bool + }{ + {"", false}, + {"0", false}, + {"false", false}, + {"true", false}, + {"1", true}, + {" 1 ", true}, + } { + t.Setenv(AllowUnisolatedEnv, tc.val) + if got := AllowUnisolatedFromEnv(); got != tc.want { + t.Errorf("%s=%q -> %v, want %v", AllowUnisolatedEnv, tc.val, got, tc.want) + } + } +} + +func TestSecurityStartupWarnings(t *testing.T) { + if w := SecurityStartupWarnings(SecurityPostureCheck{EgressMode: "enforce", UngatedActiveTasks: 0}); len(w) != 0 { + t.Fatalf("enforce + 0 ungated tasks produced unexpected warnings: %v", w) + } + out := captureLog(t, func() { + LogSecurityStartupWarnings(SecurityPostureCheck{EgressMode: "monitor", UngatedActiveTasks: 2, TargetGateOptedOut: true}) + }) + for _, want := range []string{"SECURITY POSTURE WARNING", "EGRESS ENFORCEMENT IS OFF", "EGRESS_MODE=monitor", "TARGET GATE IS OFF ON 2 ACTIVE TASK(S)", "TARGET GATE IS OFF BY OPT-OUT"} { + if !strings.Contains(out, want) { + t.Errorf("startup warning output missing %q:\n%s", want, out) + } + } +} diff --git a/server/server.go b/server/server.go index 17e04bde0..38b9a7cc6 100644 --- a/server/server.go +++ b/server/server.go @@ -215,6 +215,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi for _, o := range opts { o(s) } + s.engine.SetKillSwitchConfig(dataDir, s.execPriv) s.initSetupToken() s.loadPasswordVersion() s.initSideQuestions() @@ -1809,7 +1810,7 @@ type createTaskReq struct { LLMRotate *bool `json:"llm_rotate"` // distribute worker intents across the ordered profiles PlanHeartbeatSeconds int `json:"plan_heartbeat_seconds"` // planner heartbeat interval (seconds); 0/omitted = default 600 (10min); floor = default = 600, lower values are raised to 600 PlanQuietMode *bool `json:"plan_quiet_mode,omitempty"` // planner quiet-mode switch (#86); omitted = default on; false = edge rounds always plan - TargetGate *bool `json:"target_gate,omitempty"` // approval gate for asset targets, opt-in; omitted/null = off + TargetGate *bool `json:"target_gate,omitempty"` // approval gate for asset targets; omitted/null defaults ON for scoped tasks (company_ids or intercept_rules) and OFF otherwise; pass false to explicitly opt out SeedFirstIntent *bool `json:"seed_first_intent,omitempty"` // issue one seed intent at creation (content = description + goal) so a worker can start right away without waiting for the first planner round; omitted/null = default off, the standard plan-then-execute flow. Pass true explicitly to enable (for CTF tasks often solved in one work, this skips the pre-start planner round). CoverageEnabled *bool `json:"coverage_enabled,omitempty"` // asset coverage feature; omitted/null = default on (true). false = disables coverage calculation/display/auto-accumulated scope + hides add_task_scope/list_untested_assets. company links are unaffected. // InterceptRules: task-level asset interception/allow rules (entered at creation, stored in task_intercept_rules, never the global table). diff --git a/server/target_gate_flag_test.go b/server/target_gate_flag_test.go index cc1eaee51..1aca315fb 100644 --- a/server/target_gate_flag_test.go +++ b/server/target_gate_flag_test.go @@ -239,8 +239,9 @@ func TestSpawnedTaskInheritsGateFromCaller(t *testing.T) { {Enabled: false, Action: "block", Kind: "cidr", Pattern: "198.51.100.0/24"}, {Enabled: true, Action: "allow", Kind: "exact_domain", Pattern: "allowed.example.com"}, } + off := false gated := g.newTask(t, db.TaskCreateOptions{TargetGate: &on, InterceptRules: parentRules}) - open := g.newTask(t, db.TaskCreateOptions{InterceptRules: parentRules}) + open := g.newTask(t, db.TaskCreateOptions{TargetGate: &off, InterceptRules: parentRules}) if !gated.targetScope(0).Enabled() || open.targetScope(0).Enabled() { t.Fatal("control: one parent gated, the other not") } From bf0b37ad68da4cee616bfda6f275885d36d57bd1 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:08:49 +0100 Subject: [PATCH 2/3] style(server): gofmt the engine field alignment --- server/engine.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server/engine.go b/server/engine.go index 213a03a61..def96866b 100644 --- a/server/engine.go +++ b/server/engine.go @@ -107,12 +107,12 @@ type Engine struct { // quiet-mode (#79): open-goal fingerprint recorded at the end of the last // completed planning round, per task. Edge-triggered rounds are skipped // while it is unchanged and work is still in flight. - goalFP sync.Map // taskID -> string (sorted open-goal ids joined) - paused sync.Map // taskID -> bool, user-paused (planner + workers idle but loops alive) - deleting sync.Map // taskID -> bool, delete barrier (no new task-owned writes) + goalFP sync.Map // taskID -> string (sorted open-goal ids joined) + paused sync.Map // taskID -> bool, user-paused (planner + workers idle but loops alive) + deleting sync.Map // taskID -> bool, delete barrier (no new task-owned writes) killDataDir string killExecPriv ExecPrivilege - dropCnt sync.Map // taskID -> *int64, running count of dropped (unpersistable) activity records + dropCnt sync.Map // taskID -> *int64, running count of dropped (unpersistable) activity records // deleteMu makes installing the delete barrier atomic with registering a new // task operation. Once BeginDelete returns, every admitted writer is reflected From 643e814ad6d05e4085b5bf6dd69ffa1a82c8aa31 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:35:07 +0100 Subject: [PATCH 3/3] 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/:/workspace:rw, only verified internal=true runner-labeled network artex-task-. - 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/:/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. --- CHANGELOG.md | 6 + Dockerfile.egress-proxy | 18 + Dockerfile.runner | 19 + Dockerfile.worker | 34 + README.md | 20 + agent/filetools.go | 2 + agent/sandbox.go | 236 ++++++ agent/sandbox_test.go | 72 ++ agent/webfetch.go | 29 +- cmd/artex-egress-proxy/main.go | 54 ++ cmd/artex-exec-wrap/main.go | 251 ++++++ cmd/artex-exec-wrap/main_other.go | 13 + cmd/artex-runner/main.go | 82 ++ cmd/artex/main.go | 23 +- .../0023_task_scope_operator_approval.sql | 13 + db/retarget.go | 6 +- db/schema.sql | 1 + db/target_gate_backfill_test.go | 2 +- db/task_archives_restore.go | 3 + db/task_scope.go | 67 +- db/task_scope_approval_test.go | 91 ++ db/tasks.go | 18 +- docker-compose.sandbox.yml | 73 ++ docs/SANDBOX.md | 82 ++ sandbox/client.go | 129 +++ sandbox/docker.go | 793 ++++++++++++++++++ sandbox/docker_e2e_test.go | 295 +++++++ sandbox/policy.go | 371 ++++++++ sandbox/proxy.go | 303 +++++++ sandbox/runner.go | 166 ++++ sandbox/sandbox_test.go | 517 ++++++++++++ sandbox/types.go | 141 ++++ sandbox/validate.go | 112 +++ server/assembly.go | 33 +- server/customtool.go | 105 ++- server/engine.go | 76 +- server/intercept.go | 16 +- server/orchestration.go | 1 + server/sandbox.go | 178 ++++ server/sandbox_scope_drift_test.go | 346 ++++++++ server/sandbox_test.go | 340 ++++++++ server/server.go | 23 +- server/server_mgmt.go | 10 + server/sharedbrowser_guard.go | 81 +- 44 files changed, 5209 insertions(+), 42 deletions(-) create mode 100644 Dockerfile.egress-proxy create mode 100644 Dockerfile.runner create mode 100644 Dockerfile.worker create mode 100644 agent/sandbox.go create mode 100644 agent/sandbox_test.go create mode 100644 cmd/artex-egress-proxy/main.go create mode 100644 cmd/artex-exec-wrap/main.go create mode 100644 cmd/artex-exec-wrap/main_other.go create mode 100644 cmd/artex-runner/main.go create mode 100644 db/migrations/0023_task_scope_operator_approval.sql create mode 100644 db/task_scope_approval_test.go create mode 100644 docker-compose.sandbox.yml create mode 100644 docs/SANDBOX.md create mode 100644 sandbox/client.go create mode 100644 sandbox/docker.go create mode 100644 sandbox/docker_e2e_test.go create mode 100644 sandbox/policy.go create mode 100644 sandbox/proxy.go create mode 100644 sandbox/runner.go create mode 100644 sandbox/sandbox_test.go create mode 100644 sandbox/types.go create mode 100644 sandbox/validate.go create mode 100644 server/sandbox.go create mode 100644 server/sandbox_scope_drift_test.go create mode 100644 server/sandbox_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index e7cfbb04f..d5fe70a05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## [Unreleased] + +### Breaking Changes +- **Upgrade note (migration `0023_task_scope_operator_approval.sql`)**: Existing `source = 'manual'` `task_scope` rows are backfilled to `approved_by_operator = TRUE`, while goal-derived/agent (`source = 'agent'`) and auto (`source = 'auto'`) scopes remain `FALSE` and must be re-approved once via the Task Scope UI to grant sandbox egress. Target-gate approval clears only the tool gate; worker egress still requires operator-approved Task Scope. +- **Container sandbox required by default (`ARTEX_SANDBOX=required`)**: agent execution (`Bash`, custom command/script tools) now routes to disposable per-task `artex-worker` containers via `artex-runner` (`docker-compose.sandbox.yml`) with an `internal: true` per-task network and DNS-pinning HTTP/SOCKS5 egress allowlist proxy (`artex-egress-proxy`). Tasks refuse to start or pause when the runner is unavailable (no silent local fallback). Pass `ARTEX_SANDBOX=off` for explicit degraded local mode (logs a loud startup warning and records `sandbox=off` in every task event log). + # Changelog All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). diff --git a/Dockerfile.egress-proxy b/Dockerfile.egress-proxy new file mode 100644 index 000000000..3a9ed789a --- /dev/null +++ b/Dockerfile.egress-proxy @@ -0,0 +1,18 @@ +# ARTEX per-task egress allowlist proxy (HTTP/CONNECT :3128 + SOCKS5 :1080, CONTRACT.md §5). +FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build +WORKDIR /src +COPY go.mod go.sum ./ +COPY sandbox/ ./sandbox/ +COPY cmd/artex-egress-proxy/ ./cmd/artex-egress-proxy/ +ARG TARGETOS=linux +ARG TARGETARCH=amd64 +RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" \ + -o /out/artex-egress-proxy ./cmd/artex-egress-proxy + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* \ + && groupadd -g 10001 exec && useradd -u 10001 -g 10001 -d /nonexistent -s /usr/sbin/nologin exec +COPY --from=build /out/artex-egress-proxy /usr/local/bin/artex-egress-proxy +USER 10001:10001 +EXPOSE 3128 1080 +ENTRYPOINT ["/usr/local/bin/artex-egress-proxy"] diff --git a/Dockerfile.runner b/Dockerfile.runner new file mode 100644 index 000000000..37e6b7a52 --- /dev/null +++ b/Dockerfile.runner @@ -0,0 +1,19 @@ +# ARTEX sandbox runner service (CONTRACT.md §2). +# The ONLY component that mounts /var/run/docker.sock. +FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build +WORKDIR /src +COPY go.mod go.sum ./ +COPY sandbox/ ./sandbox/ +COPY cmd/artex-runner/ ./cmd/artex-runner/ +ARG ARTEX_VERSION=dev +ARG TARGETOS=linux +ARG TARGETARCH=amd64 +RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \ + -ldflags="-s -w -X main.version=${ARTEX_VERSION}" \ + -o /out/artex-runner ./cmd/artex-runner + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/* +COPY --from=build /out/artex-runner /usr/local/bin/artex-runner +EXPOSE 8789 +ENTRYPOINT ["/usr/local/bin/artex-runner"] diff --git a/Dockerfile.worker b/Dockerfile.worker new file mode 100644 index 000000000..1f54497d7 --- /dev/null +++ b/Dockerfile.worker @@ -0,0 +1,34 @@ +# ARTEX isolated per-task worker image (CONTRACT.md §4). +# Runs as uid/gid 10001, read-only rootfs, cap_drop ALL, no-new-privileges, +# mounted ONLY with /app/data/tasks/:/workspace:rw and connected ONLY to +# the per-task internal network artex-task-. +FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS wrap-build +WORKDIR /src +COPY go.mod go.sum ./ +COPY cmd/artex-exec-wrap/ ./cmd/artex-exec-wrap/ +ARG TARGETOS=linux +ARG TARGETARCH=amd64 +RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" -o /out/artex-exec-wrap ./cmd/artex-exec-wrap + +FROM debian:bookworm-slim +RUN set -eux; \ + apt-get update; \ + apt-get install -y --no-install-recommends \ + bash ca-certificates curl dnsutils git iputils-ping jq netcat-openbsd \ + nmap openssh-client perl python3 procps; \ + rm -rf /var/lib/apt/lists/*; \ + groupadd -g 10001 exec; \ + useradd -u 10001 -g 10001 -d /home/exec -m -s /bin/bash exec; \ + mkdir -p /workspace /home/exec; \ + chown -R 10001:10001 /workspace /home/exec; \ + find / -xdev -perm /6000 -type f -exec chmod a-s {} + + +COPY --from=wrap-build /out/artex-exec-wrap /usr/local/bin/artex-exec-wrap +RUN chmod 0755 /usr/local/bin/artex-exec-wrap + +USER 10001:10001 +WORKDIR /workspace +ENV HOME=/home/exec \ + LANG=C.UTF-8 \ + TERM=xterm +CMD ["sleep", "infinity"] diff --git a/README.md b/README.md index 726ade5f1..4c20b3622 100644 --- a/README.md +++ b/README.md @@ -1167,3 +1167,23 @@ This project is provided "as is", without any express or implied warranty. The a contributors are not liable for any direct or indirect loss, data loss, system damage or legal dispute caused by the use of this tool (whether used properly or not). **Downloading, installing or using this project means you have read, understood and agreed to all of the above terms.** + +## Container Sandbox (`ARTEX_SANDBOX=required` default) + +> **Breaking change:** `ARTEX_SANDBOX` defaults to `required`. Agent commands +> (`Bash`, shell, custom command/script tools) execute inside disposable per-task +> `artex-worker` containers via `artex-runner` rather than on the panel container. +> If `artex-runner` is unavailable, ARTEX refuses to start tasks and pauses +> running tasks with no local fallback. To explicitly opt out for local +> development, set `ARTEX_SANDBOX=off` (logs a loud startup banner and writes +> `sandbox=off` into each task's event log). + +Launch with the sandbox overlay: + +```bash +docker compose -f docker-compose.yml -f docker-compose.sandbox.yml --profile build-only build +docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d +``` + +See [`docs/SANDBOX.md`](docs/SANDBOX.md) for the runner API, per-task internal +network, HTTP/SOCKS5 egress allowlist proxy, and security boundary. diff --git a/agent/filetools.go b/agent/filetools.go index ce81d2100..82199db44 100644 --- a/agent/filetools.go +++ b/agent/filetools.go @@ -50,6 +50,8 @@ func defaultTools(base string) []actool.CoreTool { for _, t := range all { if run, ok := confinedFileToolNames[t.Name()]; ok { t = &confinedFileTool{CoreTool: t, base: base, run: run} + } else if t.Name() == "Bash" { + t = &sandboxBashTool{CoreTool: t} } out = append(out, t) } diff --git a/agent/sandbox.go b/agent/sandbox.go new file mode 100644 index 000000000..6abef12f7 --- /dev/null +++ b/agent/sandbox.go @@ -0,0 +1,236 @@ +package agent + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "path" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + + "github.com/Autumn-27/artex/sandbox" + actool "github.com/Autumn-27/norma/tool" +) + +// SandboxRunner is the minimal execution interface the agent package needs from +// the runner client (*sandbox.Client in production, fakes in unit tests). +type SandboxRunner interface { + Exec(ctx context.Context, taskID string, req sandbox.ExecRequest) (sandbox.ExecResponse, error) +} + +// SandboxExecutor wires the panel's sandbox mode and runner client into agent tools. +type SandboxExecutor struct { + Mode string + Runner SandboxRunner + OnUnavailable func(taskID string, err error) +} + +var activeSandboxExecutor atomic.Pointer[SandboxExecutor] + +// SetSandboxExecutor installs (or clears when nil) the process-wide sandbox executor. +func SetSandboxExecutor(ex *SandboxExecutor) { + activeSandboxExecutor.Store(ex) +} + +// CurrentSandboxExecutor returns the installed sandbox executor, if any. +func CurrentSandboxExecutor() *SandboxExecutor { + return activeSandboxExecutor.Load() +} + +// SandboxRequired reports whether the process-wide sandbox executor is in required mode. +func SandboxRequired() bool { + ex := activeSandboxExecutor.Load() + return ex != nil && ex.Mode == sandbox.ModeRequired +} + +// SandboxRunInfo carries per-task sandbox metadata on context.Context. +type SandboxRunInfo struct { + TaskID string + TaskDir string // panel host path for /app/data/tasks/ + ScopeDomains []string + ScopeCIDRs []string +} + +type sandboxCtxKey struct{} + +// WithSandboxRunInfo attaches per-task sandbox metadata to ctx. +func WithSandboxRunInfo(ctx context.Context, info SandboxRunInfo) context.Context { + return context.WithValue(ctx, sandboxCtxKey{}, info) +} + +// SandboxRunInfoFromContext retrieves per-task sandbox metadata from ctx. +func SandboxRunInfoFromContext(ctx context.Context) (SandboxRunInfo, bool) { + if ctx == nil { + return SandboxRunInfo{}, false + } + v, ok := ctx.Value(sandboxCtxKey{}).(SandboxRunInfo) + return v, ok && v.TaskID != "" +} + +// containerWorkdir maps a panel WorkingDir under TaskDir onto /workspace inside the worker. +func containerWorkdir(taskDir, workingDir string) string { + if strings.TrimSpace(workingDir) == "" || strings.TrimSpace(taskDir) == "" { + return "/workspace" + } + rel, err := filepath.Rel(filepath.Clean(taskDir), filepath.Clean(workingDir)) + if err != nil || rel == "." || strings.HasPrefix(rel, "..") || filepath.IsAbs(rel) { + return "/workspace" + } + return path.Clean("/workspace/" + filepath.ToSlash(rel)) +} + +// ExecInSandbox runs argv inside the task's worker container via the configured runner. +// In ARTEX_SANDBOX=required mode it fails closed (no local fallback) and notifies +// OnUnavailable when the runner cannot be reached so the engine pauses the task. +func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeoutMS int, env []string) (sandbox.ExecResponse, error) { + ex := activeSandboxExecutor.Load() + if ex == nil || ex.Mode != sandbox.ModeRequired { + return sandbox.ExecResponse{}, errors.New("sandbox executor not in required mode") + } + info, ok := SandboxRunInfoFromContext(ctx) + if !ok || info.TaskID == "" { + return sandbox.ExecResponse{}, fmt.Errorf("%w: missing task sandbox context (no local fallback)", sandbox.ErrRunnerUnavailable) + } + if ex.Runner == nil { + err := fmt.Errorf("%w: runner client is not configured", sandbox.ErrRunnerUnavailable) + if ex.OnUnavailable != nil { + ex.OnUnavailable(info.TaskID, err) + } + return sandbox.ExecResponse{}, err + } + req := sandbox.ExecRequest{ + Argv: argv, + Workdir: containerWorkdir(info.TaskDir, workingDir), + TimeoutMS: timeoutMS, + Env: sandbox.FilterPanelEnv(env), + ScopeDomains: info.ScopeDomains, + ScopeCIDRs: info.ScopeCIDRs, + } + resp, err := ex.Runner.Exec(ctx, info.TaskID, req) + if err != nil && sandbox.IsUnavailable(err) && ex.OnUnavailable != nil { + ex.OnUnavailable(info.TaskID, err) + } + return resp, err +} + +// sandboxBashTool wraps the SDK Bash tool so all Bash invocations route through +// artex-runner when ARTEX_SANDBOX=required (CONTRACT.md §§3, 6). +type sandboxBashTool struct { + actool.CoreTool +} + +func (t *sandboxBashTool) Call(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + if !SandboxRequired() { + return t.CoreTool.Call(ctx, input, tc) + } + var in struct { + Command string `json:"command"` + TimeoutMS int `json:"timeout_ms"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Errorf(fmt.Sprintf("Error: invalid Bash arguments: %v", err)), nil + } + if strings.TrimSpace(in.Command) == "" { + return actool.Errorf("Error: command is required"), nil + } + workDir := "" + var env []string + if tc != nil { + workDir = tc.WorkingDir + env = tc.Env + } + resp, err := ExecInSandbox(ctx, []string{"bash", "-c", in.Command}, workDir, in.TimeoutMS, env) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error: sandbox execution failed (ARTEX_SANDBOX=required, no local fallback): %v", err)), nil + } + return formatSandboxExecResult(resp, tc), nil +} + +func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext) actool.Result { + var b strings.Builder + if resp.Stdout != "" { + b.WriteString(resp.Stdout) + } + if resp.Stderr != "" { + if b.Len() > 0 && !strings.HasSuffix(b.String(), "\n") { + b.WriteByte('\n') + } + b.WriteString(resp.Stderr) + } + if resp.Truncated { + b.WriteString("\n[output truncated at 1 MiB]") + } + out := b.String() + if tc != nil { + out = actool.Capture(tc, out) + } + if resp.TimedOut { + return actool.Errorf(fmt.Sprintf("%s\n\n[command timed out (exit code %d)]", out, resp.ExitCode)) + } + if resp.ExitCode != 0 { + if strings.TrimSpace(out) == "" { + out = "(no output)" + } + return actool.Errorf(fmt.Sprintf("%s\n\n[exit code %d]", out, resp.ExitCode)) + } + if strings.TrimSpace(out) == "" { + out = "(command produced no output)" + } + return actool.Text(out) +} + +// sandboxScopeDialContext wraps baseDial so every TCP connection made by panel +// WebFetch in ARTEX_SANDBOX=required mode validates and pins the target IP via +// the task's sandbox.EgressPolicy (blocking non-scope IPs, IMDS, loopback, +// RFC1918, and IPv6 across all hops and redirects). +func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) { + return func(ctx context.Context, network, addr string) (net.Conn, error) { + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + return nil, fmt.Errorf("sandbox WebFetch blocked invalid target %q: %w", addr, err) + } + port, err := strconv.Atoi(portStr) + if err != nil || port <= 0 || port > 65535 { + return nil, fmt.Errorf("sandbox WebFetch blocked invalid port %q", portStr) + } + pinnedIP, err := policy.ResolveAndCheck(ctx, host) + if err != nil { + return nil, fmt.Errorf("sandbox WebFetch blocked: %w", err) + } + pinnedAddr := net.JoinHostPort(pinnedIP.String(), strconv.Itoa(port)) + if baseDial != nil { + return baseDial(ctx, network, pinnedAddr) + } + var d net.Dialer + return d.DialContext(ctx, network, pinnedAddr) + } +} + +// sandboxScopeWebFetchTool gates WebFetch inputs against the task's +// sandbox.EgressPolicy before Norma issues any HTTP request. +type sandboxScopeWebFetchTool struct { + actool.CoreTool + policy *sandbox.EgressPolicy +} + +func (t *sandboxScopeWebFetchTool) Call(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + if SandboxRequired() { + var in struct { + URL string `json:"url"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Errorf(fmt.Sprintf("Error: invalid WebFetch arguments: %v", err)), nil + } + if t.policy == nil { + return actool.Errorf("Error: sandbox WebFetch blocked: missing task egress policy"), nil + } + if err := t.policy.CheckURL(ctx, in.URL); err != nil { + return actool.Errorf(fmt.Sprintf("Error: sandbox WebFetch blocked: %v", err)), nil + } + } + return t.CoreTool.Call(ctx, input, tc) +} diff --git a/agent/sandbox_test.go b/agent/sandbox_test.go new file mode 100644 index 000000000..0121e8a98 --- /dev/null +++ b/agent/sandbox_test.go @@ -0,0 +1,72 @@ +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()) + } +} diff --git a/agent/webfetch.go b/agent/webfetch.go index a230f9ddd..6dadd58e7 100644 --- a/agent/webfetch.go +++ b/agent/webfetch.go @@ -7,6 +7,7 @@ import ( "github.com/Autumn-27/artex/egress" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/sandbox" actool "github.com/Autumn-27/norma/tool" ) @@ -25,9 +26,26 @@ import ( func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert string) []actool.CoreTool { scope, scoped := intercept.TargetScopeFromContext(ctx) gated := scoped && scope.Enabled != nil && scope.Enabled() + dialer := intercept.PinnedDialer("WebFetch", scoped) + disableDirect := gated + var sbPolicy *sandbox.EgressPolicy + if SandboxRequired() { + info, _ := SandboxRunInfoFromContext(ctx) + pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil) + if err != nil { + pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil) + } + sbPolicy = pol + dialer = sandboxScopeDialContext(pol, dialer) + disableDirect = true + } webFetch := actool.NewWebFetch(actool.WebFetchConfig{Proxy: proxy, CACert: caCert, CheckRedirect: intercept.RedirectCheck("WebFetch"), - DialContext: intercept.PinnedDialer("WebFetch", scoped), DisableDirectRetry: gated}) - return append(tools[:len(tools):len(tools)], governedFetch{webFetch}) + DialContext: dialer, DisableDirectRetry: disableDirect}) + var wrapped actool.CoreTool = governedFetch{webFetch} + if SandboxRequired() { + wrapped = &sandboxScopeWebFetchTool{CoreTool: wrapped, policy: sbPolicy} + } + return append(tools[:len(tools):len(tools)], wrapped) } // egressGovernor resolves the governor of a WebFetch call, once per call so a @@ -60,3 +78,10 @@ func (f governedFetch) Call(ctx context.Context, input json.RawMessage, tc *acto return f.CoreTool.Call(ctx, input, tc) }) } + +// NewWebFetchTool builds a WebFetch tool configured for ctx (including +// ARTEX_SANDBOX=required scope enforcement when SandboxRequired() is true). +func NewWebFetchTool(ctx context.Context, proxy, caCert string) actool.CoreTool { + tools := withWebFetch(ctx, nil, proxy, caCert) + return tools[len(tools)-1] +} diff --git a/cmd/artex-egress-proxy/main.go b/cmd/artex-egress-proxy/main.go new file mode 100644 index 000000000..e0f455553 --- /dev/null +++ b/cmd/artex-egress-proxy/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + + "github.com/Autumn-27/artex/sandbox" +) + +func envInt(name string, def int) int { + if v := strings.TrimSpace(os.Getenv(name)); v != "" { + if n, err := strconv.Atoi(v); err == nil && n > 0 { + return n + } + } + return def +} + +func main() { + taskID := strings.TrimSpace(os.Getenv("ARTEX_TASK_ID")) + domains := sandbox.ParseCSV(os.Getenv("ARTEX_SCOPE_DOMAINS")) + cidrs := sandbox.ParseCSV(os.Getenv("ARTEX_SCOPE_CIDRS")) + httpPort := envInt("ARTEX_PROXY_PORT", sandbox.DefaultProxyPort) + socksPort := envInt("ARTEX_SOCKS_PORT", sandbox.DefaultSocksPort) + logPath := strings.TrimSpace(os.Getenv("ARTEX_EGRESS_LOG_PATH")) + if logPath == "" && taskID != "" { + logPath = fmt.Sprintf("/app/data/tasks/%s/egress.jsonl", taskID) + } + + logger := sandbox.NewEgressLogger(taskID, logPath, os.Stdout) + defer logger.Close() + + policy, err := sandbox.NewEgressPolicy(taskID, domains, cidrs, logger) + if err != nil { + log.Fatalf("[egress-proxy] invalid scope policy: %v", err) + } + proxy := sandbox.NewEgressProxy(policy) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + httpAddr := fmt.Sprintf(":%d", httpPort) + socksAddr := fmt.Sprintf(":%d", socksPort) + log.Printf("[egress-proxy] task=%s http=%s socks5=%s domains=%d cidrs=%d", taskID, httpAddr, socksAddr, len(domains), len(cidrs)) + if err := proxy.ListenAndServe(ctx, httpAddr, socksAddr); err != nil { + log.Fatalf("[egress-proxy] failed: %v", err) + } +} diff --git a/cmd/artex-exec-wrap/main.go b/cmd/artex-exec-wrap/main.go new file mode 100644 index 000000000..58f7b7357 --- /dev/null +++ b/cmd/artex-exec-wrap/main.go @@ -0,0 +1,251 @@ +//go:build unix + +// Command artex-exec-wrap serves three roles inside artex-worker containers: +// 1. `--init`: runs as PID 1 inside the worker container, reaping all orphaned +// children (including setsid/nohup/double-fork descendants) on SIGCHLD until +// SIGTERM/SIGINT. +// 2. `--kill-uid `: executed as uid 10001 by artex-runner on Kill() (keeps --cap-drop ALL intact without CAP_KILL); scans /proc +// directly (trusting zero agent-writable state), sends SIGTERM then SIGKILL to +// every process owned by other than PID 1 and the killer itself, and +// exits 0 only when verified zero matching processes remain. +// 3. ` -- `: executes argv directly (zero shell +// interpolation) in its own process group, enforcing timeout_ms (SIGTERM -> +// 5s -> SIGKILL, exit 124). +package main + +import ( + "errors" + "fmt" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" +) + +func main() { + os.Exit(run()) +} + +func run() int { + if len(os.Args) == 2 && os.Args[1] == "--init" { + return runInit() + } + if len(os.Args) == 3 && os.Args[1] == "--kill-uid" { + uid, err := strconv.Atoi(strings.TrimSpace(os.Args[2])) + if err != nil || uid <= 0 { + fmt.Fprintln(os.Stderr, "usage: artex-exec-wrap --kill-uid ") + return 2 + } + return killUID(uid) + } + if len(os.Args) < 4 || os.Args[2] != "--" { + fmt.Fprintln(os.Stderr, "usage: artex-exec-wrap -- ") + return 2 + } + timeoutMS, err := strconv.Atoi(os.Args[1]) + if err != nil || timeoutMS <= 0 { + timeoutMS = 600000 + } + argv := os.Args[3:] + + cmd := exec.Command(argv[0], argv[1:]...) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + + if err := cmd.Start(); err != nil { + fmt.Fprintln(os.Stderr, err.Error()) + return 127 + } + pgid := cmd.Process.Pid + + waitCh := make(chan error, 1) + go func() { waitCh <- cmd.Wait() }() + + sigCh := make(chan os.Signal, 2) + signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT) + defer signal.Stop(sigCh) + + timer := time.NewTimer(time.Duration(timeoutMS) * time.Millisecond) + defer timer.Stop() + + select { + case err := <-waitCh: + return exitCodeFrom(err) + case <-timer.C: + terminateGroup(pgid, waitCh, 5*time.Second) + return 124 + case <-sigCh: + terminateGroup(pgid, waitCh, 5*time.Second) + return 143 + } +} + +// runInit runs as PID 1 inside the worker container, reaping any orphaned +// children via Wait4(-1, WNOHANG) so zombies never accumulate or block Kill(). +func runInit() int { + chldCh := make(chan os.Signal, 16) + termCh := make(chan os.Signal, 2) + signal.Notify(chldCh, syscall.SIGCHLD) + signal.Notify(termCh, syscall.SIGTERM, syscall.SIGINT) + defer signal.Stop(chldCh) + defer signal.Stop(termCh) + + reap := func() { + for { + var ws syscall.WaitStatus + pid, err := syscall.Wait4(-1, &ws, syscall.WNOHANG, nil) + if pid <= 0 || err != nil { + break + } + } + } + + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-chldCh: + reap() + case <-ticker.C: + reap() + case <-termCh: + reap() + return 0 + } + } +} + +func terminateGroup(pgid int, waitCh <-chan error, grace time.Duration) { + _ = syscall.Kill(-pgid, syscall.SIGTERM) + select { + case <-waitCh: + return + case <-time.After(grace): + _ = syscall.Kill(-pgid, syscall.SIGKILL) + <-waitCh + } +} + +// killUID scans /proc directly (never reading any agent-writable state) and +// terminates every non-zombie process belonging to targetUID except PID 1 and +// os.Getpid(). Sends SIGTERM, polls up to 2s, then loops SIGKILL until verified +// zero matching processes remain (exits 1 if any survive). +func killUID(targetUID int) int { + self := os.Getpid() + selfPGID := syscall.Getpgrp() + + pids := findProcessesByUID(targetUID, self) + if len(pids) == 0 { + return 0 + } + for _, pid := range pids { + if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID { + _ = syscall.Kill(-pgid, syscall.SIGTERM) + } + _ = syscall.Kill(pid, syscall.SIGTERM) + } + + // Poll up to 2s so cooperative processes exit cleanly while hostile trap '' TERM + // daemons still get SIGKILLed and verified dead well within the 5s SLA. + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if len(findProcessesByUID(targetUID, self)) == 0 { + return 0 + } + time.Sleep(25 * time.Millisecond) + } + + // Escalate to SIGKILL in rounds to defeat fork/respawn loops. + for round := 0; round < 20; round++ { + rem := findProcessesByUID(targetUID, self) + if len(rem) == 0 { + return 0 + } + for _, pid := range rem { + if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID { + _ = syscall.Kill(-pgid, syscall.SIGKILL) + } + _ = syscall.Kill(pid, syscall.SIGKILL) + } + time.Sleep(30 * time.Millisecond) + } + + if rem := findProcessesByUID(targetUID, self); len(rem) > 0 { + fmt.Fprintf(os.Stderr, "kill-uid %d: surviving pids=%v\n", targetUID, rem) + return 1 + } + return 0 +} + +// findProcessesByUID returns all non-zombie PIDs (excluding PID 1 and excludePID) +// whose /proc//status Uid line contains targetUID. +func findProcessesByUID(targetUID, excludePID int) []int { + entries, err := os.ReadDir("/proc") + if err != nil { + return nil + } + var out []int + for _, e := range entries { + if !e.IsDir() { + continue + } + name := e.Name() + if len(name) == 0 || name[0] < '0' || name[0] > '9' { + continue + } + pid, err := strconv.Atoi(name) + if err != nil || pid <= 1 || pid == excludePID { + continue + } + statRaw, err := os.ReadFile(filepath.Join("/proc", name, "stat")) + if err != nil { + continue + } + s := string(statRaw) + rparen := strings.LastIndexByte(s, ')') + if rparen < 0 || rparen+2 >= len(s) { + continue + } + fields := strings.Fields(s[rparen+2:]) + if len(fields) == 0 || fields[0] == "Z" || fields[0] == "X" { + continue + } + statusRaw, err := os.ReadFile(filepath.Join("/proc", name, "status")) + if err != nil { + continue + } + matched := false + for _, line := range strings.Split(string(statusRaw), "\n") { + if strings.HasPrefix(line, "Uid:") { + for _, uf := range strings.Fields(line[4:]) { + if u, err := strconv.Atoi(uf); err == nil && u == targetUID { + matched = true + break + } + } + break + } + } + if matched { + out = append(out, pid) + } + } + return out +} + +func exitCodeFrom(err error) int { + if err == nil { + return 0 + } + var ee *exec.ExitError + if errors.As(err, &ee) { + return ee.ExitCode() + } + return 1 +} diff --git a/cmd/artex-exec-wrap/main_other.go b/cmd/artex-exec-wrap/main_other.go new file mode 100644 index 000000000..3f24dbce8 --- /dev/null +++ b/cmd/artex-exec-wrap/main_other.go @@ -0,0 +1,13 @@ +//go:build !unix + +package main + +import ( + "fmt" + "os" +) + +func main() { + fmt.Fprintln(os.Stderr, "artex-exec-wrap requires Unix") + os.Exit(1) +} diff --git a/cmd/artex-runner/main.go b/cmd/artex-runner/main.go new file mode 100644 index 000000000..830313124 --- /dev/null +++ b/cmd/artex-runner/main.go @@ -0,0 +1,82 @@ +package main + +import ( + "context" + "log" + "net/http" + "os" + "os/signal" + "strings" + "syscall" + "time" + + "github.com/Autumn-27/artex/sandbox" +) + +var version = "dev" + +func envOr(k, def string) string { + if v := strings.TrimSpace(os.Getenv(k)); v != "" { + return v + } + return def +} + +func main() { + token := strings.TrimSpace(os.Getenv(sandbox.EnvRunnerToken)) + if token == "" { + log.Fatalf("[runner] %s is required (refusing to start unauthenticated)", sandbox.EnvRunnerToken) + } + addr := envOr("ARTEX_RUNNER_ADDR", sandbox.DefaultRunnerAddr) + sock := envOr("DOCKER_SOCK", "/var/run/docker.sock") + if dh := strings.TrimSpace(os.Getenv("DOCKER_HOST")); strings.HasPrefix(dh, "unix://") { + sock = strings.TrimPrefix(dh, "unix://") + } + + wsRoot := envOr(sandbox.EnvWorkspaceRoot, sandbox.DefaultWorkspaceRoot) + hostWSRoot := envOr("ARTEX_HOST_WORKSPACE_ROOT", wsRoot) + auditRoot := envOr(sandbox.EnvAuditRoot, sandbox.DefaultAuditRoot) + hostAuditRoot := envOr("ARTEX_HOST_AUDIT_ROOT", auditRoot) + backend := sandbox.NewDockerBackend(sandbox.DockerConfig{ + SocketPath: sock, + WorkerImage: envOr(sandbox.EnvWorkerImage, sandbox.DefaultWorkerImage), + ProxyImage: envOr(sandbox.EnvProxyImage, sandbox.DefaultProxyImage), + WorkspaceRoot: wsRoot, + HostWorkspaceRoot: hostWSRoot, + AuditRoot: auditRoot, + HostAuditRoot: hostAuditRoot, + TaskNetPrefix: envOr(sandbox.EnvTaskNetPrefix, sandbox.DefaultTaskNetPrefix), + EgressNet: envOr(sandbox.EnvEgressNet, sandbox.DefaultEgressNet), + }) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + if n, err := backend.Recover(ctx); err != nil { + log.Printf("[runner] startup container recovery warning: %v", err) + } else { + log.Printf("[runner] recovered %d managed task container(s) by label", n) + } + + rs, err := sandbox.NewRunnerServer(token, version, backend) + if err != nil { + log.Fatalf("[runner] init failed: %v", err) + } + srv := &http.Server{ + Addr: addr, + Handler: rs.Handler(), + ReadHeaderTimeout: 10 * time.Second, + } + go func() { + log.Printf("[runner] listening on %s (version=%s)", addr, version) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("[runner] serve failed: %v", err) + } + }() + + <-ctx.Done() + log.Printf("[runner] shutting down") + sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = srv.Shutdown(sctx) +} diff --git a/cmd/artex/main.go b/cmd/artex/main.go index 80b101fb9..0371af0e4 100644 --- a/cmd/artex/main.go +++ b/cmd/artex/main.go @@ -25,6 +25,7 @@ import ( "github.com/Autumn-27/artex/config" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/egress" + "github.com/Autumn-27/artex/sandbox" "github.com/Autumn-27/artex/server" ) @@ -255,7 +256,27 @@ func run() int { UngatedActiveTasks: ungatedActive, }) - srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv), server.WithIsolationStatus(isolation), server.WithSharedBrowser(*sharedBrowser), server.WithSharedBrowserLockTimeout(*sharedBrowserLockTimeout)) + sandboxCfg, err := sandbox.PanelConfigFromEnv() + if err != nil { + slog.Error("[sandbox] invalid configuration", "err", err) + return 1 + } + var sandboxClient server.SandboxClient + if sandboxCfg.Mode == sandbox.ModeRequired { + sandboxClient = sandbox.NewClient(sandboxCfg.RunnerURL, sandboxCfg.RunnerToken) + hctx, hcancel := context.WithTimeout(ctx, 5*time.Second) + h, herr := sandboxClient.Health(hctx) + hcancel() + if herr != nil || !h.OK || !h.Docker { + slog.Warn("[sandbox] ARTEX_SANDBOX=required: runner is currently unavailable; tasks will be refused until artex-runner is healthy", "runner_url", sandboxCfg.RunnerURL, "err", herr) + } else { + slog.Info("[sandbox] ARTEX_SANDBOX=required: connected to artex-runner", "runner_url", sandboxCfg.RunnerURL, "workers", h.Workers, "version", h.Version) + } + } else { + server.LogSandboxOffBanner() + } + + srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted), server.WithExecPrivilege(priv), server.WithIsolationStatus(isolation), server.WithSharedBrowser(*sharedBrowser), server.WithSharedBrowserLockTimeout(*sharedBrowserLockTimeout), server.WithSandbox(sandboxClient, sandboxCfg.Mode)) // ReadTimeout bounds how long the request headers and body may take to arrive. // It does not limit how long a handler runs, so an event stream stays open. // WriteTimeout is left unset: a write deadline would cut that stream. diff --git a/db/migrations/0023_task_scope_operator_approval.sql b/db/migrations/0023_task_scope_operator_approval.sql new file mode 100644 index 000000000..65c9d372d --- /dev/null +++ b/db/migrations/0023_task_scope_operator_approval.sql @@ -0,0 +1,13 @@ +-- Operator-only approval flag on task_scope rows. +-- Agent-added (add_task_scope) and auto-added (insert_assets) rows remain +-- coverage-only (approved_by_operator=false) and never grant sandbox egress. +ALTER TABLE task_scope ADD COLUMN IF NOT EXISTS approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE; + +-- Backfill existing operator-entered ('manual') task_scope rows so upgraded +-- tasks retain sandbox egress; goal-derived/agent ('agent') and 'auto' rows +-- remain false and must be re-approved once via the task scope UI if egress +-- is required. +UPDATE task_scope +SET approved_by_operator = TRUE +WHERE source = 'manual' + AND approved_by_operator = FALSE; diff --git a/db/retarget.go b/db/retarget.go index 21f745277..31915827a 100644 --- a/db/retarget.go +++ b/db/retarget.go @@ -153,7 +153,11 @@ func (d *DB) RetargetTask(ctx context.Context, taskID int64, oldHost, newBaseURL if n, _ := delRes.RowsAffected(); n > 0 { res.ScopesUpdated += int(n) } - if _, err := tx.ExecContext(ctx, `INSERT INTO task_scope(task_id, kind, domain, source, reason) VALUES ($1, 'subdomain', $2, 'manual', 'retargeted to new instance') ON CONFLICT DO NOTHING`, taskID, newH); err != nil { + if _, err := tx.ExecContext(ctx, ` +INSERT INTO task_scope(task_id, kind, domain, source, reason, expanded, approved_by_operator) +VALUES ($1, 'subdomain', $2, 'manual', 'retargeted to new instance', FALSE, TRUE) +ON CONFLICT (task_id, kind, COALESCE(domain,''), COALESCE(net::text,''), COALESCE(company_id,0), COALESCE(value,'')) +DO UPDATE SET approved_by_operator = TRUE, source = 'manual', expanded = FALSE`, taskID, newH); err != nil { return nil, err } res.ScopesUpdated++ diff --git a/db/schema.sql b/db/schema.sql index c9674482e..2459caa9e 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -778,6 +778,7 @@ CREATE TABLE IF NOT EXISTS task_scope ( created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); ALTER TABLE task_scope ADD COLUMN IF NOT EXISTS expanded BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE task_scope ADD COLUMN IF NOT EXISTS approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE; -- Old database upgrade: expand task scope to match the company scope's single-textbox recognition capability. ALTER TABLE task_scope ADD COLUMN IF NOT EXISTS value TEXT; ALTER TABLE task_scope DROP CONSTRAINT IF EXISTS task_scope_kind_check; diff --git a/db/target_gate_backfill_test.go b/db/target_gate_backfill_test.go index f8df4655a..0a13e03be 100644 --- a/db/target_gate_backfill_test.go +++ b/db/target_gate_backfill_test.go @@ -79,7 +79,7 @@ func TestTargetGateBackfillMigration0022(t *testing.T) { t.Fatalf("mark done: %v", err) } // Remove migration 0022 marker so Open(dsn) re-runs 0022_target_gate_backfill.sql. - if _, err := d.Exec(`DELETE FROM schema_migrations WHERE version = 22`); err != nil { + if _, err := d.Exec(`DELETE FROM schema_migrations WHERE version >= 22`); err != nil { t.Fatalf("delete migration 22 marker: %v", err) } d.Close() diff --git a/db/task_archives_restore.go b/db/task_archives_restore.go index 23dd1be71..aee0e7cbf 100644 --- a/db/task_archives_restore.go +++ b/db/task_archives_restore.go @@ -652,6 +652,9 @@ func restoreTaskScopes(tx *sql.Tx, raw json.RawMessage) ([]string, error) { warnings = append(warnings, fmt.Sprintf("company %d has been deleted; associated scope skipped", companyID)) continue } + if _, ok := row["approved_by_operator"]; !ok { + row["approved_by_operator"] = false + } kept = append(kept, row) } if len(kept) == 0 { diff --git a/db/task_scope.go b/db/task_scope.go index 11d6f8500..9f01dd326 100644 --- a/db/task_scope.go +++ b/db/task_scope.go @@ -24,13 +24,14 @@ type TaskScope struct { CompanyID *int64 `json:"company_id,omitempty"` // CompanyName is resolved for kind=company so callers can label a scope row // without a second lookup. Empty when the row is not a company reference. - CompanyName string `json:"company_name,omitempty"` - Domain string `json:"domain,omitempty"` - Net string `json:"net,omitempty"` - Value string `json:"value,omitempty"` - Source string `json:"source"` - Reason string `json:"reason,omitempty"` - Expanded bool `json:"expanded,omitempty"` + CompanyName string `json:"company_name,omitempty"` + Domain string `json:"domain,omitempty"` + Net string `json:"net,omitempty"` + Value string `json:"value,omitempty"` + Source string `json:"source"` + Reason string `json:"reason,omitempty"` + Expanded bool `json:"expanded,omitempty"` + ApprovedByOperator bool `json:"approved_by_operator"` } // stripHostPort drops a trailing :port from a host:port / ip:port / [ipv6]:port @@ -83,17 +84,33 @@ func (s *AssetStore) upsertTaskScopeResult(ts TaskScope) (bool, error) { src = "auto" } query := ` -INSERT INTO task_scope(task_id, kind, company_id, domain, net, value, source, reason, expanded) -VALUES ($1,$2,$3,$4,$5::cidr,$6,$7,NULLIF($8,''),$9) +INSERT INTO task_scope(task_id, kind, company_id, domain, net, value, source, reason, expanded, approved_by_operator) +VALUES ($1,$2,$3,$4,$5::cidr,$6,$7,NULLIF($8,''),$9,$10) ON CONFLICT DO NOTHING` + if ts.ApprovedByOperator { + // Operator-only path may promote an existing unapproved coverage row to + // approved_by_operator=true (and clear expanded). Agent/auto paths never + // enter this branch and always use ON CONFLICT DO NOTHING with false. + query = ` +INSERT INTO task_scope(task_id, kind, company_id, domain, net, value, source, reason, expanded, approved_by_operator) +VALUES ($1,$2,$3,$4,$5::cidr,$6,$7,NULLIF($8,''),false,true) +ON CONFLICT (task_id, kind, COALESCE(domain,''), COALESCE(net::text,''), COALESCE(company_id,0), COALESCE(value,'')) +DO UPDATE SET approved_by_operator = TRUE, source = 'manual', expanded = FALSE` + } var ( result sql.Result err error ) - if s.tx != nil { - result, err = s.tx.Exec(query, ts.TaskID, ts.Kind, companyVal, domainVal, netVal, valueVal, src, ts.Reason, ts.Expanded) + if ts.ApprovedByOperator { + if s.tx != nil { + result, err = s.tx.Exec(query, ts.TaskID, ts.Kind, companyVal, domainVal, netVal, valueVal, src, ts.Reason) + } else { + result, err = s.db.Exec(query, ts.TaskID, ts.Kind, companyVal, domainVal, netVal, valueVal, src, ts.Reason) + } + } else if s.tx != nil { + result, err = s.tx.Exec(query, ts.TaskID, ts.Kind, companyVal, domainVal, netVal, valueVal, src, ts.Reason, ts.Expanded, false) } else { - result, err = s.db.Exec(query, ts.TaskID, ts.Kind, companyVal, domainVal, netVal, valueVal, src, ts.Reason, ts.Expanded) + result, err = s.db.Exec(query, ts.TaskID, ts.Kind, companyVal, domainVal, netVal, valueVal, src, ts.Reason, ts.Expanded, false) } if err != nil { return false, err @@ -147,15 +164,26 @@ func (s *AssetStore) AddAutoScope(taskID int64, assetType, domain, rawURL, ip st return nil } -// AddAgentScope parses a (kind,value) pair and records it as task scope. -// source is "agent" when called from an LLM tool, "manual" from the UI. -// company: value = company name or id (must already exist). root_domain/subdomain: -// value = a domain. ip/cidr: value = an IP or CIDR (bare IP → /32,/128). +// AddOperatorScope records an operator-approved task_scope row from an +// authenticated operator API/UI path. This is the ONLY scope-addition helper +// that sets approved_by_operator=true (in addition to TaskCreateOptions.CompanyIDs +// at task creation). AddAgentScope and AddAutoScope always leave it false. +func (s *AssetStore) AddOperatorScope(taskID int64, kind, value, reason string) (TaskScope, error) { + return s.addScopeInternal(taskID, kind, value, reason, "manual", true) +} + +// AddAgentScope parses a (kind,value) pair and records it as coverage-only task +// scope (approved_by_operator is ALWAYS false). Call AddOperatorScope from +// operator API/UI handlers when granting operator-approved scope. func (s *AssetStore) AddAgentScope(taskID int64, kind, value, reason, source string) (TaskScope, error) { + return s.addScopeInternal(taskID, kind, value, reason, source, false) +} + +func (s *AssetStore) addScopeInternal(taskID int64, kind, value, reason, source string, approvedByOperator bool) (TaskScope, error) { if source == "" { source = "agent" } - ts := TaskScope{TaskID: taskID, Kind: kind, Source: source, Reason: reason} + ts := TaskScope{TaskID: taskID, Kind: kind, Source: source, Reason: reason, ApprovedByOperator: approvedByOperator} if taskID <= 0 { return ts, fmt.Errorf("task_id is required") } @@ -325,7 +353,8 @@ func (s *AssetStore) DeleteTaskScope(taskID, scopeID int64) (bool, error) { func (s *AssetStore) ListTaskScope(taskID int64) ([]TaskScope, error) { rows, err := s.db.Query(` SELECT ts.id, ts.kind, COALESCE(ts.company_id,0), COALESCE(c.name,''), COALESCE(ts.domain,''), - COALESCE(ts.net::text,''), COALESCE(ts.value,''), ts.source, COALESCE(ts.reason,''), COALESCE(ts.expanded,false) + COALESCE(ts.net::text,''), COALESCE(ts.value,''), ts.source, COALESCE(ts.reason,''), COALESCE(ts.expanded,false), + COALESCE(ts.approved_by_operator,false) FROM task_scope ts LEFT JOIN companies c ON c.id=ts.company_id WHERE ts.task_id=$1 ORDER BY ts.id`, taskID) @@ -337,7 +366,7 @@ WHERE ts.task_id=$1 ORDER BY ts.id`, taskID) for rows.Next() { var t TaskScope var cid int64 - if err := rows.Scan(&t.ID, &t.Kind, &cid, &t.CompanyName, &t.Domain, &t.Net, &t.Value, &t.Source, &t.Reason, &t.Expanded); err != nil { + if err := rows.Scan(&t.ID, &t.Kind, &cid, &t.CompanyName, &t.Domain, &t.Net, &t.Value, &t.Source, &t.Reason, &t.Expanded, &t.ApprovedByOperator); err != nil { return nil, err } t.TaskID = taskID diff --git a/db/task_scope_approval_test.go b/db/task_scope_approval_test.go new file mode 100644 index 000000000..11ad87b42 --- /dev/null +++ b/db/task_scope_approval_test.go @@ -0,0 +1,91 @@ +package db + +import ( + "testing" +) + +// TestTaskScopeOperatorApprovalBackfillMigration0023 verifies that migration +// 0023 backfills approved_by_operator=true ONLY for legacy source='manual' +// rows while leaving source='agent' and source='auto' rows false. +func TestTaskScopeOperatorApprovalBackfillMigration0023(t *testing.T) { + dsn := scratchDSN(t, "ts_approval_0023") + + d, err := Open(dsn) + if err != nil { + t.Fatalf("initial Open: %v", err) + } + coID, _, _, _, _, err := d.Companies().CreateCompanyWithScope("Mig23 Corp", "", []ScopeInput{{Kind: "domain", Value: "mig23.test"}}, "test") + if err != nil { + t.Fatalf("CreateCompanyWithScope: %v", err) + } + task, err := d.CreateTaskWithOptions("mig23-task", "goal", TaskCreateOptions{}) + if err != nil { + t.Fatalf("CreateTaskWithOptions: %v", err) + } + + // Insert legacy pre-0023 rows directly with approved_by_operator=FALSE: + // - manual domain, IP, and company rows -> MUST become TRUE + // - agent domain and IP rows -> MUST stay FALSE + // - auto domain and IP rows -> MUST stay FALSE + stmts := []struct { + sql string + args []any + }{ + {`INSERT INTO task_scope(task_id, kind, domain, source, approved_by_operator) VALUES ($1, 'root_domain', 'manual-legacy.test', 'manual', FALSE)`, []any{task.ID}}, + {`INSERT INTO task_scope(task_id, kind, net, source, approved_by_operator) VALUES ($1, 'ip', '198.51.100.10/32'::cidr, 'manual', FALSE)`, []any{task.ID}}, + {`INSERT INTO task_scope(task_id, kind, company_id, source, approved_by_operator) VALUES ($1, 'company', $2, 'manual', FALSE)`, []any{task.ID, coID}}, + {`INSERT INTO task_scope(task_id, kind, domain, source, approved_by_operator) VALUES ($1, 'root_domain', 'agent-legacy.test', 'agent', FALSE)`, []any{task.ID}}, + {`INSERT INTO task_scope(task_id, kind, net, source, approved_by_operator) VALUES ($1, 'ip', '198.51.100.20/32'::cidr, 'agent', FALSE)`, []any{task.ID}}, + {`INSERT INTO task_scope(task_id, kind, domain, source, approved_by_operator) VALUES ($1, 'root_domain', 'auto-legacy.test', 'auto', FALSE)`, []any{task.ID}}, + {`INSERT INTO task_scope(task_id, kind, net, source, approved_by_operator) VALUES ($1, 'ip', '198.51.100.30/32'::cidr, 'auto', FALSE)`, []any{task.ID}}, + } + for _, st := range stmts { + if _, err := d.Exec(st.sql, st.args...); err != nil { + t.Fatalf("seed legacy row: %v", err) + } + } + if _, err := d.Exec(`DELETE FROM schema_migrations WHERE version >= 23`); err != nil { + t.Fatalf("delete migration 23 marker: %v", err) + } + d.Close() + + // Re-open so migration 0023 executes against the legacy rows. + d2, err := Open(dsn) + if err != nil { + t.Fatalf("re-Open with migration 0023: %v", err) + } + defer d2.Close() + + rows, err := d2.Assets().ListTaskScope(task.ID) + if err != nil { + t.Fatalf("ListTaskScope: %v", err) + } + if len(rows) != 7 { + t.Fatalf("expected 7 task_scope rows, got %d", len(rows)) + } + manualCount, agentCount, autoCount := 0, 0, 0 + for _, r := range rows { + switch r.Source { + case "manual": + manualCount++ + if !r.ApprovedByOperator { + t.Errorf("legacy manual row %+v was not backfilled to approved_by_operator=true", r) + } + case "agent": + agentCount++ + if r.ApprovedByOperator { + t.Errorf("legacy agent row %+v was unexpectedly marked approved_by_operator=true", r) + } + case "auto": + autoCount++ + if r.ApprovedByOperator { + t.Errorf("legacy auto row %+v was unexpectedly marked approved_by_operator=true", r) + } + default: + t.Errorf("unexpected source %q", r.Source) + } + } + if manualCount != 3 || agentCount != 2 || autoCount != 2 { + t.Fatalf("unexpected source counts manual=%d agent=%d auto=%d", manualCount, agentCount, autoCount) + } +} diff --git a/db/tasks.go b/db/tasks.go index bc9bc2651..f5bfa53a7 100644 --- a/db/tasks.go +++ b/db/tasks.go @@ -181,6 +181,10 @@ type TaskCreateOptions struct { // defaults ON for any task with a scope (CompanyIDs or InterceptRules) and // OFF for unscoped tasks; pass an explicit false pointer to opt out. TargetGate *bool + // CompanyScopeByAgent marks CompanyIDs supplied by an LLM orchestration tool + // (spawn_task) rather than an authenticated operator, leaving task_scope + // approved_by_operator=false (coverage-only) to prevent scope drift. + CompanyScopeByAgent bool } // CreateTaskWithOptions creates an exploration, task, direct source relations, @@ -277,7 +281,7 @@ RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, descripti if err := insertTaskRelations(tx, t.ID, opts.SourceTaskIDs); err != nil { return nil, err } - if err := insertTaskCompanies(tx, t.ID, opts.CompanyIDs); err != nil { + if err := insertTaskCompanies(tx, t.ID, opts.CompanyIDs, !opts.CompanyScopeByAgent); err != nil { return nil, err } if err := insertTaskLLMProfiles(tx, t.ID, opts.LLMProfileIDs); err != nil { @@ -294,7 +298,7 @@ RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, descripti return t, tx.Commit() } -func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64) error { +func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64, approvedByOperator bool) error { if len(companyIDs) == 0 { return nil } @@ -303,20 +307,24 @@ func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64) error { if err := lockCompanyScopeMutation(tx); err != nil { return err } + src := "manual" + if !approvedByOperator { + src = "agent" + } var inserted int err := tx.QueryRow(` WITH requested(company_id, position) AS ( SELECT company_id, position FROM unnest($2::bigint[]) WITH ORDINALITY AS requested(company_id, position) ), inserted AS ( - INSERT INTO task_scope(task_id, kind, company_id, source, reason) - SELECT $1, 'company', companies.id, 'manual', 'associated with company at task creation' + INSERT INTO task_scope(task_id, kind, company_id, source, reason, approved_by_operator) + SELECT $1, 'company', companies.id, $3, 'associated with company at task creation', $4 FROM requested JOIN companies ON companies.id=requested.company_id ORDER BY requested.position RETURNING company_id ) -SELECT count(*) FROM inserted`, taskID, companyIDs).Scan(&inserted) +SELECT count(*) FROM inserted`, taskID, companyIDs, src, approvedByOperator).Scan(&inserted) if err != nil { return err } diff --git a/docker-compose.sandbox.yml b/docker-compose.sandbox.yml new file mode 100644 index 000000000..84ae90f8e --- /dev/null +++ b/docker-compose.sandbox.yml @@ -0,0 +1,73 @@ +# ARTEX Sandbox MVP overlay (CONTRACT.md §§1-6). +# Usage: +# docker compose -f docker-compose.yml -f docker-compose.sandbox.yml build +# docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d +# +# Security boundary: +# - artex (panel): holds DB credentials, keys, LLM keys; never mounts docker.sock; +# routes every agent execution to artex-runner over internal runner-net. +# - artex-runner: ONLY service mounting /var/run/docker.sock; listens on :8789 on +# runner-net only; requires Authorization: Bearer $ARTEX_RUNNER_TOKEN. +# - artex-worker / artex-egress-proxy: built via compose, instantiated per task by +# artex-runner on an isolated internal: true network artex-task-. +services: + artex: + networks: + - default + - runner-net + depends_on: + artex-runner: + condition: service_healthy + environment: + ARTEX_SANDBOX: ${ARTEX_SANDBOX:-required} + ARTEX_RUNNER_URL: ${ARTEX_RUNNER_URL:-http://artex-runner:8789} + ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env} + + artex-runner: + build: + context: . + dockerfile: Dockerfile.runner + image: artex-runner:local + networks: + - runner-net + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ./data/tasks:/app/data/tasks + - ./data/egress-audit:/app/data/egress-audit + environment: + ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env} + ARTEX_WORKER_IMAGE: ${ARTEX_WORKER_IMAGE:-artex-worker:local} + ARTEX_EGRESS_PROXY_IMAGE: ${ARTEX_EGRESS_PROXY_IMAGE:-artex-egress-proxy:local} + ARTEX_WORKSPACE_ROOT: /app/data/tasks + ARTEX_HOST_WORKSPACE_ROOT: ${ARTEX_HOST_WORKSPACE_ROOT:-./data/tasks} + ARTEX_AUDIT_ROOT: /app/data/egress-audit + ARTEX_HOST_AUDIT_ROOT: ${ARTEX_HOST_AUDIT_ROOT:-./data/egress-audit} + ARTEX_TASK_NET_PREFIX: ${ARTEX_TASK_NET_PREFIX:-artex-task-} + ARTEX_EGRESS_NET: ${ARTEX_EGRESS_NET:-egress-net} + healthcheck: + test: ["CMD-SHELL", "curl -fsS -H \"Authorization: Bearer $$ARTEX_RUNNER_TOKEN\" http://127.0.0.1:8789/v1/health"] + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped + + artex-worker: + build: + context: . + dockerfile: Dockerfile.worker + image: artex-worker:local + profiles: ["build-only"] + + artex-egress-proxy: + build: + context: . + dockerfile: Dockerfile.egress-proxy + image: artex-egress-proxy:local + profiles: ["build-only"] + +networks: + runner-net: + internal: true + egress-net: + name: ${ARTEX_EGRESS_NET:-egress-net} + driver: bridge diff --git a/docs/SANDBOX.md b/docs/SANDBOX.md new file mode 100644 index 000000000..b13208619 --- /dev/null +++ b/docs/SANDBOX.md @@ -0,0 +1,82 @@ +# ARTEX Sandbox MVP (`docker-compose.sandbox.yml`) + +The sandbox overlay separates the privileged **panel** (`artex`, holding +PostgreSQL credentials, `jwt.key`, `secret.key`, `config.json`, and LLM keys) +from disposable per-task **worker** containers (`artex-worker:local`). + +## Components + +1. **`artex` (panel)**: API, UI, DB-only tools (`report_finding`, `insert_assets`, + `record_fact`). Never mounts `/var/run/docker.sock` and never executes agent + commands locally when `ARTEX_SANDBOX=required` (default). +2. **`artex-runner` (`:8789` on internal `runner-net`)**: The **only** service + mounting `/var/run/docker.sock`. Requires `Authorization: Bearer $ARTEX_RUNNER_TOKEN` + on every endpoint including `GET /v1/health`. Creates and tracks one worker + + one egress proxy per task by Docker label (`artex.task=`). +3. **`artex-worker-` (`artex-worker:local`)**: Runs as `10001:10001`, + `--read-only`, `--cap-drop ALL`, `--security-opt no-new-privileges:true`, + `--pids-limit 512`, `--memory 2g`, `--cpus 2`, bounded `tmpfs` on `/tmp` and + `/home/exec`, mounted **only** with `/app/data/tasks/:/workspace:rw`, and + attached **only** to the per-task `internal: true` network `artex-task-`. +4. **`artex-egress-` (`artex-egress-proxy:local`)**: Attached to + `artex-task-` and `egress-net`. Enforces the task's domain suffix and CIDR + allowlists (deny by default, blocking RFC1918, loopback, link-local, metadata + endpoints `169.254.169.254`, `fd00:ec2::254`, `168.63.129.16`, `100.100.100.200`, + and IPv6 unless explicitly in `ARTEX_SCOPE_CIDRS`) on both HTTP/HTTPS CONNECT + (`:3128`) and SOCKS5 (`:1080`) with DNS pinning (no rebinding window). Logs + one JSON line per connection to `/app/data/egress-audit//egress.jsonl` and stdout. + +## Running with the sandbox + +```bash +export ARTEX_RUNNER_TOKEN="$(openssl rand -hex 32)" +docker compose -f docker-compose.yml -f docker-compose.sandbox.yml --profile build-only build +docker compose -f docker-compose.yml -f docker-compose.sandbox.yml build +docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d +``` + +## Breaking change: `ARTEX_SANDBOX=required` by default + +Starting with this release, `ARTEX_SANDBOX` defaults to **`required`**. If +`artex-runner` is unavailable, ARTEX refuses to start new tasks and pauses +running tasks rather than falling back to local execution on the panel. + +To opt out explicitly in development (degraded mode — logs a prominent startup +warning banner and records `sandbox=off` in every task event log): + +```bash +ARTEX_SANDBOX=off +``` + +## Security Hardening Notes + +- **Tamper-proof egress audit log**: `artex-egress-` writes JSONL connection logs to a proxy-only bind mount (`/app/data/egress-audit//egress.jsonl`, mounted at `/audit:rw` inside the proxy) and stdout. The worker container only mounts `/app/data/tasks/:/workspace:rw` and cannot read, truncate, or forge the egress audit log. +- **Kernel-backed kill-switch (no agent-writable state)**: `artex-worker-` runs `/usr/local/bin/artex-exec-wrap --init` as PID 1 (reaping all orphaned children). On `POST /v1/tasks/{id}/kill`, `artex-runner` executes `/usr/local/bin/artex-exec-wrap --kill-uid 10001` as uid `10001` (preserving `--cap-drop ALL`) scanning `/proc` directly (defeating `setsid`, `nohup`, nested double-forked daemons, `trap '' TERM`, 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. +- **Browser & `WebFetch` containment**: In `ARTEX_SANDBOX=required` mode, local stdio MCP servers (including the default private browser MCP) are skipped on the panel; `WebFetch` enforces the task's `sandbox.EgressPolicy` on every URL, redirect hop, and pinned dial (with direct retry disabled); and the opt-in panel-hosted shared browser MCP is only attached when `target_gate` is enabled or an explicit egress proxy is configured, with every browser navigation URL gated against the task's `sandbox.EgressPolicy` (execution containment + scope-gated panel fetch/browser; full subresource browser network isolation requires running the shared browser behind `egress-guard` in `EGRESS_MODE=enforce`). + +- **No scope drift (`approved_by_operator`)**: Only operator-approved `task_scope` rows (`approved_by_operator = true`, set exclusively via the operator API/UI or `TaskCreateOptions.CompanyIDs`) and operator `task_intercept_rules` grant sandbox egress to Bash, `WebFetch`, and the shared browser. Agent-added (`add_task_scope`), auto-added (`insert_assets`), and expanded rows are coverage-only (`approved_by_operator = false`). Tasks with no approved scope deny all egress by default. + +### Operator Scope Writers & Archive Restore Semantics + +| Write path | Sets `approved_by_operator` | Notes | +|---|---|---| +| `POST /api/tasks` (`TaskCreateOptions.CompanyIDs`, operator API) | `true` | Operator-selected companies at task creation | +| `POST /api/tasks/{id}/scope` (`AddOperatorScope`) | `true` | Operator API/UI; promotes existing unapproved coverage row if present | +| `POST /api/tasks/{id}/retarget` (`db.RetargetTask`) | `true` | Operator retarget to a newly provisioned target host | +| `add_task_scope` (`AddAgentScope`) | `false` | Agent coverage-only (even if `source="manual"` is passed) | +| `insert_assets` (`AddAutoScope`) | `false` | Auto-discovered coverage-only | +| `spawn_task` (`CompanyScopeByAgent: true`) | `false` | Agent-spawned subtask company links require operator approval before granting sandbox egress | +| Archive restore (`restoreTaskScopes`) | preserved (`false` if absent) | Post-0023 archives preserve `approved_by_operator`; legacy pre-0023 archives default to `false` (fail-closed — operators must re-approve scope rows before sandbox egress is granted) | + +### Target-Gate Approval vs. Worker Egress (MVP Behavior) + +In `ARTEX_SANDBOX=required` mode, **target-gate approval only clears the tool-call approval gate; worker egress (as well as sandbox `WebFetch` and shared-browser navigation) still requires an operator-approved Task Scope entry (`POST /api/tasks/{id}/scope`) or a task allow rule.** + +This behavior is surfaced explicitly rather than failing silently: +- Approving a pending target-gate request via `POST /api/intercept/pending/{id}/decide` or `POST /api/intercept/pending/batch-decide` includes `sandbox_egress_note` in the JSON response when `ARTEX_SANDBOX=required`. +- Every sandbox egress denial from the per-task proxy (`HTTP 403`), `WebFetch`, and the shared browser states verbatim that target-gate approval only clears the tool gate and directs the operator to approve the target in Task Scope. + +### Upgrade Notes (Migration `0023`) + +- Migration `0023_task_scope_operator_approval.sql` adds `task_scope.approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE` and backfills `approved_by_operator = TRUE` for all existing `source = 'manual'` rows so upgraded operator-scoped tasks retain sandbox egress immediately. +- Goal-derived/agent scopes (`source = 'agent'`, created via `add_task_scope`) and auto-discovered scopes (`source = 'auto'`, created via `insert_assets`) remain `approved_by_operator = FALSE` (coverage-only) and **must be re-approved once via the Task Scope UI (`POST /api/tasks/{id}/scope`)** if sandbox egress is required for those hosts. diff --git a/sandbox/client.go b/sandbox/client.go new file mode 100644 index 000000000..42593b82b --- /dev/null +++ b/sandbox/client.go @@ -0,0 +1,129 @@ +package sandbox + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +// Client is the panel-side HTTP client for artex-runner. +type Client struct { + baseURL string + token string + http *http.Client +} + +// NewClient constructs a runner client. Ambient HTTP_PROXY is explicitly disabled +// (Proxy: nil) so panel->runner calls on runner-net are never proxied. +func NewClient(baseURL, token string) *Client { + tr := &http.Transport{ + Proxy: nil, + MaxIdleConns: 16, + IdleConnTimeout: 60 * time.Second, + ResponseHeaderTimeout: 0, // exec calls can run up to MaxTimeoutMS + } + return &Client{ + baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"), + token: strings.TrimSpace(token), + http: &http.Client{Transport: tr}, + } +} + +func (c *Client) doJSON(ctx context.Context, method, path string, reqBody, out any) error { + if c == nil || c.baseURL == "" { + return fmt.Errorf("%w: runner URL is empty", ErrRunnerUnavailable) + } + var body io.Reader + if reqBody != nil { + raw, err := json.Marshal(reqBody) + if err != nil { + return err + } + body = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body) + if err != nil { + return err + } + if reqBody != nil { + req.Header.Set("Content-Type", "application/json") + } + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + resp, err := c.http.Do(req) + if err != nil { + return fmt.Errorf("%w: %v", ErrRunnerUnavailable, err) + } + defer resp.Body.Close() + + // Cap error/JSON reads to 4 MiB (ExecResponse carries <= 2 MiB of stdout+stderr + JSON overhead). + respRaw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if err != nil { + return fmt.Errorf("%w: read response: %v", ErrRunnerUnavailable, err) + } + if resp.StatusCode >= 400 { + msg := strings.TrimSpace(string(respRaw)) + switch resp.StatusCode { + case http.StatusBadRequest: + return fmt.Errorf("%w: %s", ErrBadRequest, msg) + case http.StatusUnauthorized: + return fmt.Errorf("%w: %s", ErrUnauthorized, msg) + case http.StatusNotFound: + return fmt.Errorf("%w: %s", ErrNotFound, msg) + case http.StatusConflict: + return fmt.Errorf("%w: %s", ErrDockerUnavailable, msg) + default: + return fmt.Errorf("%w: HTTP %d: %s", ErrRunnerUnavailable, resp.StatusCode, msg) + } + } + if out != nil && len(respRaw) > 0 { + if err := json.Unmarshal(respRaw, out); err != nil { + return fmt.Errorf("decode runner response: %w", err) + } + } + return nil +} + +// Health calls GET /v1/health. +func (c *Client) Health(ctx context.Context) (HealthResponse, error) { + var out HealthResponse + err := c.doJSON(ctx, http.MethodGet, "/v1/health", nil, &out) + return out, err +} + +// Exec calls POST /v1/tasks/{id}/exec. +func (c *Client) Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) { + if err := ValidateTaskID(taskID); err != nil { + return ExecResponse{}, err + } + var out ExecResponse + err := c.doJSON(ctx, http.MethodPost, "/v1/tasks/"+url.PathEscape(taskID)+"/exec", req, &out) + return out, err +} + +// Kill calls POST /v1/tasks/{id}/kill. +func (c *Client) Kill(ctx context.Context, taskID string) (KillResponse, error) { + if err := ValidateTaskID(taskID); err != nil { + return KillResponse{}, err + } + var out KillResponse + err := c.doJSON(ctx, http.MethodPost, "/v1/tasks/"+url.PathEscape(taskID)+"/kill", nil, &out) + return out, err +} + +// Delete calls DELETE /v1/tasks/{id}. +func (c *Client) Delete(ctx context.Context, taskID string) (DeleteResponse, error) { + if err := ValidateTaskID(taskID); err != nil { + return DeleteResponse{}, err + } + var out DeleteResponse + err := c.doJSON(ctx, http.MethodDelete, "/v1/tasks/"+url.PathEscape(taskID), nil, &out) + return out, err +} diff --git a/sandbox/docker.go b/sandbox/docker.go new file mode 100644 index 000000000..6c06dcf24 --- /dev/null +++ b/sandbox/docker.go @@ -0,0 +1,793 @@ +package sandbox + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + "time" +) + +// DockerConfig configures the DockerBackend for artex-runner. +type DockerConfig struct { + SocketPath string // default /var/run/docker.sock + WorkerImage string // default artex-worker:local + ProxyImage string // default artex-egress-proxy:local + WorkspaceRoot string // panel/runner path, default /app/data/tasks + HostWorkspaceRoot string // host path used in Docker bind mounts (defaults to WorkspaceRoot) + AuditRoot string // proxy-only egress audit log dir (never mounted into worker) + HostAuditRoot string // host path used in Docker bind mounts for AuditRoot + TaskNetPrefix string // default artex-task- + EgressNet string // default egress-net +} + +type taskContainers struct { + taskID string + workerID string + proxyID string + netName string + scopeHash string +} + +// DockerBackend implements Backend using Docker Engine's Unix socket REST API. +type DockerBackend struct { + cfg DockerConfig + http *http.Client + mu sync.Mutex + tasks map[string]*taskContainers +} + +// NewDockerBackend creates a DockerBackend talking to cfg.SocketPath. +func NewDockerBackend(cfg DockerConfig) *DockerBackend { + if cfg.SocketPath == "" { + cfg.SocketPath = "/var/run/docker.sock" + } + if cfg.WorkerImage == "" { + cfg.WorkerImage = DefaultWorkerImage + } + if cfg.ProxyImage == "" { + cfg.ProxyImage = DefaultProxyImage + } + if cfg.WorkspaceRoot == "" { + cfg.WorkspaceRoot = DefaultWorkspaceRoot + } + if cfg.HostWorkspaceRoot == "" { + cfg.HostWorkspaceRoot = cfg.WorkspaceRoot + } + if cfg.AuditRoot == "" { + cfg.AuditRoot = DefaultAuditRoot + } + if cfg.HostAuditRoot == "" { + cfg.HostAuditRoot = cfg.AuditRoot + } + if cfg.TaskNetPrefix == "" { + cfg.TaskNetPrefix = DefaultTaskNetPrefix + } + if cfg.EgressNet == "" { + cfg.EgressNet = DefaultEgressNet + } + sock := cfg.SocketPath + tr := &http.Transport{ + Proxy: nil, + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", sock) + }, + } + return &DockerBackend{ + cfg: cfg, + http: &http.Client{Transport: tr}, + tasks: map[string]*taskContainers{}, + } +} + +func (b *DockerBackend) dockerDo(ctx context.Context, method, path string, body any) (*http.Response, error) { + var r io.Reader + if body != nil { + raw, err := json.Marshal(body) + if err != nil { + return nil, err + } + r = bytes.NewReader(raw) + } + req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, r) + if err != nil { + return nil, err + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := b.http.Do(req) + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrDockerUnavailable, err) + } + return resp, nil +} + +// Ping verifies the Docker daemon is reachable. +func (b *DockerBackend) Ping(ctx context.Context) error { + resp, err := b.dockerDo(ctx, http.MethodGet, "/_ping", nil) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + return fmt.Errorf("%w: ping HTTP %d", ErrDockerUnavailable, resp.StatusCode) + } + return nil +} + +// WorkerCount returns the number of tracked task workers. +func (b *DockerBackend) WorkerCount() int { + b.mu.Lock() + defer b.mu.Unlock() + return len(b.tasks) +} + +// Recover discovers existing runner-created containers by label on startup. +// It strictly filters by artex.managed_by=artex-runner so it never adopts foreign containers. +func (b *DockerBackend) Recover(ctx context.Context) (int, error) { + filters, _ := json.Marshal(map[string][]string{ + "label": {LabelManagedBy + "=" + ManagedByRunner}, + }) + resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/json?all=true&filters="+url.QueryEscape(string(filters)), nil) + if err != nil { + return 0, err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return 0, fmt.Errorf("%w: list containers HTTP %d: %s", ErrDockerUnavailable, resp.StatusCode, string(raw)) + } + var list []struct { + ID string `json:"Id"` + Labels map[string]string `json:"Labels"` + State string `json:"State"` + } + if err := json.NewDecoder(resp.Body).Decode(&list); err != nil { + return 0, err + } + b.mu.Lock() + defer b.mu.Unlock() + for _, c := range list { + if c.Labels[LabelManagedBy] != ManagedByRunner { + continue + } + tid := c.Labels[LabelTask] + if ValidateTaskID(tid) != nil { + continue + } + tc := b.tasks[tid] + if tc == nil { + tc = &taskContainers{taskID: tid, netName: b.cfg.TaskNetPrefix + tid} + b.tasks[tid] = tc + } + switch c.Labels[LabelComponent] { + case ComponentWorker: + tc.workerID = c.ID + case ComponentProxy: + tc.proxyID = c.ID + } + } + return len(b.tasks), nil +} + +func (b *DockerBackend) ensureNetwork(ctx context.Context, name string, internal bool, taskID string) error { + resp, err := b.dockerDo(ctx, http.MethodGet, "/networks/"+url.PathEscape(name), nil) + if err != nil { + return err + } + if resp.StatusCode == http.StatusOK { + var existing struct { + Internal bool `json:"Internal"` + Labels map[string]string `json:"Labels"` + } + derr := json.NewDecoder(resp.Body).Decode(&existing) + resp.Body.Close() + if derr != nil { + return fmt.Errorf("inspect existing network %s: %w", name, derr) + } + if internal && !existing.Internal { + return fmt.Errorf("existing network %s is not internal=true (refusing to attach worker)", name) + } + if taskID != "" { + if existing.Labels[LabelManagedBy] != ManagedByRunner || existing.Labels[LabelTask] != taskID { + return fmt.Errorf("existing task network %s has untrusted labels %v (refusing to attach worker)", name, existing.Labels) + } + } + return nil + } + resp.Body.Close() + labels := map[string]string{LabelManagedBy: ManagedByRunner} + if taskID != "" { + labels[LabelTask] = taskID + } + payload := map[string]any{ + "Name": name, + "CheckDuplicate": true, + "Driver": "bridge", + "Internal": internal, + "Labels": labels, + } + cresp, err := b.dockerDo(ctx, http.MethodPost, "/networks/create", payload) + if err != nil { + return err + } + defer cresp.Body.Close() + if cresp.StatusCode >= 300 && cresp.StatusCode != http.StatusConflict { + raw, _ := io.ReadAll(io.LimitReader(cresp.Body, 4096)) + return fmt.Errorf("create network %s: HTTP %d: %s", name, cresp.StatusCode, string(raw)) + } + return nil +} + +func (b *DockerBackend) connectNetwork(ctx context.Context, netName, containerID string) error { + resp, err := b.dockerDo(ctx, http.MethodPost, "/networks/"+url.PathEscape(netName)+"/connect", map[string]any{ + "Container": containerID, + }) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + if strings.Contains(string(raw), "already exists") { + return nil + } + return fmt.Errorf("connect %s to %s: HTTP %d: %s", containerID, netName, resp.StatusCode, string(raw)) + } + return nil +} + +func (b *DockerBackend) removeNetwork(ctx context.Context, name string) { + resp, err := b.dockerDo(ctx, http.MethodDelete, "/networks/"+url.PathEscape(name), nil) + if err == nil { + resp.Body.Close() + } +} + +func (b *DockerBackend) removeContainer(ctx context.Context, idOrName string) { + if idOrName == "" { + return + } + resp, err := b.dockerDo(ctx, http.MethodDelete, "/containers/"+url.PathEscape(idOrName)+"?force=true&v=true", nil) + if err == nil { + resp.Body.Close() + } +} + +func (b *DockerBackend) startContainer(ctx context.Context, id string) error { + resp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(id)+"/start", nil) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 && resp.StatusCode != http.StatusNotModified { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("start container %s: HTTP %d: %s", id, resp.StatusCode, string(raw)) + } + return nil +} + +func (b *DockerBackend) createContainer(ctx context.Context, name string, spec map[string]any) (string, error) { + resp, err := b.dockerDo(ctx, http.MethodPost, "/containers/create?name="+url.QueryEscape(name), spec) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return "", fmt.Errorf("create container %s: HTTP %d: %s", name, resp.StatusCode, string(raw)) + } + var out struct { + ID string `json:"Id"` + } + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + return "", err + } + return out.ID, nil +} + +func (b *DockerBackend) resolveHostWorkspaceRoot(ctx context.Context) string { + if filepath.IsAbs(b.cfg.HostWorkspaceRoot) && b.cfg.HostWorkspaceRoot != b.cfg.WorkspaceRoot { + return b.cfg.HostWorkspaceRoot + } + // When running inside Docker (artex-runner container), inspect our own container + // mounts via the Docker API to discover the exact host path backing WorkspaceRoot. + hostname, err := os.Hostname() + if err == nil && hostname != "" { + resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+url.PathEscape(hostname)+"/json", nil) + if err == nil { + defer resp.Body.Close() + if resp.StatusCode == http.StatusOK { + var info struct { + Mounts []struct { + Source string `json:"Source"` + Destination string `json:"Destination"` + } `json:"Mounts"` + } + if json.NewDecoder(resp.Body).Decode(&info) == nil { + cleanWS := filepath.Clean(b.cfg.WorkspaceRoot) + for _, m := range info.Mounts { + if filepath.Clean(m.Destination) == cleanWS && m.Source != "" { + b.cfg.HostWorkspaceRoot = m.Source + return m.Source + } + } + } + } + } + } + if abs, err := filepath.Abs(b.cfg.HostWorkspaceRoot); err == nil { + return abs + } + return b.cfg.HostWorkspaceRoot +} + +func (b *DockerBackend) resolveHostAuditRoot(ctx context.Context) string { + if filepath.IsAbs(b.cfg.HostAuditRoot) && b.cfg.HostAuditRoot != b.cfg.AuditRoot { + return b.cfg.HostAuditRoot + } + hostname, err := os.Hostname() + if err == nil && hostname != "" { + resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+url.PathEscape(hostname)+"/json", nil) + if err == nil { + defer resp.Body.Close() + if resp.StatusCode == http.StatusOK { + var info struct { + Mounts []struct { + Source string `json:"Source"` + Destination string `json:"Destination"` + } `json:"Mounts"` + } + if json.NewDecoder(resp.Body).Decode(&info) == nil { + cleanAudit := filepath.Clean(b.cfg.AuditRoot) + for _, m := range info.Mounts { + if filepath.Clean(m.Destination) == cleanAudit && m.Source != "" { + b.cfg.HostAuditRoot = m.Source + return m.Source + } + } + } + } + } + } + if abs, err := filepath.Abs(b.cfg.HostAuditRoot); err == nil { + return abs + } + return b.cfg.HostAuditRoot +} + +func (b *DockerBackend) hostTaskDir(ctx context.Context, taskID string) string { + return filepath.Join(b.resolveHostWorkspaceRoot(ctx), taskID) +} + +func (b *DockerBackend) localTaskDir(taskID string) string { + return filepath.Join(b.cfg.WorkspaceRoot, taskID) +} + +func (b *DockerBackend) hostAuditDir(ctx context.Context, taskID string) string { + return filepath.Join(b.resolveHostAuditRoot(ctx), taskID) +} + +func (b *DockerBackend) localAuditDir(taskID string) string { + return filepath.Join(b.cfg.AuditRoot, taskID) +} + +func scopeFingerprint(domains, cidrs []string) string { + d := append([]string(nil), domains...) + c := append([]string(nil), cidrs...) + sort.Strings(d) + sort.Strings(c) + return strings.Join(d, ",") + "|" + strings.Join(c, ",") +} + +func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*taskContainers, error) { + b.mu.Lock() + tc := b.tasks[taskID] + b.mu.Unlock() + + netName := b.cfg.TaskNetPrefix + taskID + proxyName := "artex-egress-" + taskID + workerName := "artex-worker-" + taskID + sh := scopeFingerprint(scopeDomains, scopeCIDRs) + + if tc != nil && tc.scopeHash == sh { + proxyOK := tc.proxyID != "" && b.startContainer(ctx, tc.proxyID) == nil + if !proxyOK && tc.proxyID != "" { + b.removeContainer(ctx, tc.proxyID) + tc.proxyID = "" + } + workerOK := tc.workerID != "" && b.startContainer(ctx, tc.workerID) == nil + if !workerOK && tc.workerID != "" { + b.removeContainer(ctx, tc.workerID) + tc.workerID = "" + } + if proxyOK && workerOK { + return tc, nil + } + } + + // Prepare per-task workspace directory (owned by 10001:10001 when running as root) + // and separate proxy-only audit directory (NEVER mounted into the worker). + localDir := b.localTaskDir(taskID) + if err := os.MkdirAll(localDir, 0o775); err != nil { + log.Printf("[runner] mkdir %s: %v", localDir, err) + } else { + _ = os.Chown(localDir, WorkerUID, WorkerGID) + } + localAudit := b.localAuditDir(taskID) + if err := os.MkdirAll(localAudit, 0o775); err != nil { + log.Printf("[runner] mkdir audit %s: %v", localAudit, err) + } else { + _ = os.Chown(localAudit, WorkerUID, WorkerGID) + } + + // Ensure per-task internal network (no direct egress) and shared egress-net for the proxy. + if err := b.ensureNetwork(ctx, netName, true, taskID); err != nil { + return nil, err + } + if err := b.ensureNetwork(ctx, b.cfg.EgressNet, false, ""); err != nil { + return nil, err + } + + // Recreate proxy if missing or scope changed. + if tc == nil || tc.proxyID == "" || tc.scopeHash != sh { + b.removeContainer(ctx, proxyName) + proxySpec := map[string]any{ + "Image": b.cfg.ProxyImage, + "User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID), + "Env": []string{ + "ARTEX_TASK_ID=" + taskID, + "ARTEX_SCOPE_DOMAINS=" + strings.Join(scopeDomains, ","), + "ARTEX_SCOPE_CIDRS=" + strings.Join(scopeCIDRs, ","), + fmt.Sprintf("ARTEX_PROXY_PORT=%d", DefaultProxyPort), + fmt.Sprintf("ARTEX_SOCKS_PORT=%d", DefaultSocksPort), + "ARTEX_EGRESS_LOG_PATH=/audit/egress.jsonl", + }, + "Labels": map[string]string{ + LabelTask: taskID, + LabelComponent: ComponentProxy, + LabelManagedBy: ManagedByRunner, + }, + "HostConfig": map[string]any{ + "ReadonlyRootfs": true, + "CapDrop": []string{"ALL"}, + "SecurityOpt": []string{"no-new-privileges:true"}, + "PidsLimit": int64(128), + "Memory": int64(256 << 20), + "NanoCpus": int64(500_000_000), + "NetworkMode": netName, + "Binds": []string{b.hostAuditDir(ctx, taskID) + ":/audit:rw"}, + }, + } + pid, err := b.createContainer(ctx, proxyName, proxySpec) + if err != nil { + return nil, err + } + if err := b.connectNetwork(ctx, b.cfg.EgressNet, pid); err != nil { + b.removeContainer(ctx, pid) + return nil, err + } + if err := b.startContainer(ctx, pid); err != nil { + b.removeContainer(ctx, pid) + return nil, err + } + if tc == nil { + tc = &taskContainers{taskID: taskID, netName: netName} + } + tc.proxyID = pid + tc.scopeHash = sh + } + + // Create worker container strictly matching CONTRACT.md §4. + if tc.workerID == "" { + b.removeContainer(ctx, workerName) + proxyURL := fmt.Sprintf("http://%s:%d", proxyName, DefaultProxyPort) + socksURL := fmt.Sprintf("socks5h://%s:%d", proxyName, DefaultSocksPort) + workerSpec := map[string]any{ + "Image": b.cfg.WorkerImage, + "Cmd": []string{"/usr/local/bin/artex-exec-wrap", "--init"}, + "User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID), + "WorkingDir": "/workspace", + "Env": []string{ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "HOME=/home/exec", + "LANG=C.UTF-8", + "TERM=xterm", + "HTTP_PROXY=" + proxyURL, + "HTTPS_PROXY=" + proxyURL, + "ALL_PROXY=" + socksURL, + "NO_PROXY=localhost,127.0.0.1", + "http_proxy=" + proxyURL, + "https_proxy=" + proxyURL, + "all_proxy=" + socksURL, + "no_proxy=localhost,127.0.0.1", + }, + "Labels": map[string]string{ + LabelTask: taskID, + LabelComponent: ComponentWorker, + LabelManagedBy: ManagedByRunner, + }, + "HostConfig": map[string]any{ + "ReadonlyRootfs": true, + "CapDrop": []string{"ALL"}, + "SecurityOpt": []string{"no-new-privileges:true"}, + "PidsLimit": int64(512), + "Memory": int64(2 << 30), + "NanoCpus": int64(2_000_000_000), + "Tmpfs": map[string]string{ + "/tmp": "rw,noexec,nosuid,size=512m", + "/home/exec": fmt.Sprintf("rw,nosuid,size=128m,uid=%d,gid=%d,mode=0700", WorkerUID, WorkerGID), + }, + "Binds": []string{b.hostTaskDir(ctx, taskID) + ":/workspace:rw"}, + "NetworkMode": netName, + }, + } + wid, err := b.createContainer(ctx, workerName, workerSpec) + if err != nil { + return nil, err + } + if err := b.startContainer(ctx, wid); err != nil { + b.removeContainer(ctx, wid) + return nil, err + } + tc.workerID = wid + } + + b.mu.Lock() + b.tasks[taskID] = tc + b.mu.Unlock() + return tc, nil +} + +// Exec runs req.Argv directly inside the task's worker container via /usr/local/bin/artex-exec-wrap +// (zero shell interpolation, isolated process group, SIGTERM -> 5s -> SIGKILL on timeout). +func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) { + start := time.Now() + tc, err := b.ensureTask(ctx, taskID, req.ScopeDomains, req.ScopeCIDRs) + if err != nil { + return ExecResponse{}, err + } + + // Wrap argv with artex-exec-wrap so every exec gets its own process group, + // enforces timeout_ms (SIGTERM group -> 5s -> SIGKILL -> exit 124) without + // relying on any agent-writable state. + wrappedArgv := make([]string, 0, len(req.Argv)+4) + wrappedArgv = append(wrappedArgv, + "/usr/local/bin/artex-exec-wrap", + strconv.Itoa(req.TimeoutMS), + "--", + ) + wrappedArgv = append(wrappedArgv, req.Argv...) + + envList := make([]string, 0, len(req.Env)) + for k, v := range req.Env { + envList = append(envList, k+"="+v) + } + sort.Strings(envList) + + createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(tc.workerID)+"/exec", map[string]any{ + "AttachStdout": true, + "AttachStderr": true, + "Tty": false, + "User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID), + "WorkingDir": req.Workdir, + "Env": envList, + "Cmd": wrappedArgv, + }) + if err != nil { + return ExecResponse{}, err + } + defer createResp.Body.Close() + if createResp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(createResp.Body, 4096)) + return ExecResponse{}, fmt.Errorf("create exec: HTTP %d: %s", createResp.StatusCode, string(raw)) + } + var created struct { + ID string `json:"Id"` + } + if err := json.NewDecoder(createResp.Body).Decode(&created); err != nil { + return ExecResponse{}, err + } + + // Give the HTTP start stream a small buffer over timeout_ms (5s SIGKILL grace + 5s slack). + execCtx, cancel := context.WithTimeout(ctx, time.Duration(req.TimeoutMS)*time.Millisecond+12*time.Second) + defer cancel() + + startResp, err := b.dockerDo(execCtx, http.MethodPost, "/exec/"+url.PathEscape(created.ID)+"/start", map[string]any{ + "Detach": false, + "Tty": false, + }) + if err != nil { + if ctx.Err() != nil { + _ = b.Kill(context.Background(), taskID) + } + return ExecResponse{}, err + } + defer startResp.Body.Close() + + stdout, stderr, truncated, _ := demuxDockerStream(startResp.Body, MaxOutputBytes) + + inspectResp, err := b.dockerDo(context.Background(), http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil) + exitCode := -1 + if err == nil { + defer inspectResp.Body.Close() + var ins struct { + ExitCode int `json:"ExitCode"` + } + if json.NewDecoder(inspectResp.Body).Decode(&ins) == nil { + exitCode = ins.ExitCode + } + } + + timedOut := exitCode == 124 + return ExecResponse{ + ExitCode: exitCode, + Stdout: stdout, + Stderr: stderr, + Truncated: truncated, + TimedOut: timedOut, + DurationMS: time.Since(start).Milliseconds(), + }, nil +} + +// Kill terminates EVERY uid-10001 process inside the task's worker container +// (excluding PID 1) by running a root exec scanning /proc directly — never +// trusting any agent-writable state. If root exec fails or reports surviving +// processes, Kill falls back to force-removing the worker container so no +// process can ever survive Pause/Stop (preserving /workspace for the next exec). +func (b *DockerBackend) Kill(ctx context.Context, taskID string) error { + b.mu.Lock() + tc := b.tasks[taskID] + b.mu.Unlock() + if tc == nil || tc.workerID == "" { + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + workerID := tc.workerID + + if err := b.killWorkerByProcScan(ctx, workerID); err != nil { + // Fail closed: force-remove the worker container (kernel destroys the + // entire PID namespace & cgroup) while keeping /workspace and the task + // network/proxy intact so the next exec recreates a clean worker. + log.Printf("[runner] /proc uid kill for task %s failed (%v); force-removing worker container", taskID, err) + b.removeContainer(ctx, workerID) + b.mu.Lock() + if cur := b.tasks[taskID]; cur != nil && cur.workerID == workerID { + cur.workerID = "" + } + b.mu.Unlock() + } + return nil +} + +func (b *DockerBackend) killWorkerByProcScan(ctx context.Context, workerID string) error { + resp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(workerID)+"/exec", map[string]any{ + "AttachStdout": true, + "AttachStderr": true, + "Tty": false, + "User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID), + "Cmd": []string{"/usr/local/bin/artex-exec-wrap", "--kill-uid", strconv.Itoa(WorkerUID)}, + }) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode == http.StatusNotFound { + return fmt.Errorf("%w: worker %s gone", ErrNotFound, workerID) + } + if resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("kill exec create: HTTP %d: %s", resp.StatusCode, string(raw)) + } + var created struct { + ID string `json:"Id"` + } + if err := json.NewDecoder(resp.Body).Decode(&created); err != nil { + return err + } + kctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + sresp, err := b.dockerDo(kctx, http.MethodPost, "/exec/"+url.PathEscape(created.ID)+"/start", map[string]any{ + "Detach": false, + "Tty": false, + }) + if err != nil { + return err + } + _, _ = io.Copy(io.Discard, sresp.Body) + sresp.Body.Close() + + insResp, err := b.dockerDo(context.Background(), http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil) + if err != nil { + return err + } + defer insResp.Body.Close() + var ins struct { + ExitCode int `json:"ExitCode"` + } + if err := json.NewDecoder(insResp.Body).Decode(&ins); err != nil { + return err + } + if ins.ExitCode != 0 { + return fmt.Errorf("kill-uid exited %d", ins.ExitCode) + } + return nil +} + +// Delete kills and removes the task's worker container, egress proxy container, and +// per-task internal network, while preserving /app/data/tasks/ on disk. +func (b *DockerBackend) Delete(ctx context.Context, taskID string) error { + b.mu.Lock() + tc := b.tasks[taskID] + delete(b.tasks, taskID) + b.mu.Unlock() + + if tc == nil { + return fmt.Errorf("%w: task %s", ErrNotFound, taskID) + } + _ = b.Kill(ctx, taskID) + b.removeContainer(ctx, tc.workerID) + b.removeContainer(ctx, tc.proxyID) + b.removeNetwork(ctx, tc.netName) + return nil +} + +// demuxDockerStream parses Docker's 8-byte multiplexed stdout/stderr framing +// ([stream_type, 0, 0, 0, size_be32]) and caps each stream at maxBytes. +func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, truncated bool, err error) { + var outBuf, errBuf bytes.Buffer + hdr := make([]byte, 8) + for { + if _, err := io.ReadFull(r, hdr); err != nil { + if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { + break + } + return outBuf.String(), errBuf.String(), truncated, err + } + streamType := hdr[0] + frameLen := int64(binary.BigEndian.Uint32(hdr[4:8])) + if frameLen <= 0 { + continue + } + var dst *bytes.Buffer + if streamType == 2 { + dst = &errBuf + } else { + dst = &outBuf + } + rem := int64(maxBytes - dst.Len()) + if rem > 0 { + take := frameLen + if take > rem { + take = rem + truncated = true + } + if _, err := io.CopyN(dst, r, take); err != nil && !errors.Is(err, io.EOF) { + return outBuf.String(), errBuf.String(), truncated, err + } + frameLen -= take + } else { + truncated = true + } + if frameLen > 0 { + if _, err := io.CopyN(io.Discard, r, frameLen); err != nil && !errors.Is(err, io.EOF) { + return outBuf.String(), errBuf.String(), truncated, err + } + } + } + return outBuf.String(), errBuf.String(), truncated, nil +} diff --git a/sandbox/docker_e2e_test.go b/sandbox/docker_e2e_test.go new file mode 100644 index 000000000..18b8920e9 --- /dev/null +++ b/sandbox/docker_e2e_test.go @@ -0,0 +1,295 @@ +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 2>&1 & + nohup sh -c 'sleep 300' /dev/null 2>&1 & + sh -c '(setsid sh -c "trap "" TERM; sleep 300" /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 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) + } +} diff --git a/sandbox/policy.go b/sandbox/policy.go new file mode 100644 index 000000000..4978d5923 --- /dev/null +++ b/sandbox/policy.go @@ -0,0 +1,371 @@ +package sandbox + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/netip" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" +) + +// Metadata and reserved private prefixes denied by default unless explicitly +// listed in ARTEX_SCOPE_CIDRS (CONTRACT.md §§1, 5). +var defaultDeniedPrefixes = mustParsePrefixes([]string{ + "0.0.0.0/8", + "10.0.0.0/8", + "100.64.0.0/10", + "100.100.100.200/32", // Alibaba Cloud metadata + "127.0.0.0/8", + "168.63.129.16/32", // Azure wireserver / metadata + "169.254.0.0/16", // AWS/GCP/Azure link-local & 169.254.169.254 metadata + "172.16.0.0/12", + "192.168.0.0/16", + "224.0.0.0/4", + "240.0.0.0/4", + "::/128", + "::1/128", + "fc00::/7", + "fe80::/10", + "fd00:ec2::254/128", // AWS IPv6 IMDS + "ff00::/8", +}) + +func mustParsePrefixes(raw []string) []netip.Prefix { + out := make([]netip.Prefix, 0, len(raw)) + for _, s := range raw { + out = append(out, netip.MustParsePrefix(s)) + } + return out +} + +// EgressLogEntry is one JSON line logged per connection per CONTRACT.md §5. +type EgressLogEntry struct { + TaskID string `json:"task_id"` + TS string `json:"ts"` + Host string `json:"host"` + Port int `json:"port"` + ResolvedIP string `json:"resolved_ip"` + Protocol string `json:"protocol"` + Decision string `json:"decision"` + Bytes int64 `json:"bytes"` +} + +// EgressLogger writes JSONL connection records to stdout and optionally a per-task file. +type EgressLogger struct { + mu sync.Mutex + stdout io.Writer + file *os.File + taskID string +} + +// NewEgressLogger creates a logger writing to stdout (or w) and optionally logPath. +func NewEgressLogger(taskID, logPath string, stdout io.Writer) *EgressLogger { + if stdout == nil { + stdout = os.Stdout + } + l := &EgressLogger{taskID: taskID, stdout: stdout} + if strings.TrimSpace(logPath) != "" { + _ = os.MkdirAll(filepath.Dir(logPath), 0o755) + if f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644); err == nil { + l.file = f + } + } + return l +} + +// Close closes the underlying log file if open. +func (l *EgressLogger) Close() { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + if l.file != nil { + _ = l.file.Close() + l.file = nil + } +} + +// Log emits one JSONL line to both stdout and the per-task egress.jsonl file. +func (l *EgressLogger) Log(e EgressLogEntry) { + if l == nil { + return + } + if e.TaskID == "" { + e.TaskID = l.taskID + } + if e.TS == "" { + e.TS = time.Now().UTC().Format(time.RFC3339Nano) + } + raw, err := json.Marshal(e) + if err != nil { + return + } + raw = append(raw, '\n') + l.mu.Lock() + defer l.mu.Unlock() + if l.stdout != nil { + _, _ = l.stdout.Write(raw) + } + if l.file != nil { + _, _ = l.file.Write(raw) + } +} + +// EgressPolicy enforces per-task domain/CIDR allowlists with DNS pinning. + +// egressScopeHint makes sandbox egress denials non-silent regarding target-gate approvals. +const egressScopeHint = " (approve target in Task Scope; target-gate approval only clears the tool gate and does not widen worker egress)" + +type EgressPolicy struct { + TaskID string + Domains []string + CIDRs []netip.Prefix + Resolver func(ctx context.Context, host string) ([]netip.Addr, error) + Dialer func(ctx context.Context, network, addr string) (net.Conn, error) + Logger *EgressLogger +} + +// NewEgressPolicy parses comma-separated domain suffixes and IP/CIDR entries. +func NewEgressPolicy(taskID string, domains, cidrs []string, logger *EgressLogger) (*EgressPolicy, error) { + p := &EgressPolicy{ + TaskID: taskID, + Logger: logger, + } + for _, d := range domains { + d = strings.ToLower(strings.TrimSpace(d)) + d = strings.TrimPrefix(d, "*.") + d = strings.TrimPrefix(d, ".") + d = strings.TrimSuffix(d, ".") + if d != "" { + p.Domains = append(p.Domains, d) + } + } + for _, raw := range cidrs { + raw = strings.TrimSpace(raw) + if raw == "" { + continue + } + if strings.Contains(raw, "/") { + pfx, err := netip.ParsePrefix(raw) + if err != nil { + return nil, fmt.Errorf("invalid scope CIDR %q: %w", raw, err) + } + p.CIDRs = append(p.CIDRs, pfx.Masked()) + } else { + addr, err := netip.ParseAddr(raw) + if err != nil { + return nil, fmt.Errorf("invalid scope IP %q: %w", raw, err) + } + addr = addr.Unmap() + p.CIDRs = append(p.CIDRs, netip.PrefixFrom(addr, addr.BitLen())) + } + } + return p, nil +} + +// ParseCSV splits a comma-separated environment value into trimmed non-empty items. +func ParseCSV(raw string) []string { + var out []string + for _, part := range strings.Split(raw, ",") { + part = strings.TrimSpace(part) + if part != "" { + out = append(out, part) + } + } + return out +} + +func (p *EgressPolicy) domainAllowed(host string) bool { + h := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), ".")) + if h == "" { + return false + } + for _, suffix := range p.Domains { + if h == suffix || strings.HasSuffix(h, "."+suffix) { + return true + } + } + return false +} + +func (p *EgressPolicy) ipInScopeCIDR(addr netip.Addr) bool { + addr = addr.Unmap() + for _, pfx := range p.CIDRs { + if pfx.Contains(addr) { + return true + } + } + return false +} + +func isDefaultDeniedAddr(addr netip.Addr) bool { + addr = addr.Unmap() + // Deny all IPv6 unless explicitly in ARTEX_SCOPE_CIDRS (CONTRACT.md §5). + if addr.Is6() { + return true + } + for _, pfx := range defaultDeniedPrefixes { + if pfx.Contains(addr) { + return true + } + } + return false +} + +func (p *EgressPolicy) resolve(ctx context.Context, host string) ([]netip.Addr, error) { + if p.Resolver != nil { + return p.Resolver(ctx, host) + } + ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host) + if err != nil { + return nil, err + } + out := make([]netip.Addr, 0, len(ips)) + for _, ip := range ips { + out = append(out, ip.Unmap()) + } + return out, nil +} + +// ResolveAndCheck validates host against the allowlist, resolves DNS once if host is +// a domain name, checks every resolved IP against default-deny/private/metadata/IPv6 +// rules, and returns the pinned IP address to dial directly (zero rebinding window). +func (p *EgressPolicy) ResolveAndCheck(ctx context.Context, host string) (netip.Addr, error) { + h := strings.TrimSpace(host) + h = strings.TrimPrefix(strings.TrimSuffix(h, "]"), "[") + if h == "" { + return netip.Addr{}, errors.New("egress denied: empty host") + } + + // Literal IP target: allowed ONLY if explicitly in ARTEX_SCOPE_CIDRS. + if addr, err := netip.ParseAddr(h); err == nil { + addr = addr.Unmap() + if !p.ipInScopeCIDR(addr) { + return addr, fmt.Errorf("egress denied: IP %s is not in task scope CIDRs%s", addr, egressScopeHint) + } + return addr, nil + } + + // Domain target: must match ARTEX_SCOPE_DOMAINS. + if !p.domainAllowed(h) { + return netip.Addr{}, fmt.Errorf("egress denied: domain %q is not in task scope%s", h, egressScopeHint) + } + + addrs, err := p.resolve(ctx, h) + if err != nil || len(addrs) == 0 { + return netip.Addr{}, fmt.Errorf("egress denied: dns lookup failed for %q: %v", h, err) + } + for _, addr := range addrs { + addr = addr.Unmap() + if p.ipInScopeCIDR(addr) { + return addr, nil + } + if isDefaultDeniedAddr(addr) { + continue + } + return addr, nil + } + return addrs[0].Unmap(), fmt.Errorf("egress denied: %q resolved only to disallowed/private/IPv6 address %s", h, addrs[0].Unmap()) +} + +// DialPinned enforces the policy, pins the resolved IP, and dials directly to that IP. +func (p *EgressPolicy) DialPinned(ctx context.Context, host string, port int, protocol string) (net.Conn, netip.Addr, error) { + if port <= 0 || port > 65535 { + p.logDecision(host, port, "", protocol, "deny", 0) + return nil, netip.Addr{}, fmt.Errorf("egress denied: invalid port %d", port) + } + addr, err := p.ResolveAndCheck(ctx, host) + if err != nil { + ipStr := "" + if addr.IsValid() { + ipStr = addr.String() + } + p.logDecision(host, port, ipStr, protocol, "deny", 0) + return nil, addr, err + } + target := net.JoinHostPort(addr.String(), strconv.Itoa(port)) + dialFn := p.Dialer + if dialFn == nil { + d := &net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second} + dialFn = d.DialContext + } + conn, err := dialFn(ctx, "tcp", target) + if err != nil { + p.logDecision(host, port, addr.String(), protocol, "error", 0) + return nil, addr, err + } + return conn, addr, nil +} + +func (p *EgressPolicy) logDecision(host string, port int, ip, protocol, decision string, n int64) { + if p.Logger != nil { + p.Logger.Log(EgressLogEntry{ + TaskID: p.TaskID, + Host: host, + Port: port, + ResolvedIP: ip, + Protocol: protocol, + Decision: decision, + Bytes: n, + }) + } +} + +// CheckURL validates a navigation/fetch URL against the task scope allowlist. +// Only http/https/ws/wss schemes are permitted. Literal IPs must match +// ScopeCIDRs (blocking IMDS, loopback, RFC1918, and arbitrary non-scope IPs). +// Domains must match ScopeDomains; if DNS resolution returns addresses, at +// least one address must be allowed (rejecting domains resolving solely to +// private/IMDS/IPv6 addresses). +func (p *EgressPolicy) CheckURL(ctx context.Context, rawURL string) error { + rawURL = strings.TrimSpace(rawURL) + if rawURL == "" { + return errors.New("egress denied: empty URL") + } + u, err := url.Parse(rawURL) + if err != nil { + return fmt.Errorf("egress denied: invalid URL %q: %w", rawURL, err) + } + scheme := strings.ToLower(strings.TrimSpace(u.Scheme)) + switch scheme { + case "http", "https", "ws", "wss": + default: + return fmt.Errorf("egress denied: scheme %q is not allowed in sandbox mode", scheme) + } + host := strings.TrimSpace(u.Hostname()) + if host == "" { + return fmt.Errorf("egress denied: URL %q has no host", rawURL) + } + // Literal IP target: allowed ONLY if explicitly in ScopeCIDRs. + if addr, err := netip.ParseAddr(host); err == nil { + addr = addr.Unmap() + if !p.ipInScopeCIDR(addr) { + return fmt.Errorf("egress denied: IP %s is not in task scope CIDRs%s", addr, egressScopeHint) + } + return nil + } + if !p.domainAllowed(host) { + return fmt.Errorf("egress denied: domain %q is not in task scope%s", host, egressScopeHint) + } + // If DNS resolves, reject if every resolved IP is disallowed/private/IMDS/IPv6. + if addrs, err := p.resolve(ctx, host); err == nil && len(addrs) > 0 { + for _, addr := range addrs { + addr = addr.Unmap() + if p.ipInScopeCIDR(addr) || !isDefaultDeniedAddr(addr) { + return nil + } + } + return fmt.Errorf("egress denied: %q resolved only to disallowed/private/IPv6 address %s", host, addrs[0].Unmap()) + } + return nil +} diff --git a/sandbox/proxy.go b/sandbox/proxy.go new file mode 100644 index 000000000..ceaa62839 --- /dev/null +++ b/sandbox/proxy.go @@ -0,0 +1,303 @@ +package sandbox + +import ( + "bufio" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "strconv" + "strings" + "sync" + "time" +) + +// EgressProxy serves both an HTTP/HTTPS CONNECT proxy and a SOCKS5 TCP proxy +// backed by the same EgressPolicy (allowlist + DNS pinning + JSONL audit log). +type EgressProxy struct { + Policy *EgressPolicy + httpServer *http.Server + httpLn net.Listener + socksLn net.Listener +} + +// NewEgressProxy creates an EgressProxy bound to Policy. +func NewEgressProxy(policy *EgressPolicy) *EgressProxy { + ep := &EgressProxy{Policy: policy} + ep.httpServer = &http.Server{ + Handler: ep, + ReadHeaderTimeout: 15 * time.Second, + } + return ep +} + +// ServeHTTP handles both HTTP CONNECT tunnels and plain HTTP proxy requests. +func (p *EgressProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodConnect { + p.handleConnect(w, r) + return + } + p.handlePlainHTTP(w, r) +} + +func splitHostPortDefault(raw string, defaultPort int) (string, int, error) { + if strings.Contains(raw, ":") { + h, ps, err := net.SplitHostPort(raw) + if err == nil { + port, perr := strconv.Atoi(ps) + if perr != nil { + return "", 0, perr + } + return h, port, nil + } + } + return strings.TrimPrefix(strings.TrimSuffix(raw, "]"), "["), defaultPort, nil +} + +func (p *EgressProxy) handleConnect(w http.ResponseWriter, r *http.Request) { + host, port, err := splitHostPortDefault(r.Host, 443) + if err != nil { + http.Error(w, "bad CONNECT host", http.StatusBadRequest) + return + } + up, addr, err := p.Policy.DialPinned(r.Context(), host, port, "https-connect") + if err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return + } + defer up.Close() + + hj, ok := w.(http.Hijacker) + if !ok { + http.Error(w, "hijacking unsupported", http.StatusInternalServerError) + return + } + clientConn, buf, err := hj.Hijack() + if err != nil { + return + } + defer clientConn.Close() + + _, _ = io.WriteString(clientConn, "HTTP/1.1 200 Connection Established\r\n\r\n") + n := relayBidirectional(clientConn, buf, up) + p.Policy.logDecision(host, port, addr.String(), "https-connect", "allow", n) +} + +func (p *EgressProxy) handlePlainHTTP(w http.ResponseWriter, r *http.Request) { + if r.URL == nil || r.URL.Host == "" { + http.Error(w, "absolute URL required for proxy", http.StatusBadRequest) + return + } + defaultPort := 80 + if strings.EqualFold(r.URL.Scheme, "https") { + defaultPort = 443 + } + host, port, err := splitHostPortDefault(r.URL.Host, defaultPort) + if err != nil { + http.Error(w, "bad target host", http.StatusBadRequest) + return + } + up, addr, err := p.Policy.DialPinned(r.Context(), host, port, "http") + if err != nil { + http.Error(w, err.Error(), http.StatusForbidden) + return + } + defer up.Close() + + outReq := r.Clone(r.Context()) + outReq.RequestURI = "" + outReq.Header.Del("Proxy-Connection") + outReq.Header.Del("Proxy-Authorization") + + tr := &http.Transport{ + DialContext: func(context.Context, string, string) (net.Conn, error) { + return up, nil + }, + DisableKeepAlives: true, + } + resp, err := tr.RoundTrip(outReq) + if err != nil { + p.Policy.logDecision(host, port, addr.String(), "http", "error", 0) + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + defer resp.Body.Close() + for k, vals := range resp.Header { + for _, v := range vals { + w.Header().Add(k, v) + } + } + w.WriteHeader(resp.StatusCode) + n, _ := io.Copy(w, resp.Body) + p.Policy.logDecision(host, port, addr.String(), "http", "allow", n) +} + +// ServeSOCKS5 accepts RFC 1928 SOCKS5 TCP CONNECT connections on ln using the same Policy. +func (p *EgressProxy) ServeSOCKS5(ctx context.Context, ln net.Listener) error { + p.socksLn = ln + for { + conn, err := ln.Accept() + if err != nil { + if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { + return nil + } + return err + } + go p.handleSOCKS5Conn(ctx, conn) + } +} + +func (p *EgressProxy) handleSOCKS5Conn(ctx context.Context, c net.Conn) { + defer c.Close() + _ = c.SetDeadline(time.Now().Add(15 * time.Second)) + br := bufio.NewReader(c) + + // 1) Greeting: VER, NMETHODS, METHODS... + ver, err := br.ReadByte() + if err != nil || ver != 0x05 { + return + } + nMethods, err := br.ReadByte() + if err != nil { + return + } + methods := make([]byte, int(nMethods)) + if _, err := io.ReadFull(br, methods); err != nil { + return + } + // Select NO AUTHENTICATION REQUIRED (0x00) + if _, err := c.Write([]byte{0x05, 0x00}); err != nil { + return + } + + // 2) Request: VER, CMD, RSV, ATYP, DST.ADDR, DST.PORT + hdr := make([]byte, 4) + if _, err := io.ReadFull(br, hdr); err != nil || hdr[0] != 0x05 { + return + } + if hdr[1] != 0x01 { // Only CONNECT (0x01); refuse BIND / UDP ASSOCIATE + _, _ = c.Write([]byte{0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0}) + return + } + var host string + switch hdr[3] { + case 0x01: // IPv4 + buf := make([]byte, 4) + if _, err := io.ReadFull(br, buf); err != nil { + return + } + ip, _ := netip.AddrFromSlice(buf) + host = ip.String() + case 0x03: // Domain name + l, err := br.ReadByte() + if err != nil { + return + } + buf := make([]byte, int(l)) + if _, err := io.ReadFull(br, buf); err != nil { + return + } + host = string(buf) + case 0x04: // IPv6 + buf := make([]byte, 16) + if _, err := io.ReadFull(br, buf); err != nil { + return + } + ip, _ := netip.AddrFromSlice(buf) + host = ip.String() + default: + _, _ = c.Write([]byte{0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0}) + return + } + portBuf := make([]byte, 2) + if _, err := io.ReadFull(br, portBuf); err != nil { + return + } + port := int(binary.BigEndian.Uint16(portBuf)) + + up, addr, err := p.Policy.DialPinned(ctx, host, port, "socks5") + if err != nil { + // 0x02 = connection not allowed by ruleset + _, _ = c.Write([]byte{0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0}) + return + } + defer up.Close() + + _ = c.SetDeadline(time.Time{}) + _, _ = c.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0}) + n := relayBidirectional(c, br, up) + p.Policy.logDecision(host, port, addr.String(), "socks5", "allow", n) +} + +func relayBidirectional(client net.Conn, clientBuf io.Reader, upstream net.Conn) int64 { + var wg sync.WaitGroup + var c2u, u2c int64 + wg.Add(2) + go func() { + defer wg.Done() + c2u, _ = io.Copy(upstream, clientBuf) + if tc, ok := upstream.(*net.TCPConn); ok { + _ = tc.CloseWrite() + } + }() + go func() { + defer wg.Done() + u2c, _ = io.Copy(client, upstream) + if tc, ok := client.(*net.TCPConn); ok { + _ = tc.CloseWrite() + } + }() + wg.Wait() + return c2u + u2c +} + +// ListenAndServe starts both the HTTP proxy and SOCKS5 proxy until ctx is cancelled. +func (p *EgressProxy) ListenAndServe(ctx context.Context, httpAddr, socksAddr string) error { + hln, err := net.Listen("tcp", httpAddr) + if err != nil { + return fmt.Errorf("listen http proxy %s: %w", httpAddr, err) + } + p.httpLn = hln + errCh := make(chan error, 2) + go func() { + if err := p.httpServer.Serve(hln); err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- err + } + }() + if socksAddr != "" { + sln, err := net.Listen("tcp", socksAddr) + if err != nil { + _ = p.Close() + return fmt.Errorf("listen socks5 proxy %s: %w", socksAddr, err) + } + p.socksLn = sln + go func() { + if err := p.ServeSOCKS5(ctx, sln); err != nil { + errCh <- err + } + }() + } + select { + case <-ctx.Done(): + _ = p.Close() + return nil + case err := <-errCh: + _ = p.Close() + return err + } +} + +// Close shuts down both listeners. +func (p *EgressProxy) Close() error { + if p.httpServer != nil { + _ = p.httpServer.Close() + } + if p.socksLn != nil { + _ = p.socksLn.Close() + } + return nil +} diff --git a/sandbox/runner.go b/sandbox/runner.go new file mode 100644 index 000000000..6f8803af9 --- /dev/null +++ b/sandbox/runner.go @@ -0,0 +1,166 @@ +package sandbox + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "strings" +) + +// Backend is the container lifecycle backend used by RunnerServer (DockerBackend in production, +// fake backend in unit tests). +type Backend interface { + Ping(ctx context.Context) error + Recover(ctx context.Context) (int, error) + WorkerCount() int + Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) + Kill(ctx context.Context, taskID string) error + Delete(ctx context.Context, taskID string) error +} + +// RunnerServer implements the pinned HTTP API from CONTRACT.md §3. +type RunnerServer struct { + token string + version string + backend Backend + mux *http.ServeMux +} + +// NewRunnerServer builds an authenticated RunnerServer. Empty token is refused. +func NewRunnerServer(token, version string, backend Backend) (*RunnerServer, error) { + token = strings.TrimSpace(token) + if token == "" { + return nil, errors.New("ARTEX_RUNNER_TOKEN is required") + } + if version == "" { + version = "dev" + } + rs := &RunnerServer{ + token: token, + version: version, + backend: backend, + mux: http.NewServeMux(), + } + rs.mux.HandleFunc("GET /v1/health", rs.withAuth(rs.handleHealth)) + rs.mux.HandleFunc("POST /v1/tasks/{id}/exec", rs.withAuth(rs.handleExec)) + rs.mux.HandleFunc("POST /v1/tasks/{id}/kill", rs.withAuth(rs.handleKill)) + rs.mux.HandleFunc("DELETE /v1/tasks/{id}", rs.withAuth(rs.handleDelete)) + return rs, nil +} + +// Handler returns the HTTP handler for artex-runner. +func (rs *RunnerServer) Handler() http.Handler { return rs.mux } + +func (rs *RunnerServer) withAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + auth := r.Header.Get("Authorization") + if !strings.HasPrefix(auth, "Bearer ") { + writeRunnerErr(w, http.StatusUnauthorized, "missing bearer token") + return + } + got := strings.TrimPrefix(auth, "Bearer ") + if subtle.ConstantTimeCompare([]byte(got), []byte(rs.token)) != 1 { + writeRunnerErr(w, http.StatusUnauthorized, "invalid bearer token") + return + } + next(w, r) + } +} + +func (rs *RunnerServer) handleHealth(w http.ResponseWriter, r *http.Request) { + dockerOK := rs.backend != nil && rs.backend.Ping(r.Context()) == nil + workers := 0 + if rs.backend != nil { + workers = rs.backend.WorkerCount() + } + resp := HealthResponse{ + OK: dockerOK, + Docker: dockerOK, + Workers: workers, + Version: rs.version, + } + if !dockerOK { + writeRunnerJSON(w, http.StatusConflict, resp) + return + } + writeRunnerJSON(w, http.StatusOK, resp) +} + +func (rs *RunnerServer) handleExec(w http.ResponseWriter, r *http.Request) { + taskID := r.PathValue("id") + if err := ValidateTaskID(taskID); err != nil { + writeRunnerErr(w, http.StatusBadRequest, err.Error()) + return + } + var req ExecRequest + dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20)) + if err := dec.Decode(&req); err != nil { + writeRunnerErr(w, http.StatusBadRequest, "invalid json: "+err.Error()) + return + } + if err := ValidateExecRequest(&req); err != nil { + writeRunnerErr(w, http.StatusBadRequest, err.Error()) + return + } + res, err := rs.backend.Exec(r.Context(), taskID, req) + if err != nil { + rs.writeBackendErr(w, err) + return + } + writeRunnerJSON(w, http.StatusOK, res) +} + +func (rs *RunnerServer) handleKill(w http.ResponseWriter, r *http.Request) { + taskID := r.PathValue("id") + if err := ValidateTaskID(taskID); err != nil { + writeRunnerErr(w, http.StatusBadRequest, err.Error()) + return + } + if err := rs.backend.Kill(r.Context(), taskID); err != nil { + rs.writeBackendErr(w, err) + return + } + writeRunnerJSON(w, http.StatusOK, KillResponse{Killed: true}) +} + +func (rs *RunnerServer) handleDelete(w http.ResponseWriter, r *http.Request) { + taskID := r.PathValue("id") + if err := ValidateTaskID(taskID); err != nil { + writeRunnerErr(w, http.StatusBadRequest, err.Error()) + return + } + if err := rs.backend.Delete(r.Context(), taskID); err != nil { + rs.writeBackendErr(w, err) + return + } + writeRunnerJSON(w, http.StatusOK, DeleteResponse{Deleted: true}) +} + +func (rs *RunnerServer) writeBackendErr(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, ErrBadRequest): + writeRunnerErr(w, http.StatusBadRequest, err.Error()) + case errors.Is(err, ErrNotFound): + writeRunnerErr(w, http.StatusNotFound, err.Error()) + case errors.Is(err, ErrDockerUnavailable): + writeRunnerErr(w, http.StatusConflict, err.Error()) + default: + log.Printf("[runner] backend error: %v", err) + writeRunnerErr(w, http.StatusInternalServerError, fmt.Sprintf("runner error: %v", err)) + } +} + +func writeRunnerJSON(w http.ResponseWriter, code int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(v) +} + +func writeRunnerErr(w http.ResponseWriter, code int, msg string) { + writeRunnerJSON(w, code, map[string]string{"error": msg}) +} diff --git a/sandbox/sandbox_test.go b/sandbox/sandbox_test.go new file mode 100644 index 000000000..2b1da01e2 --- /dev/null +++ b/sandbox/sandbox_test.go @@ -0,0 +1,517 @@ +package sandbox + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +func TestValidateEnvRejectsForbiddenPatternsAndOversizedValues(t *testing.T) { + forbidden := []string{ + "ARTEX_PG_DSN", "ARTEX_RUNNER_TOKEN", "artex_secret", + "OPENAI_API_KEY", "JWT_KEY", "AUTH_TOKEN", "DB_PASSWORD", "CLIENT_SECRET", + "PGHOST", "PGPASSWORD", "PGUSER", + "AWS_ACCESS_KEY_ID", "GCP_PROJECT", "AZURE_CLIENT_ID", + } + for _, name := range forbidden { + if err := ValidateEnv(map[string]string{name: "val"}); !errors.Is(err, ErrBadRequest) { + t.Errorf("ValidateEnv(%q) = %v, want ErrBadRequest", name, err) + } + } + if err := ValidateEnv(map[string]string{"FOO": strings.Repeat("a", MaxEnvValueBytes+1)}); !errors.Is(err, ErrBadRequest) { + t.Fatalf("oversized env value error = %v, want ErrBadRequest", err) + } + if err := ValidateEnv(map[string]string{"FOO": "bar", "HTTP_USER_AGENT": "ok"}); err != nil { + t.Fatalf("valid env rejected: %v", err) + } +} + +type fakeBackend struct { + mu sync.Mutex + pingErr error + workers map[string]bool + killed []string + deleted []string + lastExecReq ExecRequest +} + +func newFakeBackend() *fakeBackend { + return &fakeBackend{workers: map[string]bool{}} +} + +func (f *fakeBackend) Ping(context.Context) error { + f.mu.Lock() + defer f.mu.Unlock() + return f.pingErr +} +func (f *fakeBackend) Recover(context.Context) (int, error) { return 0, nil } +func (f *fakeBackend) WorkerCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.workers) +} +func (f *fakeBackend) Exec(_ context.Context, taskID string, req ExecRequest) (ExecResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.pingErr != nil { + return ExecResponse{}, fmt.Errorf("%w: %v", ErrDockerUnavailable, f.pingErr) + } + f.workers[taskID] = true + f.lastExecReq = req + return ExecResponse{ExitCode: 0, Stdout: "ran:" + strings.Join(req.Argv, " "), DurationMS: 5}, nil +} +func (f *fakeBackend) Kill(_ context.Context, taskID string) error { + f.mu.Lock() + defer f.mu.Unlock() + if !f.workers[taskID] { + return fmt.Errorf("%w: %s", ErrNotFound, taskID) + } + f.killed = append(f.killed, taskID) + return nil +} +func (f *fakeBackend) Delete(_ context.Context, taskID string) error { + f.mu.Lock() + defer f.mu.Unlock() + if !f.workers[taskID] { + return fmt.Errorf("%w: %s", ErrNotFound, taskID) + } + delete(f.workers, taskID) + f.deleted = append(f.deleted, taskID) + return nil +} + +func TestRunnerHTTPAuthAndEndpoints(t *testing.T) { + fb := newFakeBackend() + rs, err := NewRunnerServer("super-runner-tok", "test-v1", fb) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(rs.Handler()) + defer srv.Close() + + // Missing / wrong token -> 401 on EVERY route including /v1/health. + badClient := NewClient(srv.URL, "wrong") + if _, err := badClient.Health(context.Background()); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("health with wrong token: %v, want ErrUnauthorized", err) + } + noTokClient := NewClient(srv.URL, "") + if _, err := noTokClient.Health(context.Background()); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("health without token: %v, want ErrUnauthorized", err) + } + + cl := NewClient(srv.URL, "super-runner-tok") + h, err := cl.Health(context.Background()) + if err != nil || !h.OK || !h.Docker || h.Version != "test-v1" || h.Workers != 0 { + t.Fatalf("health = %+v err=%v", h, err) + } + + // Forbidden env -> 400 (not silent drop). + if _, err := cl.Exec(context.Background(), "42", ExecRequest{ + Argv: []string{"id"}, + Env: map[string]string{"AWS_SECRET_ACCESS_KEY": "nope"}, + }); !errors.Is(err, ErrBadRequest) { + t.Fatalf("forbidden env err = %v, want ErrBadRequest", err) + } + + // Valid exec -> 200. + res, err := cl.Exec(context.Background(), "42", ExecRequest{ + Argv: []string{"bash", "-c", "id"}, + Env: map[string]string{"FOO": "bar"}, + }) + if err != nil || res.ExitCode != 0 || !strings.Contains(res.Stdout, "bash -c id") { + t.Fatalf("exec = %+v err=%v", res, err) + } + + // Kill unknown task -> 404; known task -> 200. + if _, err := cl.Kill(context.Background(), "999"); !errors.Is(err, ErrNotFound) { + t.Fatalf("kill unknown = %v, want ErrNotFound", err) + } + if kr, err := cl.Kill(context.Background(), "42"); err != nil || !kr.Killed { + t.Fatalf("kill 42 = %+v err=%v", kr, err) + } + + // Delete known task -> 200; second delete -> 404. + if dr, err := cl.Delete(context.Background(), "42"); err != nil || !dr.Deleted { + t.Fatalf("delete 42 = %+v err=%v", dr, err) + } + if _, err := cl.Delete(context.Background(), "42"); !errors.Is(err, ErrNotFound) { + t.Fatalf("delete 42 again = %v, want ErrNotFound", err) + } + + // Docker unreachable -> 409. + fb.mu.Lock() + fb.pingErr = errors.New("socket closed") + fb.mu.Unlock() + if _, err := cl.Health(context.Background()); !errors.Is(err, ErrDockerUnavailable) { + t.Fatalf("health when docker down = %v, want ErrDockerUnavailable (409)", err) + } +} + +func TestEgressPolicyAndProxyAllowDenyAndDNSPinning(t *testing.T) { + logFile := filepath.Join(t.TempDir(), "egress.jsonl") + var stdoutBuf bytes.Buffer + logger := NewEgressLogger("task-7", logFile, &stdoutBuf) + defer logger.Close() + + // Target backend on local loopback (explicitly allowlisted via CIDR ONLY for the positive test). + targetSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, "hello-allowed-target") + })) + defer targetSrv.Close() + tu, _ := url.Parse(targetSrv.URL) + _, portStr, _ := net.SplitHostPort(tu.Host) + + // Policy 1: domain allowlist only (no private CIDRs) — verifies metadata/RFC1918/IPv6/rebind denial. + polStrict, err := NewEgressPolicy("task-7", []string{"allowed.example"}, nil, logger) + if err != nil { + t.Fatal(err) + } + polStrict.Resolver = func(_ context.Context, host string) ([]netip.Addr, error) { + switch host { + case "rebind.allowed.example": + return []netip.Addr{netip.MustParseAddr("169.254.169.254")}, nil + case "ipv6.allowed.example": + return []netip.Addr{netip.MustParseAddr("2606:2800:220:1:248:1893:25c8:1946")}, nil + case "ok.allowed.example": + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil + default: + return nil, errors.New("nxdomain") + } + } + + deniedHosts := []string{ + "169.254.169.254", + "fd00:ec2::254", + "168.63.129.16", + "100.100.100.200", + "127.0.0.1", + "10.0.0.1", + "172.16.0.1", + "192.168.1.1", + "evil.example", + "rebind.allowed.example", // DNS rebinding to IMDS denied! + "ipv6.allowed.example", // IPv6 denied unless in ARTEX_SCOPE_CIDRS! + } + for _, h := range deniedHosts { + if _, err := polStrict.ResolveAndCheck(context.Background(), h); err == nil { + t.Errorf("host %q was unexpectedly allowed", h) + } + } + if ip, err := polStrict.ResolveAndCheck(context.Background(), "ok.allowed.example"); err != nil || ip.String() != "93.184.216.34" { + t.Fatalf("ok.allowed.example = %v %v, want 93.184.216.34", ip, err) + } + + // Policy 2: explicit CIDR 127.0.0.1/32 for live HTTP proxy & SOCKS5 proxy tests. + polLive, err := NewEgressPolicy("task-7", []string{"target.test"}, []string{"127.0.0.1/32"}, logger) + if err != nil { + t.Fatal(err) + } + polLive.Resolver = func(_ context.Context, host string) ([]netip.Addr, error) { + if host == "app.target.test" { + return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil + } + return []netip.Addr{netip.MustParseAddr("203.0.113.10")}, nil + } + + ep := NewEgressProxy(polLive) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + httpLn, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer httpLn.Close() + go func() { _ = ep.httpServer.Serve(httpLn) }() + + socksLn, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer socksLn.Close() + go func() { _ = ep.ServeSOCKS5(ctx, socksLn) }() + + proxyURL, _ := url.Parse("http://" + httpLn.Addr().String()) + httpCl := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}} + + // Allowed HTTP request through proxy. + resp, err := httpCl.Get("http://app.target.test:" + portStr + "/") + if err != nil { + t.Fatalf("allowed HTTP via proxy failed: %v", err) + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if resp.StatusCode != 200 || string(body) != "hello-allowed-target" { + t.Fatalf("HTTP proxy response = %d %q", resp.StatusCode, body) + } + + // Denied metadata endpoint through HTTP proxy -> 403. + resp2, err := httpCl.Get("http://169.254.169.254/latest/meta-data/") + if err != nil { + t.Fatalf("denied metadata HTTP call err: %v", err) + } + resp2.Body.Close() + if resp2.StatusCode != http.StatusForbidden { + t.Fatalf("metadata HTTP status = %d, want 403", resp2.StatusCode) + } + + // SOCKS5 denied metadata endpoint -> reply 0x02 (not allowed by ruleset). + sc, err := net.DialTimeout("tcp", socksLn.Addr().String(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + defer sc.Close() + _, _ = sc.Write([]byte{0x05, 0x01, 0x00}) + greet := make([]byte, 2) + if _, err := io.ReadFull(sc, greet); err != nil || greet[0] != 0x05 || greet[1] != 0x00 { + t.Fatalf("socks5 greet = %x err=%v", greet, err) + } + // CONNECT 169.254.169.254:80 + _, _ = sc.Write([]byte{0x05, 0x01, 0x00, 0x01, 169, 254, 169, 254, 0, 80}) + rep := make([]byte, 10) + if _, err := io.ReadFull(sc, rep); err != nil || rep[1] != 0x02 { + t.Fatalf("socks5 metadata reply = %x err=%v, want rep=0x02 (denied)", rep, err) + } + + // Verify egress.jsonl recorded both allow and deny JSON lines. + rawLog, err := os.ReadFile(logFile) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(rawLog), `"decision":"allow"`) || !strings.Contains(string(rawLog), `"decision":"deny"`) { + t.Fatalf("egress.jsonl missing allow/deny records:\n%s", rawLog) + } +} + +func TestDemuxDockerStreamCapsAt1MiB(t *testing.T) { + var raw bytes.Buffer + writeFrame := func(stream byte, data []byte) { + hdr := make([]byte, 8) + hdr[0] = stream + binary.BigEndian.PutUint32(hdr[4:8], uint32(len(data))) + raw.Write(hdr) + raw.Write(data) + } + writeFrame(1, bytes.Repeat([]byte("A"), MaxOutputBytes+128)) + writeFrame(2, []byte("err-line")) + out, errOut, trunc, err := demuxDockerStream(&raw, MaxOutputBytes) + if err != nil { + t.Fatal(err) + } + if !trunc || len(out) != MaxOutputBytes || errOut != "err-line" { + t.Fatalf("demux: len(out)=%d err=%q trunc=%v", len(out), errOut, trunc) + } +} + +func TestComposeSandboxConfigBoundary(t *testing.T) { + if _, err := exec.LookPath("docker"); err != nil { + t.Skip("docker CLI not available") + } + cmd := exec.Command("docker", "compose", "-f", "../docker-compose.yml", "-f", "../docker-compose.sandbox.yml", "config", "--format", "json") + cmd.Env = append(os.Environ(), "POSTGRES_PASSWORD=test", "ARTEX_RUNNER_TOKEN=testtoken") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("docker compose config failed: %v\n%s", err, out) + } + var cfg struct { + Networks map[string]struct { + Internal bool `json:"internal"` + } `json:"networks"` + Services map[string]struct { + Networks map[string]any `json:"networks"` + Volumes []map[string]any `json:"volumes"` + Environment map[string]string `json:"environment"` + } `json:"services"` + } + if err := json.Unmarshal(out, &cfg); err != nil { + t.Fatalf("unmarshal compose json: %v", err) + } + rn, ok := cfg.Networks["runner-net"] + if !ok || !rn.Internal { + t.Fatalf("runner-net must be internal: true, got %+v", cfg.Networks) + } + artexSvc := cfg.Services["artex"] + runnerSvc := cfg.Services["artex-runner"] + for _, v := range artexSvc.Volumes { + if src, _ := v["source"].(string); strings.Contains(src, "docker.sock") { + t.Fatalf("panel artex service must NEVER mount docker.sock: %+v", v) + } + } + if artexSvc.Environment["ARTEX_SANDBOX"] != "required" { + t.Fatalf("artex ARTEX_SANDBOX = %q, want required", artexSvc.Environment["ARTEX_SANDBOX"]) + } + hasSock := false + for _, v := range runnerSvc.Volumes { + if src, _ := v["source"].(string); src == "/var/run/docker.sock" { + hasSock = true + } + } + if !hasSock { + t.Fatalf("artex-runner must mount /var/run/docker.sock, got %+v", runnerSvc.Volumes) + } + if _, hasRunnerNet := runnerSvc.Networks["runner-net"]; len(runnerSvc.Networks) != 1 || !hasRunnerNet { + t.Fatalf("artex-runner must attach ONLY to runner-net, got %+v", runnerSvc.Networks) + } +} + +// TestDockerBackendRejectsUnsafeExistingNetwork verifies ensureNetwork fails +// closed if a pre-existing artex-task- network is not internal=true or +// lacks runner-owned labels. +func TestDockerBackendRejectsUnsafeExistingNetwork(t *testing.T) { + cases := []struct { + name string + internal bool + labels map[string]string + wantErr bool + }{ + { + name: "non_internal_rejected", + internal: false, + labels: map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "t1"}, + wantErr: true, + }, + { + name: "missing_runner_labels_rejected", + internal: true, + labels: map[string]string{}, + wantErr: true, + }, + { + name: "wrong_task_label_rejected", + internal: true, + labels: map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "other"}, + wantErr: true, + }, + { + name: "valid_internal_runner_network_accepted", + internal: true, + labels: map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "t1"}, + wantErr: false, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + sock := filepath.Join(t.TempDir(), "docker.sock") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/networks/") { + _ = json.NewEncoder(w).Encode(map[string]any{ + "Name": "artex-task-t1", + "Internal": tc.internal, + "Labels": tc.labels, + }) + return + } + w.WriteHeader(http.StatusNotFound) + })} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { + _ = srv.Close() + _ = ln.Close() + }) + + b := NewDockerBackend(DockerConfig{SocketPath: sock}) + err = b.ensureNetwork(context.Background(), "artex-task-t1", true, "t1") + if tc.wantErr && err == nil { + t.Fatalf("expected error for %s, got nil", tc.name) + } + if !tc.wantErr && err != nil { + t.Fatalf("expected nil error for %s, got %v", tc.name, err) + } + }) + } +} + +// TestDockerBackendRecreatesDeadWorker verifies that if startContainer fails +// on a cached dead worker container, ensureTask removes it and creates a fresh +// worker container rather than returning the stale ID. +func TestDockerBackendRecreatesDeadWorker(t *testing.T) { + sock := filepath.Join(t.TempDir(), "docker.sock") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + var workerCreates atomic.Int32 + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + p := r.URL.Path + switch { + case r.Method == http.MethodGet && strings.HasPrefix(p, "/networks/artex-task-"): + _ = json.NewEncoder(w).Encode(map[string]any{ + "Internal": true, + "Labels": map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "tdead"}, + }) + case r.Method == http.MethodGet && strings.HasPrefix(p, "/networks/"): + _ = json.NewEncoder(w).Encode(map[string]any{"Internal": false, "Labels": map[string]string{}}) + case r.Method == http.MethodPost && p == "/containers/dead-worker/start": + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte("no such container")) + case r.Method == http.MethodPost && strings.HasSuffix(p, "/start"): + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"): + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodPost && p == "/containers/create": + name := r.URL.Query().Get("name") + if strings.HasPrefix(name, "artex-worker-") { + n := workerCreates.Add(1) + _ = json.NewEncoder(w).Encode(map[string]string{"Id": fmt.Sprintf("fresh-worker-%d", n)}) + return + } + _ = json.NewEncoder(w).Encode(map[string]string{"Id": "proxy-1"}) + default: + w.WriteHeader(http.StatusOK) + } + })} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { + _ = srv.Close() + _ = ln.Close() + }) + + ws := t.TempDir() + au := t.TempDir() + b := NewDockerBackend(DockerConfig{ + SocketPath: sock, + WorkspaceRoot: ws, + HostWorkspaceRoot: ws, + AuditRoot: au, + HostAuditRoot: au, + }) + b.tasks["tdead"] = &taskContainers{ + taskID: "tdead", + workerID: "dead-worker", + proxyID: "live-proxy", + netName: "artex-task-tdead", + scopeHash: scopeFingerprint(nil, nil), + } + + tc, err := b.ensureTask(context.Background(), "tdead", nil, nil) + if err != nil { + t.Fatalf("ensureTask failed: %v", err) + } + if tc.workerID != "fresh-worker-1" { + t.Fatalf("expected recreated worker ID fresh-worker-1, got %q", tc.workerID) + } + if workerCreates.Load() != 1 { + t.Fatalf("expected 1 worker create call, got %d", workerCreates.Load()) + } +} diff --git a/sandbox/types.go b/sandbox/types.go new file mode 100644 index 000000000..9995e26d1 --- /dev/null +++ b/sandbox/types.go @@ -0,0 +1,141 @@ +package sandbox + +import ( + "errors" + "fmt" + "os" + "strings" +) + +// Pinned environment variables, defaults, limits, and labels from CONTRACT.md. +const ( + ModeRequired = "required" + ModeOff = "off" + + EnvSandboxMode = "ARTEX_SANDBOX" + EnvRunnerURL = "ARTEX_RUNNER_URL" + EnvRunnerToken = "ARTEX_RUNNER_TOKEN" + EnvWorkerImage = "ARTEX_WORKER_IMAGE" + EnvProxyImage = "ARTEX_EGRESS_PROXY_IMAGE" + EnvWorkspaceRoot = "ARTEX_WORKSPACE_ROOT" + EnvAuditRoot = "ARTEX_AUDIT_ROOT" + EnvTaskNetPrefix = "ARTEX_TASK_NET_PREFIX" + EnvEgressNet = "ARTEX_EGRESS_NET" + + DefaultRunnerURL = "http://artex-runner:8789" + DefaultRunnerAddr = ":8789" + DefaultWorkerImage = "artex-worker:local" + DefaultProxyImage = "artex-egress-proxy:local" + DefaultWorkspaceRoot = "/app/data/tasks" + DefaultAuditRoot = "/app/data/egress-audit" + DefaultTaskNetPrefix = "artex-task-" + DefaultEgressNet = "egress-net" + + DefaultProxyPort = 3128 + DefaultSocksPort = 1080 + + DefaultTimeoutMS = 600000 + MaxTimeoutMS = 3600000 + MaxOutputBytes = 1 << 20 // 1 MiB per stream + MaxEnvValueBytes = 8192 + + LabelTask = "artex.task" + LabelComponent = "artex.component" + LabelManagedBy = "artex.managed_by" + + ComponentWorker = "worker" + ComponentProxy = "egress-proxy" + ManagedByRunner = "artex-runner" + + WorkerUID = 10001 + WorkerGID = 10001 +) + +// Typed client / runner errors. +var ( + ErrRunnerUnavailable = errors.New("sandbox runner unavailable") + ErrUnauthorized = errors.New("sandbox runner unauthorized") + ErrBadRequest = errors.New("sandbox runner invalid request") + ErrNotFound = errors.New("sandbox task not found") + ErrDockerUnavailable = errors.New("sandbox runner cannot reach docker") +) + +// ExecRequest is the request body for POST /v1/tasks/{id}/exec. +type ExecRequest struct { + Argv []string `json:"argv"` + Workdir string `json:"workdir,omitempty"` + TimeoutMS int `json:"timeout_ms,omitempty"` + Env map[string]string `json:"env,omitempty"` + ScopeDomains []string `json:"scope_domains,omitempty"` + ScopeCIDRs []string `json:"scope_cidrs,omitempty"` +} + +// ExecResponse is the response body for POST /v1/tasks/{id}/exec. +type ExecResponse struct { + ExitCode int `json:"exit_code"` + Stdout string `json:"stdout"` + Stderr string `json:"stderr"` + Truncated bool `json:"truncated"` + TimedOut bool `json:"timed_out"` + DurationMS int64 `json:"duration_ms"` +} + +// KillResponse is the response body for POST /v1/tasks/{id}/kill. +type KillResponse struct { + Killed bool `json:"killed"` +} + +// DeleteResponse is the response body for DELETE /v1/tasks/{id}. +type DeleteResponse struct { + Deleted bool `json:"deleted"` +} + +// HealthResponse is the response body for GET /v1/health. +type HealthResponse struct { + OK bool `json:"ok"` + Docker bool `json:"docker"` + Workers int `json:"workers"` + Version string `json:"version"` +} + +// PanelConfig holds panel-side sandbox configuration parsed from env. +type PanelConfig struct { + Mode string + RunnerURL string + RunnerToken string +} + +// ModeFromEnv reads ARTEX_SANDBOX. Unset/empty defaults to "required". +func ModeFromEnv() (string, error) { + raw := strings.ToLower(strings.TrimSpace(os.Getenv(EnvSandboxMode))) + switch raw { + case "", ModeRequired: + return ModeRequired, nil + case ModeOff: + return ModeOff, nil + default: + return "", fmt.Errorf("invalid %s=%q (want %q or %q)", EnvSandboxMode, raw, ModeRequired, ModeOff) + } +} + +// PanelConfigFromEnv parses panel sandbox env vars (ARTEX_SANDBOX, ARTEX_RUNNER_URL, ARTEX_RUNNER_TOKEN). +func PanelConfigFromEnv() (PanelConfig, error) { + mode, err := ModeFromEnv() + if err != nil { + return PanelConfig{}, err + } + u := strings.TrimSpace(os.Getenv(EnvRunnerURL)) + if u == "" { + u = DefaultRunnerURL + } + return PanelConfig{ + Mode: mode, + RunnerURL: strings.TrimRight(u, "/"), + RunnerToken: strings.TrimSpace(os.Getenv(EnvRunnerToken)), + }, nil +} + +// IsUnavailable reports whether err indicates the sandbox runner or Docker cannot be reached. +func IsUnavailable(err error) bool { + return errors.Is(err, ErrRunnerUnavailable) || errors.Is(err, ErrDockerUnavailable) +} diff --git a/sandbox/validate.go b/sandbox/validate.go new file mode 100644 index 000000000..9061b7702 --- /dev/null +++ b/sandbox/validate.go @@ -0,0 +1,112 @@ +package sandbox + +import ( + "fmt" + "path" + "regexp" + "strings" +) + +var ( + taskIDRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,63}$`) + envNameRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`) +) + +// ValidateTaskID verifies a task ID is safe for Docker names, labels, and workspace paths. +func ValidateTaskID(id string) error { + id = strings.TrimSpace(id) + if id == "" || !taskIDRE.MatchString(id) || strings.Contains(id, "..") { + return fmt.Errorf("%w: invalid task id %q", ErrBadRequest, id) + } + return nil +} + +// IsForbiddenEnvName reports whether name matches any forbidden secret/cloud/DB pattern +// pinned in CONTRACT.md §3: ARTEX_*, *_KEY, *_TOKEN, *_PASSWORD, *_SECRET, PG*, AWS_*, GCP_*, AZURE_*. +func IsForbiddenEnvName(name string) bool { + u := strings.ToUpper(strings.TrimSpace(name)) + if u == "" { + return true + } + for _, prefix := range []string{"ARTEX_", "PG", "AWS_", "GCP_", "AZURE_"} { + if strings.HasPrefix(u, prefix) { + return true + } + } + for _, suffix := range []string{"_KEY", "_TOKEN", "_PASSWORD", "_SECRET"} { + if strings.HasSuffix(u, suffix) { + return true + } + } + return false +} + +// ValidateEnv rejects forbidden variable names, invalid names, NUL bytes, or values > 8192 bytes. +// Per CONTRACT.md §3 this is always a 400 validation error, never a silent drop. +func ValidateEnv(env map[string]string) error { + for k, v := range env { + if !envNameRE.MatchString(k) { + return fmt.Errorf("%w: invalid env variable name %q", ErrBadRequest, k) + } + if IsForbiddenEnvName(k) { + return fmt.Errorf("%w: forbidden env variable %q", ErrBadRequest, k) + } + if len(v) > MaxEnvValueBytes { + return fmt.Errorf("%w: env variable %q exceeds %d bytes", ErrBadRequest, k, MaxEnvValueBytes) + } + if strings.ContainsRune(v, 0) { + return fmt.Errorf("%w: env variable %q contains NUL byte", ErrBadRequest, k) + } + } + return nil +} + +// FilterPanelEnv strips forbidden variables from an ambient/session env slice before +// sending additive env vars from the panel to the runner (the runner still validates strictly). +func FilterPanelEnv(kvs []string) map[string]string { + out := make(map[string]string) + for _, kv := range kvs { + k, v, ok := strings.Cut(kv, "=") + if !ok || !envNameRE.MatchString(k) || IsForbiddenEnvName(k) || len(v) > MaxEnvValueBytes || strings.ContainsRune(v, 0) { + continue + } + // Never override worker proxy or home variables from panel process env. + switch strings.ToUpper(k) { + case "PATH", "HOME", "XDG_CACHE_HOME", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY": + continue + } + out[k] = v + } + return out +} + +// ValidateExecRequest validates and normalizes an ExecRequest in place. +func ValidateExecRequest(req *ExecRequest) error { + if req == nil { + return fmt.Errorf("%w: missing request body", ErrBadRequest) + } + if len(req.Argv) == 0 || strings.TrimSpace(req.Argv[0]) == "" { + return fmt.Errorf("%w: argv must be non-empty", ErrBadRequest) + } + for i, arg := range req.Argv { + if strings.ContainsRune(arg, 0) { + return fmt.Errorf("%w: argv[%d] contains NUL byte", ErrBadRequest, i) + } + } + if req.TimeoutMS < 0 || req.TimeoutMS > MaxTimeoutMS { + return fmt.Errorf("%w: timeout_ms must be between 0 and %d", ErrBadRequest, MaxTimeoutMS) + } + if req.TimeoutMS == 0 { + req.TimeoutMS = DefaultTimeoutMS + } + if strings.TrimSpace(req.Workdir) == "" { + req.Workdir = "/workspace" + } else { + clean := path.Clean(req.Workdir) + if clean != "/workspace" && !strings.HasPrefix(clean, "/workspace/") { + return fmt.Errorf("%w: workdir must stay inside /workspace (got %q)", ErrBadRequest, req.Workdir) + } + req.Workdir = clean + } + return ValidateEnv(req.Env) +} diff --git a/server/assembly.go b/server/assembly.go index 1b19cbb9e..f9daceb8b 100644 --- a/server/assembly.go +++ b/server/assembly.go @@ -5,11 +5,13 @@ import ( "encoding/json" "io" "log" + "os" "path/filepath" "strings" "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/artex/intercept" "github.com/Autumn-27/artex/traffic" "github.com/Autumn-27/norma/skill" actool "github.com/Autumn-27/norma/tool" @@ -98,7 +100,15 @@ func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.Cor // The browser MCP drives the shared browser the operator can watch and // take over, instead of a private headless one (sharedbrowser.go). dial, shared := m, false + if agent.SandboxRequired() && (m.Transport == "" || m.Transport == "stdio") { + log.Printf("[sandbox] skipping local stdio MCP %q on panel (ARTEX_SANDBOX=required: panel never runs local agent subprocesses)", m.Name) + continue + } if browser != nil && isSharedBrowserMCP(m) { + if agent.SandboxRequired() && !sharedBrowserAllowedInSandbox(ctx, m) { + log.Printf("[sandbox] skipping direct-network shared browser MCP %q (ARTEX_SANDBOX=required requires target_gate=on or explicit browser/egress proxy)", m.Name) + continue + } var revoke func() dial, shared, revoke = prepareSharedBrowserMCP(ctx, browser, m, browserRunInfo, browserHolder) if revoke != nil { @@ -366,7 +376,7 @@ func wireTools(pg *db.DB, domainReg map[string]actool.CoreTool) { // web_search), NOT by tools-table binding. Orchestration-only agents (auto, // mainagent) have no shell execution tools and never receive shell_* even if // an older DB had interactive_shell=true. See docs/interactive-shell-design.md §14.2. - if agentKey != "auto" && agentKey != "mainagent" && !actool.InteractiveShellDisabled() { + if agentKey != "auto" && agentKey != "mainagent" && !actool.InteractiveShellDisabled() && !agent.SandboxRequired() { if a, err := pg.GetAgentByKey(agentKey); err == nil && a != nil && a.InteractiveShell { out = append(out, actool.ShellSessionTools()...) for i, t := range out { @@ -428,3 +438,24 @@ func jsonStrMap(raw json.RawMessage) map[string]string { } return out } + +// sharedBrowserAllowedInSandbox requires either the task's target gate to be +// enabled or an explicit proxy to be configured on the browser/panel before +// attaching the opt-in panel-hosted shared browser in ARTEX_SANDBOX=required mode. +func sharedBrowserAllowedInSandbox(ctx context.Context, m *db.MCPServer) bool { + if scope, ok := intercept.TargetScopeFromContext(ctx); ok && scope.Enabled != nil && scope.Enabled() { + return true + } + if m != nil { + proxy, _ := browserMCPProxy(jsonStrSlice(m.Args), jsonStrMap(m.Env)) + if strings.TrimSpace(proxy) != "" { + return true + } + } + for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ARTEX_EGRESS_PROXY"} { + if strings.TrimSpace(os.Getenv(k)) != "" { + return true + } + } + return false +} diff --git a/server/customtool.go b/server/customtool.go index cd4442816..4d3b094f3 100644 --- a/server/customtool.go +++ b/server/customtool.go @@ -3,8 +3,10 @@ package server import ( "bytes" "context" + "crypto/rand" "crypto/tls" "crypto/x509" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -18,12 +20,14 @@ import ( "strings" "time" + "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/config" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/egress" "github.com/Autumn-27/artex/guard" "github.com/Autumn-27/artex/intercept" "github.com/Autumn-27/artex/notify" + "github.com/Autumn-27/artex/sandbox" "github.com/Autumn-27/norma/permission" actool "github.com/Autumn-27/norma/tool" ) @@ -464,7 +468,32 @@ func (s *Server) runCommandTool(ctx context.Context, key string, execRaw json.Ra ctx, cancel = context.WithTimeout(ctx, timeoutOr(spec.TimeoutMs, 120000)) defer cancel() } - res, err := actool.NewBash().Call(ctx, bashIn, tc) + var res actool.Result + var err error + if agent.SandboxRequired() { + workDir := "" + var env []string + if tc != nil { + workDir = tc.WorkingDir + env = tc.Env + } + sresp, serr := agent.ExecInSandbox(ctx, []string{"bash", "-c", cmd}, workDir, spec.TimeoutMs, env) + if serr != nil { + res = actool.Errorf(fmt.Sprintf("sandbox command tool failed (ARTEX_SANDBOX=required, no local fallback): %v", serr)) + } else { + out := sresp.Stdout + if sresp.Stderr != "" { + out += "\n" + sresp.Stderr + } + if sresp.ExitCode != 0 || sresp.TimedOut { + res = actool.Errorf(fmt.Sprintf("%s\n\n[exit code %d]", actool.Capture(tc, out), sresp.ExitCode)) + } else { + res = actool.Text(actool.Capture(tc, out)) + } + } + } else { + res, err = actool.NewBash().Call(ctx, bashIn, tc) + } if err == nil && !res.IsError { intercept.RecordStatefulReadOnly(ctx, key, nil, cmd, "") } @@ -495,7 +524,26 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw if err := intercept.CheckStatefulTool(ctx, key, rawParams, spec.Code, ""); err != nil { return actool.Errorf(err.Error()), nil } - body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeoutOr(spec.TimeoutMs, 120000), s.execPriv) + var body string + var err error + if agent.SandboxRequired() { + // Stage script code and params JSON as temporary workspace files (via os.OpenRoot + // to block symlink escape) so large scripts/params never hit argv E2BIG. + sresp, serr := execScriptInSandbox(ctx, key, spec.Code, rawParams, workDir, spec.TimeoutMs, sessionEnv) + if serr != nil { + err = fmt.Errorf("sandbox script tool failed (ARTEX_SANDBOX=required, no local fallback): %w", serr) + } else { + body = sresp.Stdout + if sresp.Stderr != "" { + body += "\n" + sresp.Stderr + } + if sresp.ExitCode != 0 || sresp.TimedOut { + err = fmt.Errorf("%s\n[exit code %d]", strings.TrimSpace(body), sresp.ExitCode) + } + } + } else { + body, err = execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeoutOr(spec.TimeoutMs, 120000), s.execPriv) + } if err != nil { return actool.Errorf(err.Error()), nil } @@ -766,3 +814,56 @@ func scalarStr(v any) (string, bool) { return "", false } } + +// execScriptInSandbox stages a custom Python script and its JSON parameters into +// symlink-confined temporary files inside the task workspace and invokes python3 +// with a short fixed-length argv (preventing E2BIG on large scripts or inputs). +func execScriptInSandbox(ctx context.Context, key, code string, rawParams []byte, workDir string, timeoutMS int, sessionEnv []string) (sandbox.ExecResponse, error) { + info, ok := agent.SandboxRunInfoFromContext(ctx) + baseDir := info.TaskDir + if !ok || strings.TrimSpace(baseDir) == "" { + baseDir = workDir + } + if strings.TrimSpace(baseDir) == "" { + return sandbox.ExecResponse{}, errors.New("sandbox script tool: missing task workspace directory") + } + if err := os.MkdirAll(baseDir, 0o775); err != nil { + return sandbox.ExecResponse{}, fmt.Errorf("sandbox script tool: mkdir workspace: %w", err) + } + root, err := os.OpenRoot(baseDir) + if err != nil { + return sandbox.ExecResponse{}, fmt.Errorf("sandbox script tool: open workspace root: %w", err) + } + defer root.Close() + + var nonce [8]byte + _, _ = rand.Read(nonce[:]) + tag := hex.EncodeToString(nonce[:]) + scriptName := ".artex-tool-" + tag + ".py" + paramsName := ".artex-tool-" + tag + ".json" + + writeFile := func(name string, data []byte) error { + f, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) + if err != nil { + return err + } + _, werr := f.Write(data) + cerr := f.Close() + if werr != nil { + return werr + } + return cerr + } + if err := writeFile(scriptName, []byte(code)); err != nil { + return sandbox.ExecResponse{}, fmt.Errorf("sandbox script tool: stage script: %w", err) + } + defer root.Remove(scriptName) + if err := writeFile(paramsName, rawParams); err != nil { + return sandbox.ExecResponse{}, fmt.Errorf("sandbox script tool: stage params: %w", err) + } + defer root.Remove(paramsName) + + wrapper := "import sys; p, s = sys.argv[1], sys.argv[2]; sys.stdin = open(p, 'r', encoding='utf-8'); code = open(s, 'r', encoding='utf-8').read(); exec(compile(code, '', 'exec'), {'__name__': '__main__'})" + argv := []string{"python3", "-c", wrapper, "/workspace/" + paramsName, "/workspace/" + scriptName} + return agent.ExecInSandbox(ctx, argv, workDir, timeoutMS, sessionEnv) +} diff --git a/server/engine.go b/server/engine.go index def96866b..1056064a6 100644 --- a/server/engine.go +++ b/server/engine.go @@ -15,6 +15,7 @@ import ( "github.com/Autumn-27/artex/agent" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" + "github.com/Autumn-27/artex/sandbox" "github.com/Autumn-27/norma/harness" "github.com/Autumn-27/norma/llm" "github.com/jackc/pgx/v5/pgconn" @@ -96,6 +97,9 @@ func retryableWorkerModelError(reason harness.TerminalReason, err error) bool { type Engine struct { statefulGuardOnce sync.Once statefulGuard *intercept.StatefulTargetGuard + sandboxClient SandboxClient + sandboxMode string + sandboxDataDir string m *Manager debounce time.Duration @@ -186,6 +190,35 @@ func (e *Engine) nextPlannerRound(taskID string) int { return n } +// SetSandbox configures the runner client and mode used by the engine. +func (e *Engine) SetSandbox(client SandboxClient, mode, dataDir string) { + e.sandboxClient = client + e.sandboxMode = mode + e.sandboxDataDir = dataDir +} + +func (e *Engine) killSandboxTask(taskID string) { + if e.sandboxClient == nil || e.sandboxMode != sandbox.ModeRequired { + return + } + kctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := e.sandboxClient.Kill(kctx, taskID); err != nil && !errors.Is(err, sandbox.ErrNotFound) { + log.Printf("[sandbox] kill task %s: %v", taskID, err) + } +} + +func (e *Engine) withTaskSandbox(ctx context.Context, taskID string) context.Context { + if e.sandboxMode != sandbox.ModeRequired { + return ctx + } + var pg *db.DB + if e.m != nil { + pg = e.m.pg + } + return agent.WithSandboxRunInfo(ctx, taskSandboxRunInfo(pg, e.sandboxDataDir, taskID)) +} + // Pause stops a task: marks it paused AND cancels any in-flight planner/worker run // for it (a long worker.Execute would otherwise keep going until it finishes). // SetKillSwitchConfig configures the data directory and executor privilege used @@ -206,7 +239,11 @@ func (e *Engine) killLocalTask(taskID string) { func (e *Engine) Pause(taskID string, cause error) { e.paused.Store(taskID, true) e.cancelExec(taskID, cause) - e.killLocalTask(taskID) + if e.sandboxMode == sandbox.ModeRequired { + e.killSandboxTask(taskID) + } else { + e.killLocalTask(taskID) + } } // BeginDelete installs an execution barrier before task data/files are removed. @@ -222,7 +259,11 @@ func (e *Engine) BeginDelete(taskID string) bool { e.paused.Store(taskID, true) e.deleteMu.Unlock() e.cancelExec(taskID, agent.AbortTaskDeleted) - e.killLocalTask(taskID) + if e.sandboxMode == sandbox.ModeRequired { + e.killSandboxTask(taskID) + } else { + e.killLocalTask(taskID) + } return true } @@ -338,6 +379,7 @@ func (e *Engine) StopTask(taskID string) { e.deleteMu.Unlock() e.cancelExec(taskID, agent.AbortTaskDeleted) + e.killSandboxTask(taskID) e.runtimeMu.Lock() rt := e.runtimes[taskID] if rt != nil { @@ -889,6 +931,33 @@ func (e *Engine) ReadyFor(t *Task) bool { // but no-op until an LLM is configured (so a task created while idle picks up // automatically once LLM is set from the UI). func (e *Engine) Run(ctx context.Context, t *Task) { + if e.sandboxMode == sandbox.ModeRequired { + if e.sandboxClient == nil { + log.Printf("[sandbox] refusing to start task %s: runner client unavailable (ARTEX_SANDBOX=required)", t.ID) + e.paused.Store(t.ID, true) + return + } + hctx, cancel := context.WithTimeout(ctx, 5*time.Second) + h, err := e.sandboxClient.Health(hctx) + cancel() + if err != nil || !h.OK || !h.Docker { + log.Printf("[sandbox] refusing to start task %s: runner unavailable (err=%v ok=%v docker=%v)", t.ID, err, h.OK, h.Docker) + e.paused.Store(t.ID, true) + if t.Store != nil { + _, _ = t.Store.AppendActivity(db.Activity{ + Kind: "system", + IsError: true, + Summary: "sandbox runner unavailable (ARTEX_SANDBOX=required): task paused, no local fallback", + }) + } + return + } + } else if e.sandboxMode == sandbox.ModeOff && t.Store != nil { + _, _ = t.Store.AppendActivity(db.Activity{ + Kind: "system", + Summary: "sandbox=off: task running without container sandbox (ARTEX_SANDBOX=off)", + }) + } workers := e.m.Workers() e.deleteMu.RLock() if e.IsDeleting(t.ID) { @@ -1113,7 +1182,7 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) { } } taskIDInt, _ := strconv.ParseInt(t.ID, 10, 64) - pctx := e.budgetRoundCtx(e.plannerGateContext(ectx, t, intercept.DefaultTargetWaitBound), t, false) + pctx := e.withTaskSandbox(e.budgetRoundCtx(e.plannerGateContext(ectx, t, intercept.DefaultTargetWaitBound), t, false), t.ID) resets := t.planResets.Load() e.BeginLLMCall(t.ID) met, reason, err := planner.Plan(pctx, taskIDInt, e.m.assets, t.Store, t.Goal, triggers, t.TargetGuard.Hooks(), emit) @@ -1365,6 +1434,7 @@ func (e *Engine) runIntent(ctx context.Context, t *Task, name string, worker *ag label := fmt.Sprintf("%s · #%d", name, iid) workCtx = intercept.WithTaskContext(workCtx, t.ID, label, taskEmit) workCtx = intercept.WithTargetScope(workCtx, t.targetScope(intercept.DefaultTargetWaitBound)) + workCtx = e.withTaskSandbox(workCtx, t.ID) if sg := e.statefulGuardForTask(); sg != nil { workCtx = intercept.WithStatefulGuard(workCtx, sg) workCtx = intercept.WithStatefulActor(workCtx, t.ID, iid) diff --git a/server/intercept.go b/server/intercept.go index 179d0c44b..ba63598de 100644 --- a/server/intercept.go +++ b/server/intercept.go @@ -16,6 +16,7 @@ import ( "github.com/Autumn-27/artex/guard" "github.com/Autumn-27/artex/intercept" "github.com/Autumn-27/artex/llmrec" + "github.com/Autumn-27/artex/sandbox" "github.com/Autumn-27/norma/llm" ) @@ -423,10 +424,17 @@ func (s *Server) interceptDecide(w http.ResponseWriter, r *http.Request) { writeErr(w, 500, err.Error()) return } - writeJSON(w, 200, map[string]any{"ok": true}) + resp := map[string]any{"ok": true} + if req.Decision == "allowed" && s.sandboxMode == sandbox.ModeRequired { + resp["sandbox_egress_note"] = sandboxGateApprovalNote + } + writeJSON(w, 200, resp) } // maxBatchDecide bounds one batch decision request. + +const sandboxGateApprovalNote = "Target-gate approval clears the tool approval gate only; in ARTEX_SANDBOX=required mode, worker egress still requires an operator-approved Task Scope entry (POST /api/tasks/{id}/scope) or task allow rule." + const maxBatchDecide = 100 type batchDecideResult struct { @@ -481,7 +489,11 @@ func (s *Server) interceptBatchDecide(w http.ResponseWriter, r *http.Request) { } results = append(results, res) } - writeJSON(w, 200, map[string]any{"decided": decided, "failed": len(ids) - decided, "results": results}) + resp := map[string]any{"decided": decided, "failed": len(ids) - decided, "results": results} + if req.Decision == "allowed" && decided > 0 && s.sandboxMode == sandbox.ModeRequired { + resp["sandbox_egress_note"] = sandboxGateApprovalNote + } + writeJSON(w, 200, resp) } // alwaysAllowPriority places "always allow" rules below every default and diff --git a/server/orchestration.go b/server/orchestration.go index 72e22968e..fabd02e55 100644 --- a/server/orchestration.go +++ b/server/orchestration.go @@ -359,6 +359,7 @@ func (s *Server) toolSpawnTask() actool.CoreTool { t, err := s.m.CreateTaskWithOptions(a.Description, a.Goal, db.TaskCreateOptions{ SourceTaskIDs: sourceIDs, CompanyIDs: companyIDs, + CompanyScopeByAgent: true, LLMProfileIDs: llmIDs, TimeoutSeconds: a.TimeoutSeconds, PlanHeartbeatSeconds: a.PlanHeartbeatSeconds, diff --git a/server/sandbox.go b/server/sandbox.go new file mode 100644 index 000000000..9652cc841 --- /dev/null +++ b/server/sandbox.go @@ -0,0 +1,178 @@ +package server + +import ( + "context" + "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) +} + +// 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 { + info := agent.SandboxRunInfo{ + TaskID: taskID, + TaskDir: filepath.Join(dataDir, "tasks", taskID), + } + if pg == nil { + return info + } + tid, err := strconv.ParseInt(taskID, 10, 64) + if err != nil || tid <= 0 { + return info + } + 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 rows.Scan(&kind, &dom, &netStr, &val, &compID) == nil { + 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) + } + } + } + } + } + // Expand company-scoped tasks (task_scope.kind='company') from company_scope + // and attributed company assets so company-scoped tasks reach their targets. + for _, cid := range companyIDs { + if rows, err := pg.Query(`SELECT kind, COALESCE(domain,''), COALESCE(net::text,'') FROM company_scope WHERE company_id=$1`, cid); err == nil { + for rows.Next() { + var kind, dom, netStr string + if rows.Scan(&kind, &dom, &netStr) == nil { + switch kind { + case "domain": + addDom(dom) + case "ip", "cidr": + addCIDR(netStr) + } + } + } + rows.Close() + } + if rows, err := pg.Query(`SELECT COALESCE(root_domain,''), COALESCE(domain,''), COALESCE(ip,'') FROM assets WHERE company_id=$1`, cid); err == nil { + for rows.Next() { + var rdom, dom, ip string + if rows.Scan(&rdom, &dom, &ip) == nil { + if rdom != "" { + addDom(rdom) + } + if dom != "" { + addDom(dom) + } + if ip != "" { + addCIDR(ip) + } + } + } + rows.Close() + } + } + 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 rows.Scan(&kind, &pat) == nil { + switch kind { + case "exact_domain", "domain_suffix": + addDom(pat) + case "cidr", "ip": + addCIDR(pat) + } + } + } + } + return info +} diff --git a/server/sandbox_scope_drift_test.go b/server/sandbox_scope_drift_test.go new file mode 100644 index 000000000..e20306b16 --- /dev/null +++ b/server/sandbox_scope_drift_test.go @@ -0,0 +1,346 @@ +package server + +import ( + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "net/netip" + "net/url" + "os" + "strconv" + "strings" + "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" +) + +// TestSandboxScopeDriftBlockedAcrossProxyWebFetchAndBrowser verifies that +// agent-added (add_task_scope / AddAgentScope) and auto-added (insert_assets / +// AddAutoScope) task_scope rows are strictly coverage-only and NEVER grant +// egress to the sandbox proxy, WebFetch, or shared browser. Only operator- +// approved rows (AddOperatorScope / operator API) and operator-selected +// companies (TaskCreateOptions.CompanyIDs) grant egress, with strict domain +// suffix matching and deny-by-default when no approved scope exists. +func TestSandboxScopeDriftBlockedAcrossProxyWebFetchAndBrowser(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() }) + + agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired}) + t.Cleanup(func() { agent.SetSandboxExecutor(nil) }) + + // Local canary HTTP server representing a target IP reachable only when + // explicitly in ScopeCIDRs. + canary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + _, _ = w.Write([]byte("CANARY_REACHED")) + })) + t.Cleanup(canary.Close) + canaryHost, canaryPort, err := net.SplitHostPort(strings.TrimPrefix(canary.URL, "http://")) + if err != nil { + t.Fatal(err) + } + canaryURL := "http://" + net.JoinHostPort(canaryHost, canaryPort) + "/probe" + + // Helper: build a real sandbox HTTP egress proxy + WebFetch + sharedBrowserTool + // directly from taskSandboxRunInfo(pg, dataDir, taskID). + buildEnforcers := func(t *testing.T, taskID int64) ( + info agent.SandboxRunInfo, + proxyCheck func(rawURL string) (int, error), + webFetchCheck func(rawURL string) (bool, string), + browserCheck func(rawURL string) (bool, string), + ) { + t.Helper() + info = taskSandboxRunInfo(pg, t.TempDir(), strconv.FormatInt(taskID, 10)) + pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil) + if err != nil { + t.Fatalf("NewEgressPolicy: %v", err) + } + // Deterministic offline resolver for domain suffix tests (resolves to public TEST-NET-3 IP). + pol.Resolver = func(_ context.Context, host string) ([]netip.Addr, error) { + return []netip.Addr{netip.MustParseAddr("203.0.113.99")}, nil + } + // Dialer that routes 203.0.113.99 to our local canary so allowed domain + // requests succeed without external internet access. + pol.Dialer = func(ctx context.Context, network, addr string) (net.Conn, error) { + h, _, _ := net.SplitHostPort(addr) + var d net.Dialer + if h == "203.0.113.99" { + return d.DialContext(ctx, network, net.JoinHostPort(canaryHost, canaryPort)) + } + return d.DialContext(ctx, network, addr) + } + + proxy := sandbox.NewEgressProxy(pol) + proxySrv := httptest.NewServer(proxy) + t.Cleanup(proxySrv.Close) + proxyURL, _ := url.Parse(proxySrv.URL) + httpClient := &http.Client{ + Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, + Timeout: 5 * time.Second, + } + proxyCheck = func(rawURL string) (int, error) { + resp, err := httpClient.Get(rawURL) + if err != nil { + return 0, err + } + defer resp.Body.Close() + return resp.StatusCode, nil + } + + ctx := agent.WithSandboxRunInfo(context.Background(), info) + wf := agent.NewWebFetchTool(ctx, "", "") + webFetchCheck = func(rawURL string) (bool, string) { + in, _ := json.Marshal(map[string]any{"url": rawURL}) + res, err := wf.Call(ctx, in, &actool.ToolContext{}) + if err != nil { + return false, err.Error() + } + return !res.IsError, res.Flatten() + } + + innerBrowser := actool.Build(actool.Spec{ + Name: "browser_navigate", + Description: "navigate", + Run: func(_ context.Context, _ json.RawMessage, _ *actool.ToolContext) (actool.Result, error) { + return actool.Text("NAVIGATED"), nil + }, + }) + br := &sharedBrowserTool{CoreTool: innerBrowser} + browserCheck = func(rawURL string) (bool, string) { + in, _ := json.Marshal(map[string]any{"url": rawURL}) + res, err := br.Call(ctx, in, &actool.ToolContext{}) + if err != nil { + return false, err.Error() + } + return !res.IsError, res.Flatten() + } + return + } + + assertAllDenied := func(t *testing.T, label, targetURL string, + proxyCheck func(string) (int, error), + webFetchCheck func(string) (bool, string), + browserCheck func(string) (bool, string), + ) { + t.Helper() + if code, err := proxyCheck(targetURL); err == nil && code != http.StatusForbidden { + t.Fatalf("%s: proxy unexpectedly allowed %s (HTTP %d)", label, targetURL, code) + } + if ok, body := webFetchCheck(targetURL); ok { + t.Fatalf("%s: WebFetch unexpectedly allowed %s (body=%q)", label, targetURL, body) + } else if !strings.Contains(body, "target-gate approval only clears the tool gate") { + t.Fatalf("%s: WebFetch denial missing non-silent gate/scope guidance: %q", label, body) + } + if ok, body := browserCheck(targetURL); ok { + t.Fatalf("%s: shared browser unexpectedly allowed %s (body=%q)", label, targetURL, body) + } else if !strings.Contains(body, "target-gate approval only clears the tool gate") { + t.Fatalf("%s: browser denial missing non-silent gate/scope guidance: %q", label, body) + } + } + + suffix := strconv.FormatInt(time.Now().UnixNano(), 10) + as := pg.Assets() + + // ----------------------------------------------------------------------- + // Case 1: Unscoped task + add_task_scope (AddAgentScope) + insert_assets + // (AddAutoScope) + agent-added company -> ALL DENIED across proxy, + // WebFetch, and shared browser. + // ----------------------------------------------------------------------- + tUnscoped, err := pg.CreateTaskWithOptions("unscoped-drift-"+suffix, "goal", db.TaskCreateOptions{}) + if err != nil { + t.Fatalf("CreateTaskWithOptions unscoped: %v", err) + } + + agentDom := "agent-drift-" + suffix + ".test" + autoDom := "auto-drift-" + suffix + ".test" + agentCompDom := "agent-co-" + suffix + ".test" + agentCompName := "AgentInjectedCo-" + suffix + _, _, _, _, _, err = pg.Companies().CreateCompanyWithScope( + agentCompName, "", + []db.ScopeInput{ + {Kind: "domain", Value: agentCompDom}, + {Kind: "cidr", Value: canaryHost + "/32"}, + }, + "test", + ) + if err != nil { + t.Fatalf("CreateCompanyWithScope agentComp: %v", err) + } + + // Simulate prompt-injected agent calling add_task_scope & insert_assets: + if ts, err := as.AddAgentScope(tUnscoped.ID, "root_domain", agentDom, "injected domain", "agent"); err != nil || ts.ApprovedByOperator { + t.Fatalf("AddAgentScope domain: ts=%+v err=%v (must be approved_by_operator=false)", ts, err) + } + if ts, err := as.AddAgentScope(tUnscoped.ID, "ip", canaryHost, "injected ip", "agent"); err != nil || ts.ApprovedByOperator { + t.Fatalf("AddAgentScope ip: ts=%+v err=%v (must be approved_by_operator=false)", ts, err) + } + if ts, err := as.AddAgentScope(tUnscoped.ID, "company", agentCompName, "injected company", "agent"); err != nil || ts.ApprovedByOperator { + t.Fatalf("AddAgentScope company: ts=%+v err=%v (must be approved_by_operator=false)", ts, err) + } + // Even passing source="manual" to AddAgentScope must NOT grant operator approval. + if ts, err := as.AddAgentScope(tUnscoped.ID, "root_domain", "forged-manual-"+suffix+".test", "spoof", "manual"); err != nil || ts.ApprovedByOperator { + t.Fatalf("AddAgentScope manual spoof must stay approved_by_operator=false: ts=%+v err=%v", ts, err) + } + if err := as.AddAutoScope(tUnscoped.ID, "root_domain", autoDom, "", ""); err != nil { + t.Fatalf("AddAutoScope domain: %v", err) + } + if err := as.AddAutoScope(tUnscoped.ID, "ip", "", "", canaryHost); err != nil { + t.Fatalf("AddAutoScope ip: %v", err) + } + + info1, proxy1, wf1, br1 := buildEnforcers(t, tUnscoped.ID) + if len(info1.ScopeDomains) != 0 || len(info1.ScopeCIDRs) != 0 { + t.Fatalf("scope drift! unapproved agent/auto rows leaked into sandbox allowlist: domains=%v cidrs=%v", info1.ScopeDomains, info1.ScopeCIDRs) + } + for _, target := range []string{ + canaryURL, + "http://" + agentDom + "/", + "http://" + autoDom + "/", + "http://" + agentCompDom + "/", + "http://forged-manual-" + suffix + ".example.com/", + "http://169.254.169.254/latest/meta-data/", + } { + assertAllDenied(t, "unapproved-drift", target, proxy1, wf1, br1) + } + + // ----------------------------------------------------------------------- + // Case 2: Operator-approved rows (AddOperatorScope) -> ALLOWED, with + // strict domain suffix enforcement (sub.approved allowed, evil-approved denied). + // ----------------------------------------------------------------------- + approvedDom := "approved-" + suffix + ".test" + if ts, err := as.AddOperatorScope(tUnscoped.ID, "root_domain", approvedDom, "operator approved"); err != nil || !ts.ApprovedByOperator { + t.Fatalf("AddOperatorScope domain: ts=%+v err=%v", ts, err) + } + // Promoting the previously agent-added canaryHost IP via AddOperatorScope succeeds. + if ts, err := as.AddOperatorScope(tUnscoped.ID, "ip", canaryHost, "operator approved canary IP"); err != nil || !ts.ApprovedByOperator { + t.Fatalf("AddOperatorScope ip promote: ts=%+v err=%v", ts, err) + } + + _, proxy2, wf2, br2 := buildEnforcers(t, tUnscoped.ID) + // Operator-approved IP allowed across proxy, WebFetch, and browser: + if code, err := proxy2(canaryURL); err != nil || code != http.StatusOK { + t.Fatalf("proxy should allow operator-approved IP %s, got code=%d err=%v", canaryURL, code, err) + } + if ok, body := wf2(canaryURL); !ok || !strings.Contains(body, "CANARY_REACHED") { + t.Fatalf("WebFetch should allow operator-approved IP %s, got ok=%v body=%q", canaryURL, ok, body) + } + if ok, body := br2(canaryURL); !ok || body != "NAVIGATED" { + t.Fatalf("browser should allow operator-approved IP %s, got ok=%v body=%q", canaryURL, ok, body) + } + // Operator-approved domain and strict subdomain allowed: + for _, okDomURL := range []string{"http://" + approvedDom + "/x", "http://sub." + approvedDom + "/y"} { + if code, err := proxy2(okDomURL); err != nil || code != http.StatusOK { + t.Fatalf("proxy should allow operator-approved domain/suffix %s, got code=%d err=%v", okDomURL, code, err) + } + if ok, body := br2(okDomURL); !ok || body != "NAVIGATED" { + t.Fatalf("browser should allow operator-approved domain/suffix %s, got ok=%v body=%q", okDomURL, ok, body) + } + } + // Strict domain suffix enforcement: lookalike prefix/suffix domains DENIED! + for _, badSuffixURL := range []string{ + "http://evil" + approvedDom + "/", + "http://evil-" + approvedDom + "/", + "http://" + approvedDom + ".attacker.invalid/", + "http://" + agentDom + "/", + "http://" + agentCompDom + "/", + } { + assertAllDenied(t, "suffix-enforcement", badSuffixURL, proxy2, wf2, br2) + } + + // ----------------------------------------------------------------------- + // Case 3: Operator-selected company (TaskCreateOptions.CompanyIDs) -> + // ALLOWED for company domain/CIDR, while agent-added company on same task + // remains DENIED. + // ----------------------------------------------------------------------- + opCompDom := "op-co-" + suffix + ".test" + opCompID, _, _, _, _, err := pg.Companies().CreateCompanyWithScope( + "OperatorSelectedCo-"+suffix, "", + []db.ScopeInput{ + {Kind: "domain", Value: opCompDom}, + {Kind: "cidr", Value: canaryHost + "/32"}, + }, + "test", + ) + if err != nil { + t.Fatalf("CreateCompanyWithScope opComp: %v", err) + } + tOpComp, err := pg.CreateTaskWithOptions("op-company-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{opCompID}, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions opComp: %v", err) + } + // Agent tries to attach a second unapproved company to the same task -> must NOT widen egress! + if ts, err := as.AddAgentScope(tOpComp.ID, "company", agentCompName, "agent widen company", "agent"); err != nil || ts.ApprovedByOperator { + t.Fatalf("AddAgentScope second company: ts=%+v err=%v", ts, err) + } + + _, proxy3, wf3, br3 := buildEnforcers(t, tOpComp.ID) + // Operator-selected company domain/subdomain and IP allowed: + if code, err := proxy3("http://api." + opCompDom + "/v1"); err != nil || code != http.StatusOK { + t.Fatalf("proxy should allow operator-selected company subdomain, got code=%d err=%v", code, err) + } + if ok, body := br3("https://api." + opCompDom + "/v1"); !ok || body != "NAVIGATED" { + t.Fatalf("browser should allow operator-selected company subdomain, got ok=%v body=%q", ok, body) + } + if ok, body := wf3(canaryURL); !ok || !strings.Contains(body, "CANARY_REACHED") { + t.Fatalf("WebFetch should allow operator-selected company CIDR, got ok=%v body=%q", ok, body) + } + // Agent-added second company and lookalike suffix DENIED: + assertAllDenied(t, "agent-added-second-company", "http://"+agentCompDom+"/", proxy3, wf3, br3) + assertAllDenied(t, "op-company-bad-suffix", "http://evil-"+opCompDom+"/", proxy3, wf3, br3) + + // ----------------------------------------------------------------------- + // Case 4: Operator RetargetTask sets approved_by_operator=true for newHost + // and agent-spawned task with CompanyScopeByAgent=true leaves it false. + // ----------------------------------------------------------------------- + oldRetargetHost := "old-inst-" + suffix + ".test" + newRetargetHost := "new-inst-" + suffix + ".test" + tRetarget, err := pg.CreateTaskWithOptions("retarget-"+suffix, "Test https://"+oldRetargetHost, db.TaskCreateOptions{}) + if err != nil { + t.Fatalf("CreateTaskWithOptions retarget: %v", err) + } + if _, err := as.AddOperatorScope(tRetarget.ID, "subdomain", oldRetargetHost, "operator"); err != nil { + t.Fatalf("AddOperatorScope old host: %v", err) + } + if _, err := pg.RetargetTask(context.Background(), tRetarget.ID, oldRetargetHost, "https://"+newRetargetHost); err != nil { + t.Fatalf("RetargetTask: %v", err) + } + _, proxy4, wf4, br4 := buildEnforcers(t, tRetarget.ID) + if code, err := proxy4("http://" + newRetargetHost + "/"); err != nil || code != http.StatusOK { + t.Fatalf("proxy should allow operator-retargeted host %s, got code=%d err=%v", newRetargetHost, code, err) + } + if ok, body := br4("https://" + newRetargetHost + "/"); !ok || body != "NAVIGATED" { + t.Fatalf("browser should allow operator-retargeted host %s, got ok=%v body=%q", newRetargetHost, ok, body) + } + assertAllDenied(t, "old-retargeted-host-removed", "http://"+oldRetargetHost+"/", proxy4, wf4, br4) + + // Agent-spawned task (spawn_task sets CompanyScopeByAgent=true) must NOT mint + // operator-approved egress for an arbitrary company. + tAgentSpawn, err := pg.CreateTaskWithOptions("agent-spawn-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{opCompID}, + CompanyScopeByAgent: true, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions agent-spawn: %v", err) + } + info5, proxy5, wf5, br5 := buildEnforcers(t, tAgentSpawn.ID) + if len(info5.ScopeDomains) != 0 || len(info5.ScopeCIDRs) != 0 { + t.Fatalf("agent-spawned task leaked company scope into sandbox allowlist: domains=%v cidrs=%v", info5.ScopeDomains, info5.ScopeCIDRs) + } + assertAllDenied(t, "agent-spawned-company", "http://"+opCompDom+"/", proxy5, wf5, br5) + assertAllDenied(t, "agent-spawned-company-ip", canaryURL, proxy5, wf5, br5) +} diff --git a/server/sandbox_test.go b/server/sandbox_test.go new file mode 100644 index 000000000..952dcf932 --- /dev/null +++ b/server/sandbox_test.go @@ -0,0 +1,340 @@ +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"}, + }) + + 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 company_scope domains/CIDRs and attributed company assets into the +// task's sandbox egress allowlist. +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", + ) + 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, ",") + for _, wantDom := range []string{scopeDom, subDom, rootDom} { + if !strings.Contains(domJoined, wantDom) { + t.Fatalf("expected company domain %q in ScopeDomains=%v", wantDom, info.ScopeDomains) + } + } + for _, wantCIDR := range []string{"198.51.100.0/24", "203.0.113.42"} { + if !strings.Contains(cidrJoined, wantCIDR) { + t.Fatalf("expected company CIDR/IP %q in ScopeCIDRs=%v", wantCIDR, 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)) + } +} diff --git a/server/server.go b/server/server.go index 38b9a7cc6..4f7141051 100644 --- a/server/server.go +++ b/server/server.go @@ -56,8 +56,10 @@ type Server struct { scrubSecrets bool // drop ARTEX_PG_DSN and the API keys from the environment once read (binary only) - execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own - isolation IsolationStatus // result of the startup isolation self-test (isolation.go); zero when not run + execPriv ExecPrivilege // identity agent processes run under; zero keeps the server's own + isolation IsolationStatus + sandboxMode string + sandboxClient SandboxClient // result of the startup isolation self-test (isolation.go); zero when not run chatBridges *chatBridgeRunner // inbound chat bridges (issue #5); nil without PostgreSQL @@ -216,6 +218,17 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi o(s) } s.engine.SetKillSwitchConfig(dataDir, s.execPriv) + s.engine.SetSandbox(s.sandboxClient, s.sandboxMode, dataDir) + if s.sandboxMode != "" { + agent.SetSandboxExecutor(&agent.SandboxExecutor{ + Mode: s.sandboxMode, + Runner: s.sandboxClient, + OnUnavailable: func(taskID string, err error) { + log.Printf("[sandbox] runner unavailable for task %s (%v): pausing task (no local fallback)", taskID, err) + s.engine.Pause(taskID, agent.AbortPausedByOrchestrator) + }, + }) + } s.initSetupToken() s.loadPasswordVersion() s.initSideQuestions() @@ -1880,6 +1893,10 @@ func (s *Server) createTask(w http.ResponseWriter, r *http.Request) { writeErr(w, 400, "invalid task-level intercept rules: "+err.Error()) return } + if err := s.checkSandboxReady(r.Context()); err != nil { + writeErr(w, http.StatusServiceUnavailable, err.Error()) + return + } t, err := s.m.CreateTaskWithOptions(req.Description, req.Goal, db.TaskCreateOptions{ Name: strings.TrimSpace(req.Name), CategoryID: req.CategoryID, SourceTaskIDs: sourceIDs, CompanyIDs: req.CompanyIDs, LLMProfileIDs: req.LLMProfileIDs, @@ -2296,7 +2313,7 @@ func (s *Server) taskScopeAdd(w http.ResponseWriter, r *http.Request) { return } taskID, _ := strconv.ParseInt(t.ID, 10, 64) - ts, err := as.AddAgentScope(taskID, body.Kind, body.Value, body.Reason, "manual") + ts, err := as.AddOperatorScope(taskID, body.Kind, body.Value, body.Reason) if err != nil { writeErr(w, 400, err.Error()) return diff --git a/server/server_mgmt.go b/server/server_mgmt.go index a36548c93..6bd5f8162 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "log" "log/slog" "mime" "net" @@ -33,6 +34,7 @@ import ( "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" "github.com/Autumn-27/artex/notify" + "github.com/Autumn-27/artex/sandbox" "github.com/Autumn-27/norma/llm" "github.com/Autumn-27/norma/skill" ) @@ -269,6 +271,14 @@ func (s *Server) pgDeleteTask(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusConflict, err.Error()) return } + if s.sandboxClient != nil && s.sandboxMode == sandbox.ModeRequired { + dctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + _, derr := s.sandboxClient.Delete(dctx, id) + cancel() + if derr != nil && !errors.Is(derr, sandbox.ErrNotFound) { + log.Printf("[sandbox] delete task %s container resources: %v", id, derr) + } + } result, err := s.m.DeleteTask(id, opts) if err != nil { var committed *taskDeleteCommittedError diff --git a/server/sharedbrowser_guard.go b/server/sharedbrowser_guard.go index 1cedafb78..edddb5a57 100644 --- a/server/sharedbrowser_guard.go +++ b/server/sharedbrowser_guard.go @@ -8,6 +8,7 @@ import ( "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" "github.com/google/uuid" ) @@ -135,12 +136,88 @@ type sharedBrowserTool struct { } func (t *sharedBrowserTool) Call(ctx context.Context, in json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { - if refusal := t.b.AgentGate(ctx, t.holder, t.label, t.Name()); refusal != "" { - return actool.Errorf(refusal), nil + if agent.SandboxRequired() { + if err := sandboxCheckBrowserInput(ctx, t.Name(), in); err != nil { + return actool.Errorf(fmt.Sprintf("sandbox browser navigation blocked: %v", err)), nil + } + } + if t.b != nil { + if refusal := t.b.AgentGate(ctx, t.holder, t.label, t.Name()); refusal != "" { + return actool.Errorf(refusal), nil + } } return t.CoreTool.Call(ctx, in, tc) } +// sandboxCheckBrowserInput extracts every URL argument from a browser MCP tool +// invocation and enforces the task's sandbox.EgressPolicy (deny by default; +// blocks non-scope IPs, IMDS, loopback, RFC1918, non-scope domains, and +// dangerous schemes like file:// or chrome://). +func sandboxCheckBrowserInput(ctx context.Context, toolName string, raw json.RawMessage) error { + info, _ := agent.SandboxRunInfoFromContext(ctx) + policy, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil) + if err != nil { + return fmt.Errorf("invalid task egress policy: %w", err) + } + urls := extractBrowserInputURLs(toolName, raw) + for _, u := range urls { + if err := policy.CheckURL(ctx, u); err != nil { + return err + } + } + return nil +} + +func extractBrowserInputURLs(toolName string, raw json.RawMessage) []string { + var parsed any + if err := json.Unmarshal(raw, &parsed); err != nil { + return nil + } + var out []string + seen := map[string]bool{} + add := func(s string) { + s = strings.TrimSpace(s) + if s != "" && !seen[s] { + seen[s] = true + out = append(out, s) + } + } + navTool := strings.Contains(strings.ToLower(toolName), "navigat") || + strings.Contains(strings.ToLower(toolName), "goto") || + strings.Contains(strings.ToLower(toolName), "open") + var walk func(key string, v any) + walk = func(key string, v any) { + switch x := v.(type) { + case map[string]any: + for k, val := range x { + walk(strings.ToLower(k), val) + } + case []any: + for _, item := range x { + walk(key, item) + } + case string: + s := strings.TrimSpace(x) + if s == "" { + return + } + if key == "url" || key == "href" || key == "uri" || key == "target_url" || key == "target" { + add(s) + return + } + low := strings.ToLower(s) + if strings.HasPrefix(low, "http://") || strings.HasPrefix(low, "https://") || + strings.HasPrefix(low, "ws://") || strings.HasPrefix(low, "wss://") || + strings.HasPrefix(low, "file://") || strings.HasPrefix(low, "chrome://") || + strings.HasPrefix(low, "javascript:") || (navTool && strings.Contains(s, "://")) { + add(s) + } + } + } + walk("", parsed) + return out +} + // AcceptsRawInput forwards the wrapped tool's opt-out of the harness schema check. func (t *sharedBrowserTool) AcceptsRawInput() bool { r, ok := t.CoreTool.(interface{ AcceptsRawInput() bool })