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/2] 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/2] 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