mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
- 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.
364 lines
11 KiB
Go
364 lines
11 KiB
Go
//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 >/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 >/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 >/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 >/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))
|
|
})
|
|
}
|
|
}
|