Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

security(agent): share only run-dir leaves; main agent gets its own leaf

BaaRaie73cdeda9356
diff --git a/SECURITY.md b/SECURITY.md
index c6f5009..e1afb8d 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -51,7 +51,7 @@ Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge c
## Agent Process Isolation
-The server runs as root, but the processes an agent starts (Bash, the interactive shell, custom tools and stdio MCP servers) run as the unprivileged uid and gid set by `-exec-uid` and `-exec-gid` (default 10001). Only the task workspace tree, shared with that group, and their own home (`<data>/exec-home`) are writable by them; `keys/` (`jwt.key`, `secret.key`), the config file and the MITM CA key are root-only, and the server's environment block no longer carries `ARTEX_PG_DSN`, `ARTEX_SECRET_KEY`, the LLM API keys or the LLM proxy and base URLs (Linux). The agent's file tools (Read, Write, Edit, MultiEdit, LS, Glob, Grep) run inside the server but reach only the run's working directory: paths are opened through `os.Root`, so absolute paths elsewhere, `..` and symlinks leading out are refused, and a working directory reached through any symlink is refused (a swap between that check and the open is not closed). `ingest_bbot` reads its file through the same confinement. Custom-tool scripts are protected only when the executor privilege drop is active: they are then written to `<data>/exec-scripts`, a root-owned directory the executor can read and cannot change; with the drop disabled they still go to `.tools/` under the run directory. Residual, not closed here: the other root reads and writes by path remain open, and a symlink the executor places can redirect them, so root may read or write outside the workspace. They are the command-output spill (`cmd-output/`, written by Norma), `ingest_scan_output` (a root read by path), the `ask_operator` image staging (a root read and write under the task `uploads/` directory), chat uploads under the `tasks/<id>/uploads/` or `sessions/<id>/uploads/` directories, `ensureRunDir` and the chat session directory creation (a root `MkdirAll` that follows planted symlinks), and task archive packaging (`lstat` then open by path). The Docker image has no setuid programs and `docker-compose.yml` sets `no-new-privileges`. These are a containment layer, not a sandbox: an executor can still read world-readable files under the data directory, reach the loopback API and the database if the network allows it, and use any credential it was given through the platform. Persistence tools (custom tools, MCP servers, skills) need operator approval by default.
+The server runs as root, but the processes an agent starts (Bash, the interactive shell, custom tools and stdio MCP servers) run as the unprivileged uid and gid set by `-exec-uid` and `-exec-gid` (default 10001). Only the run directories and their own home (`<data>/exec-home`) are writable by them. No agent working directory is an ancestor of another: the main agent and the planner work in `tasks/<id>/main`, a worker in `tasks/<id>/i<N>`, a chat in `sessions/<id>`. Their parents (`tasks/`, `sessions/` and `tasks/<id>`) are root:root 0755, so the executor cannot create, rename or remove an entry there, and only the leaves are shared with the executor group (setgid, 0775); with the drop active the server creates each level without following a symlink. Files that a task wrote directly in `tasks/<id>/` before this layout are not moved and keep the owner and mode they had, so one that was group-writable stays writable by the executor. `keys/` (`jwt.key`, `secret.key`), the config file and the MITM CA key are root-only, and the server's environment block no longer carries `ARTEX_PG_DSN`, `ARTEX_SECRET_KEY`, the LLM API keys or the LLM proxy and base URLs (Linux). The agent's file tools (Read, Write, Edit, MultiEdit, LS, Glob, Grep) run inside the server but reach only the run's working directory: paths are opened through `os.Root`, so absolute paths elsewhere, `..` and symlinks leading out are refused, and a working directory reached through any symlink is refused. The executor cannot replace a run directory or one of its parents, so the race that remains is the swap between an `EvalSymlinks` check and the open of a file inside a run directory, which the executor can do only inside a leaf (every executor process has the same identity, so this is any leaf, never a leaf itself or its parents). `ingest_bbot` reads its file through the same confinement. Custom-tool scripts are protected only when the executor privilege drop is active: they are then written to `<data>/exec-scripts`, a root-owned directory the executor can read and cannot change; with the drop disabled they still go to `.tools/` under the run directory. Residual, not closed here: the other root reads and writes by path remain open, and a symlink the executor places can redirect them, so root may read or write outside the workspace. They are the command-output spill (`cmd-output/`, written by Norma), `ingest_scan_output` (a root read by path), the `ask_operator` image staging (a root read and write under the task `uploads/` directory), chat uploads under the `tasks/<id>/main/uploads/` or `sessions/<id>/uploads/` directories, and task archive packaging (`lstat` then open by path). The Docker image has no setuid programs and `docker-compose.yml` sets `no-new-privileges`. These are a containment layer, not a sandbox: an executor can still read world-readable files under the data directory, reach the loopback API and the database if the network allows it, and use any credential it was given through the platform. Persistence tools (custom tools, MCP servers, skills) need operator approval by default.
## What to Expect
diff --git a/agent/chat.go b/agent/chat.go
index 2feca34..f6cf0ab 100644
--- a/agent/chat.go
+++ b/agent/chat.go
@@ -152,8 +152,8 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
if !sessionDirInside(c.workDir, sessionWorkDir) {
return "", fmt.Errorf("invalid session id %q", sessionID)
}
- // 0775 for the same reason as ensureRunDir: the executor group writes here.
- _ = os.MkdirAll(sessionWorkDir, 0o775)
+ // A run directory like the task ones, created the same way (makeRunDir).
+ makeRunDir(c.workDir, sessionWorkDir)
ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir)
// Pure assistant: DefaultTools as the base; AugmentTools layers in the key's
diff --git a/agent/mainagent.go b/agent/mainagent.go
index adc4858..7fc9a7e 100644
--- a/agent/mainagent.go
+++ b/agent/mainagent.go
@@ -130,7 +130,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)})
tools, def, cleanup := AugmentTools(ctx, "mainagent", base)
defer cleanup()
- // this task's working directory <workDir>/tasks/<taskID>, created up front.
+ // the main run directory <workDir>/tasks/<taskID>/main, created up front.
mainDir := ensureRunDir(m.workDir, taskID, 0)
ctx = intercept.WithReviewWorkingDirectory(ctx, mainDir)
system, boundary := deferredSystem(mainAgentSystem(goal, m.workDir, mainDir), def)
@@ -155,7 +155,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
DeepSeekSearchModel: m.webSearch.DeepSeekModel,
WebSearchProxy: m.webSearch.Proxy,
BashEnv: proxyEnv(m.proxyAddr, m.proxyCACert), // Bash subcommands go through the proxy + trust the CA by default
- WorkingDir: mainDir, // this task's working directory <workDir>/tasks/<taskID>
+ WorkingDir: mainDir, // the main run directory <workDir>/tasks/<taskID>/main
ToolOutputDir: cmdOutDir(mainDir),
MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management)
Compaction: compactionConfig(m.compactionWindow()), // long chats stay within the window
diff --git a/agent/planner.go b/agent/planner.go
index 4b8809e..68afd15 100644
--- a/agent/planner.go
+++ b/agent/planner.go
@@ -514,7 +514,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
// wrap-up round. Its agent-reported gap lines are framed with this message's env.
budgetRound, _ := ctx.Value(budgetRoundKey{}).(BudgetRound)
situational += tsx.coverageLedgerBlock(tc.Final || budgetRound.WrapUp, env)
- // This task's work dir <workDir>/tasks/<taskID>; create it first.
+ // The main run directory <workDir>/tasks/<taskID>/main; create it first.
taskDir := ensureRunDir(p.workDir, taskID, 0)
ctx = intercept.WithReviewContext(ctx, taskDir, intercept.ReviewBackground{})
sysBody := plannerSystem(goal, p.workDir, taskDir) + frameLessonsBlock(p.lessonsBlock)
@@ -553,7 +553,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
DeepSeekSearchModel: p.webSearch.DeepSeekModel,
WebSearchProxy: p.webSearch.Proxy,
BashEnv: proxyEnv(p.proxyAddr, p.proxyCACert), // Bash subcommands go through the proxy + trust its CA by default
- WorkingDir: taskDir, // this task's work dir <workDir>/tasks/<taskID>
+ WorkingDir: taskDir, // the main run directory <workDir>/tasks/<taskID>/main
ToolOutputDir: cmdOutDir(taskDir),
MaxTurns: p.maxTurns, // 0 = unlimited (configurable in agent management)
MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until it
diff --git a/agent/rundir_test.go b/agent/rundir_test.go
new file mode 100644
index 0000000..ca852b5
--- /dev/null
+++ b/agent/rundir_test.go
@@ -0,0 +1,61 @@
+package agent
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// The main agent and the planner work in tasks/<id>/main, a worker in
+// tasks/<id>/i<N>, a chat in sessions/<id>: no run directory is an ancestor of
+// another, and each is created through the server's maker when one is set.
+func TestRunDirLayout(t *testing.T) {
+ base := t.TempDir()
+ mainDir := ensureRunDir(base, 7, 0)
+ worker := ensureRunDir(base, 7, 12)
+ session := EnsureSessionDir(base, "conv-3")
+ task := filepath.Join(base, "tasks", "7")
+ if mainDir != filepath.Join(task, "main") || worker != filepath.Join(task, "i12") || session != filepath.Join(base, "sessions", "conv-3") {
+ t.Fatalf("run directories: main %s, worker %s, session %s", mainDir, worker, session)
+ }
+ dirs := []string{mainDir, worker, session}
+ for _, dir := range dirs {
+ if fi, err := os.Stat(dir); err != nil || !fi.IsDir() {
+ t.Fatalf("%s was not created: %v", dir, err)
+ }
+ for _, other := range dirs {
+ if other != dir && strings.HasPrefix(other, dir+string(filepath.Separator)) {
+ t.Errorf("%s is an ancestor of %s", dir, other)
+ }
+ }
+ }
+
+ var made []string
+ SetRunDirMaker(func(b, leaf string) error {
+ if b != base {
+ t.Errorf("maker base = %s, want %s", b, base)
+ }
+ made = append(made, leaf)
+ return nil
+ })
+ t.Cleanup(func() { SetRunDirMaker(nil) })
+ want := []string{EnsureRunDir(base, 8, 0), EnsureRunDir(base, 8, 5), EnsureSessionDir(base, "conv-4")}
+ if strings.Join(made, "|") != strings.Join(want, "|") {
+ t.Errorf("maker calls = %v, want %v", made, want)
+ }
+ if _, err := os.Stat(filepath.Join(base, "tasks", "8")); !os.IsNotExist(err) {
+ t.Errorf("a run directory was created beside the maker: %v", err)
+ }
+}
+
+func TestIsRunDirName(t *testing.T) {
+ for name, want := range map[string]bool{
+ "main": true, "i1": true, "i120": true,
+ "": false, "i": false, "i1a": false, "i-1": false, "I1": false, "uploads": false, "cmd-output": false, "main2": false,
+ } {
+ if got := IsRunDirName(name); got != want {
+ t.Errorf("IsRunDirName(%q) = %v, want %v", name, got, want)
+ }
+ }
+}
diff --git a/agent/worker.go b/agent/worker.go
index 70b3b46..0ebd093 100644
--- a/agent/worker.go
+++ b/agent/worker.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "log"
"os"
"path/filepath"
"strconv"
@@ -314,22 +315,78 @@ func workerArtifactSpec(runDir string) string {
return "\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this intent's dedicated work directory " + runDir + "** (already created automatically; just write with relative paths there — no manual mkdir needed) — **do NOT write to /tmp, do NOT use other absolute paths**."
}
+// mainRunDirName is the run directory of a task's main agent and planner.
+const mainRunDirName = "main"
+
+// runDirMaker creates a run directory below the data directory with the ownership
+// the server wants. The server sets it when agent processes run as the executor
+// (server/execpriv_unix.go); nil keeps a plain MkdirAll.
+var runDirMaker func(base, leaf string) error
+
+// SetRunDirMaker sets how run directories are created. Call it before any agent runs.
+func SetRunDirMaker(f func(base, leaf string) error) { runDirMaker = f }
+
+// makeRunDir creates the run directory leaf below base. Best-effort — on failure,
+// writes fail the same way an unwritable CWD would.
+func makeRunDir(base, leaf string) {
+ if runDirMaker == nil {
+ // 0775: the umask of the server decides the final bits.
+ _ = os.MkdirAll(leaf, 0o775)
+ return
+ }
+ if err := runDirMaker(base, leaf); err != nil {
+ log.Printf("[agent] run directory %s: %v", leaf, err)
+ }
+}
+
// ensureRunDir builds and creates an agent's working directory under base:
-// <base>/tasks/<taskID> for planner/main; <base>/tasks/<taskID>/i<intentID> for a
-// worker (intentID<=0 → task dir only). The "tasks/" segment groups per-task dirs
-// symmetrically with the chat agent's "sessions/<sessionID>". Best-effort mkdir — on
-// failure, writes fail the same way an unwritable CWD would.
+// <base>/tasks/<taskID>/main for planner/main (intentID<=0);
+// <base>/tasks/<taskID>/i<intentID> for a worker. No run directory is an ancestor of
+// another: the task directory holds the leaves and is no agent's working directory.
+// The "tasks/" segment groups per-task dirs symmetrically with the chat agent's
+// "sessions/<sessionID>".
func ensureRunDir(base string, taskID, intentID int64) string {
- dir := filepath.Join(base, "tasks", strconv.FormatInt(taskID, 10))
+ leaf := mainRunDirName
if intentID > 0 {
- dir = filepath.Join(dir, "i"+strconv.FormatInt(intentID, 10))
+ leaf = "i" + strconv.FormatInt(intentID, 10)
}
- // 0775: with the executor group sharing the task tree (server/execpriv.go) the
- // agent's shell must write here; the umask of the server decides the final bits.
- _ = os.MkdirAll(dir, 0o775)
+ dir := filepath.Join(base, "tasks", strconv.FormatInt(taskID, 10), leaf)
+ makeRunDir(base, dir)
return dir
}
+// EnsureRunDir is ensureRunDir for the server, which places the main agent's
+// uploads in its run directory.
+func EnsureRunDir(base string, taskID, intentID int64) string {
+ return ensureRunDir(base, taskID, intentID)
+}
+
+// EnsureSessionDir creates the chat run directory <base>/sessions/<sessionID> the
+// way ensureRunDir creates a task one, and returns it.
+func EnsureSessionDir(base, sessionID string) string {
+ dir := filepath.Join(base, "sessions", sessionID)
+ makeRunDir(base, dir)
+ return dir
+}
+
+// IsRunDirName reports whether name is a run directory inside a task directory:
+// main or i<intentID>.
+func IsRunDirName(name string) bool {
+ if name == mainRunDirName {
+ return true
+ }
+ digits, ok := strings.CutPrefix(name, "i")
+ if !ok || digits == "" {
+ return false
+ }
+ for _, c := range digits {
+ if c < '0' || c > '9' {
+ return false
+ }
+ }
+ return true
+}
+
// cmdOutDir is the SDK large-tool-output spill dir under an agent's run dir.
func cmdOutDir(dir string) string { return filepath.Join(dir, "cmd-output") }
diff --git a/server/chatupload.go b/server/chatupload.go
index addc785..bd7cc03 100644
--- a/server/chatupload.go
+++ b/server/chatupload.go
@@ -8,8 +8,10 @@ import (
"os"
"path/filepath"
"regexp"
+ "strconv"
"strings"
+ "github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
)
@@ -43,9 +45,9 @@ type chatAttachment struct {
//
// POST /api/chat/upload?scope=task|session|staging&id=<id>, multipart field "file"
// (repeatable). Returns {attachments:[{name,path,size,abs}]}. Target dir mirrors the
-// agent CWD layout:
+// agent CWD layout (the run directory is created like the agent creates it):
//
-// scope=task → <workDir>/tasks/<id>/uploads/
+// scope=task → <workDir>/tasks/<id>/main/uploads/ (the main agent's run directory)
// scope=session → <workDir>/sessions/<id>/uploads/
// scope=staging → <workDir>/drafts/<id>/uploads/ (pre-task staging: the task has no ID yet;
// files land here first and the frontend writes their abs paths into the task description)
@@ -69,8 +71,10 @@ func (s *Server) chatUpload(w http.ResponseWriter, r *http.Request) {
writeErr(w, 400, "invalid id")
return
}
+ base := filepath.Join(s.m.dir, sub, id) // the directory uploads/ goes in
if taskScoped {
- if s.m.ResolveTask(id) == nil {
+ t := s.m.ResolveTask(id)
+ if t == nil {
writeErr(w, 404, "task not found")
return
}
@@ -79,8 +83,12 @@ func (s *Server) chatUpload(w http.ResponseWriter, r *http.Request) {
return
}
defer s.engine.decInflight(id)
+ taskID, _ := strconv.ParseInt(t.ID, 10, 64)
+ base = agent.EnsureRunDir(s.m.dir, taskID, 0)
+ } else if sub == "sessions" {
+ base = agent.EnsureSessionDir(s.m.dir, id)
}
- dir := filepath.Join(s.m.dir, sub, id, "uploads")
+ dir := filepath.Join(base, "uploads")
if err := os.MkdirAll(dir, 0o755); err != nil {
writeErr(w, 500, "failed to create directory: "+err.Error())
return
diff --git a/server/execpriv_other.go b/server/execpriv_other.go
index 1d7bb38..b8f68f9 100644
--- a/server/execpriv_other.go
+++ b/server/execpriv_other.go
@@ -21,6 +21,8 @@ func applyExecCredential(c *exec.Cmd, p ExecPrivilege) {}
func prepareExecScript(p ExecPrivilege, path string) error { return nil }
+func shareRestoredTaskDir(p ExecPrivilege, taskDir string) error { return nil }
+
// PrepareExecPrivilege fails when a drop is enabled; a disabled one does nothing.
func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string) error {
if p.Enabled {
diff --git a/server/execpriv_root_linux_test.go b/server/execpriv_root_linux_test.go
index 3198536..6ec1f38 100644
--- a/server/execpriv_root_linux_test.go
+++ b/server/execpriv_root_linux_test.go
@@ -14,6 +14,7 @@ import (
"testing"
"time"
+ "github.com/Autumn-27/artex/agent"
actool "github.com/Autumn-27/norma/tool"
)
@@ -24,8 +25,8 @@ import (
// writable HOME and cache.
type execRootFixture struct {
- priv ExecPrivilege
- home, secret, work string
+ priv ExecPrivilege
+ data, home, secret, work string
}
func newExecRootFixture(t *testing.T) *execRootFixture {
@@ -53,6 +54,7 @@ func newExecRootFixture(t *testing.T) *execRootFixture {
if err != nil {
t.Fatal(err)
}
+ t.Cleanup(func() { agent.SetRunDirMaker(nil) }) // PrepareExecPrivilege sets it process-wide
if err := PrepareExecPrivilege(&priv, dataDir, "", ""); err != nil {
t.Fatal(err)
}
@@ -63,11 +65,9 @@ func newExecRootFixture(t *testing.T) *execRootFixture {
if _, err := os.ReadFile(secret); err != nil {
t.Fatalf("root must read its own key: %v", err)
}
- work := filepath.Join(dataDir, "tasks", "1")
- if err := os.MkdirAll(work, 0o775); err != nil {
- t.Fatal(err)
- }
- return &execRootFixture{priv: priv, home: filepath.Join(dataDir, execHomeDir), secret: secret, work: work}
+ // The run directory of task 1's main agent, created as the agent creates it.
+ work := agent.EnsureRunDir(dataDir, 1, 0)
+ return &execRootFixture{priv: priv, data: dataDir, home: filepath.Join(dataDir, execHomeDir), secret: secret, work: work}
}
// probe is the shell script each path runs as the executor.
diff --git a/server/execpriv_unix.go b/server/execpriv_unix.go
index 5812473..10a2b8d 100644
--- a/server/execpriv_unix.go
+++ b/server/execpriv_unix.go
@@ -13,6 +13,8 @@ import (
"strconv"
"strings"
"syscall"
+
+ "github.com/Autumn-27/artex/agent"
)
// Environment names the shims read. They carry no secret: the executor id, the real
@@ -136,27 +138,24 @@ func prepareExecScript(p ExecPrivilege, path string) error {
}
// PrepareExecPrivilege sets up the state the executor needs before the server opens
-// its stores. The task and chat workspace trees are shared with the executor group
-// (setgid, group read/write, umask 002) instead of chowned per directory: the
-// workspace is created in many places, and new subdirectories inherit the group. The key files and the
-// config file (which can hold the database DSN) are restricted to root. Nothing
-// else under the data directory changes; directories a root-only path needs are
-// left as they are. It sets p.ScriptDir to the script directory it creates.
+// its stores. Only the run directories are shared with the executor group (setgid,
+// group read/write, umask 002): tasks/<id>/main, tasks/<id>/i<N> and sessions/<id>.
+// Their parents (tasks/, sessions/ and tasks/<id>) are root:root 0755, so the
+// executor cannot create, rename or remove a run directory, and no run directory is
+// an ancestor of another. Inside a run directory new subdirectories inherit the
+// group. The key files and the config file (which can hold the database DSN) are
+// restricted to root. Nothing else under the data directory changes; directories a
+// root-only path needs are left as they are. It sets p.ScriptDir to the script
+// directory it creates.
func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string) error {
if !p.Enabled {
return nil
}
- // tasks/ holds the run directories of the task agents, sessions/ the chat
- // workspaces: the shell of each runs in one of them.
- for _, sub := range []string{"tasks", "sessions"} {
- root := filepath.Join(dataDir, sub)
- if err := os.MkdirAll(root, 0o775); err != nil {
- return fmt.Errorf("create %s workspace root: %w", sub, err)
- }
- if err := shareWithExecGroup(root, int(p.GID)); err != nil {
- return fmt.Errorf("share %s workspace with the executor group: %w", sub, err)
- }
+ gid := int(p.GID)
+ if err := shareRunDirs(dataDir, gid); err != nil {
+ return fmt.Errorf("share the run directories with the executor group: %w", err)
}
+ agent.SetRunDirMaker(func(base, leaf string) error { return makeRunDir(base, leaf, gid) })
if err := prepareExecHome(*p, dataDir); err != nil {
return fmt.Errorf("prepare the executor home: %w", err)
}
@@ -186,12 +185,135 @@ func PrepareExecPrivilege(p *ExecPrivilege, dataDir, keyDir, configPath string)
}
}
// Files and directories the server creates from now on are group-writable, so
- // the executor can write into the task workspace inside the shared tree.
+ // the executor can write what the server puts in a run directory.
syscall.Umask(0o002)
- log.Printf("[exec] agent processes run as uid %d gid %d; task workspace %s is shared with that group", p.UID, p.GID, tasks)
+ log.Printf("[exec] agent processes run as uid %d gid %d; the run directories under %s are shared with that group", p.UID, p.GID, tasks)
+ return nil
+}
+
+// runDirMode is the mode of a run directory: group-writable, and setgid so what is
+// created in it keeps the executor group.
+const runDirMode = 0o775 | os.ModeSetgid
+
+// setDirOwner makes dir root:gid with mode. dir is opened without following a
+// symlink and changed through the descriptor, so a planted link is refused and
+// never changes another directory.
+func setDirOwner(dir string, gid int, mode os.FileMode) error {
+ f, err := os.OpenFile(dir, os.O_RDONLY|syscall.O_DIRECTORY|syscall.O_NOFOLLOW, 0)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ if err := f.Chown(0, gid); err != nil {
+ return err
+ }
+ return f.Chmod(mode)
+}
+
+// makeRunDir creates the run directory leaf below base. Every directory between
+// base and the leaf is root:root 0755, and the leaf alone is shared with the
+// executor group. A parent is set before the next level is touched: once it is
+// root-only, the executor cannot swap what is below it.
+func makeRunDir(base, leaf string, gid int) error {
+ rel, err := filepath.Rel(base, leaf)
+ if err != nil || rel == "." || !filepath.IsLocal(rel) {
+ return fmt.Errorf("%s is not below %s", leaf, base)
+ }
+ parts := strings.Split(rel, string(filepath.Separator))
+ dir := base
+ for i, part := range parts {
+ dir = filepath.Join(dir, part)
+ group, mode := 0, os.FileMode(0o755)
+ if i == len(parts)-1 {
+ group, mode = gid, runDirMode
+ }
+ if err := os.Mkdir(dir, mode.Perm()); err != nil && !errors.Is(err, fs.ErrExist) {
+ return err
+ }
+ if err := setDirOwner(dir, group, mode); err != nil {
+ return err
+ }
+ }
return nil
}
+// shareRunDirs applies the run-directory layout to what is on disk: tasks/ and
+// sessions/ become root:root 0755, each task directory too, and each run directory
+// (sessions/<id>, tasks/<id>/main, tasks/<id>/i<N>) is shared with the executor
+// group with what it holds.
+func shareRunDirs(dataDir string, gid int) error {
+ if err := os.MkdirAll(dataDir, 0o755); err != nil {
+ return err
+ }
+ for _, sub := range []string{"tasks", "sessions"} {
+ root := filepath.Join(dataDir, sub)
+ if err := os.Mkdir(root, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
+ return err
+ }
+ if err := setDirOwner(root, 0, 0o755); err != nil {
+ return err
+ }
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ return err
+ }
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ dir := filepath.Join(root, e.Name())
+ if sub == "tasks" {
+ err = shareTaskDir(dir, gid)
+ } else {
+ err = shareRunDir(dir, gid)
+ }
+ if err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// shareTaskDir makes a task directory root:root 0755 and shares the run directories
+// in it. Its other entries are left as they are: a task whose main agent worked in
+// the task directory itself keeps its files there, with the owner and mode they had.
+func shareTaskDir(taskDir string, gid int) error {
+ if err := setDirOwner(taskDir, 0, 0o755); err != nil {
+ return err
+ }
+ entries, err := os.ReadDir(taskDir)
+ if err != nil {
+ return err
+ }
+ for _, e := range entries {
+ if !e.IsDir() || !agent.IsRunDirName(e.Name()) {
+ continue
+ }
+ if err := shareRunDir(filepath.Join(taskDir, e.Name()), gid); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// shareRunDir shares one run directory and what it holds with the executor group.
+func shareRunDir(leaf string, gid int) error {
+ if err := setDirOwner(leaf, gid, runDirMode); err != nil {
+ return err
+ }
+ return shareWithExecGroup(leaf, gid)
+}
+
+// shareRestoredTaskDir puts the run-directory layout back on a task directory that
+// was restored from an archive: the package keeps neither owners nor directory modes.
+func shareRestoredTaskDir(p ExecPrivilege, taskDir string) error {
+ if !p.Enabled {
+ return nil
+ }
+ return shareTaskDir(taskDir, int(p.GID))
+}
+
// shareWithExecGroup gives the executor group the tree under root: the group owns
// each entry and gets read/write (and traverse on directories), and directories set
// the setgid bit so anything created below them keeps the group.
diff --git a/server/rundir_root_linux_test.go b/server/rundir_root_linux_test.go
new file mode 100644
index 0000000..aba7925
--- /dev/null
+++ b/server/rundir_root_linux_test.go
@@ -0,0 +1,331 @@
+//go:build linux
+
+package server
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/Autumn-27/artex/agent"
+ pgdb "github.com/Autumn-27/artex/db"
+)
+
+// Root tests of the run-directory layout: no agent working directory is an ancestor
+// of another, the parents of the run directories are root:root 0755, and only the
+// leaves are shared with the executor group.
+
+// checkDir asserts that path is a directory owned by root with the group gid and
+// exactly mode (permission bits plus setuid, setgid and sticky).
+func checkDir(t *testing.T, path string, gid uint32, mode os.FileMode) {
+ t.Helper()
+ fi, err := os.Lstat(path)
+ if err != nil {
+ t.Errorf("%s: %v", path, err)
+ return
+ }
+ st := fi.Sys().(*syscall.Stat_t)
+ got := fi.Mode() & (os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky)
+ if !fi.IsDir() || st.Uid != 0 || st.Gid != gid || got != mode {
+ t.Errorf("%s: %v uid %d gid %d, want a directory %v root:%d", path, fi.Mode(), st.Uid, st.Gid, mode, gid)
+ return
+ }
+ t.Logf("%s: %v uid %d gid %d", path, fi.Mode(), st.Uid, st.Gid)
+}
+
+const (
+ parentDirMode = os.FileMode(0o755)
+ leafDirMode = 0o775 | os.ModeSetgid
+)
+
+// PrepareExecPrivilege and ensureRunDir, for a task with a main agent and a worker
+// and for a chat session.
+func TestRunDirLayoutAsRoot(t *testing.T) {
+ f := newExecRootFixture(t)
+ task := filepath.Join(f.data, "tasks", "1")
+ mainDir := f.work
+ worker := agent.EnsureRunDir(f.data, 1, 7)
+ session := agent.EnsureSessionDir(f.data, "conv-3")
+ if mainDir != filepath.Join(task, "main") || worker != filepath.Join(task, "i7") || session != filepath.Join(f.data, "sessions", "conv-3") {
+ t.Fatalf("run directories: main %s, worker %s, session %s", mainDir, worker, session)
+ }
+ check := func() {
+ t.Helper()
+ for _, dir := range []string{filepath.Join(f.data, "tasks"), filepath.Join(f.data, "sessions"), task} {
+ checkDir(t, dir, 0, parentDirMode)
+ }
+ for _, dir := range []string{mainDir, worker, session} {
+ checkDir(t, dir, DefaultExecGID, leafDirMode)
+ }
+ }
+ check()
+ // A later run of the same agents finds the directories and leaves them so.
+ agent.EnsureRunDir(f.data, 1, 0)
+ agent.EnsureRunDir(f.data, 1, 7)
+ agent.EnsureSessionDir(f.data, "conv-3")
+ check()
+ // What the server creates in a leaf keeps the executor group and is group-writable.
+ uploads := filepath.Join(mainDir, "uploads")
+ if err := os.MkdirAll(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(uploads, "report.txt")
+ if err := os.WriteFile(file, []byte("x"), 0o666); err != nil {
+ t.Fatal(err)
+ }
+ checkDir(t, uploads, DefaultExecGID, 0o755|os.ModeSetgid)
+ fi, err := os.Lstat(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := fi.Sys().(*syscall.Stat_t); st.Gid != DefaultExecGID || fi.Mode().Perm() != 0o664 {
+ t.Errorf("%s: %v gid %d, want 0664 with gid %d", file, fi.Mode(), st.Gid, DefaultExecGID)
+ }
+}
+
+// An executor process started in the main agent's run directory cannot rename or
+// remove a worker's run directory or its own, and cannot create an entry in the
+// task directory or in tasks/.
+func TestRunDirSiblingsProtectedAsRoot(t *testing.T) {
+ f := newExecRootFixture(t)
+ py, err := exec.LookPath("python3")
+ if err != nil {
+ t.Fatalf("python3 is needed for the executor probe: %v", err)
+ }
+ tasks := filepath.Join(f.data, "tasks")
+ task := filepath.Join(tasks, "1")
+ worker := agent.EnsureRunDir(f.data, 1, 7)
+
+ code := `import errno, os
+main = os.getcwd()
+task = os.path.dirname(main)
+tasks = os.path.dirname(task)
+worker = os.path.join(task, "i7")
+print("uid=%d gid=%d" % (os.getuid(), os.getgid()))
+print("cwd=" + main)
+def attempt(name, fn):
+ try:
+ fn()
+ print(name + "=done")
+ except OSError as e:
+ print(name + "=" + errno.errorcode.get(e.errno, str(e.errno)))
+attempt("own_write", lambda: open("own.txt", "w").close())
+attempt("rename_worker", lambda: os.rename(worker, os.path.join(task, "i7.moved")))
+attempt("rename_worker_into_main", lambda: os.rename(worker, os.path.join(main, "i7")))
+attempt("rmdir_worker", lambda: os.rmdir(worker))
+attempt("unlink_worker", lambda: os.unlink(worker))
+attempt("rename_main", lambda: os.rename(main, os.path.join(task, "main.moved")))
+attempt("rmdir_main", lambda: os.rmdir(main))
+attempt("create_in_task", lambda: open(os.path.join(task, "planted"), "w").close())
+attempt("mkdir_in_task", lambda: os.mkdir(os.path.join(task, "i8")))
+attempt("symlink_in_task", lambda: os.symlink("/etc", os.path.join(task, "i9")))
+attempt("create_in_tasks", lambda: open(os.path.join(tasks, "planted"), "w").close())
+attempt("mkdir_in_tasks", lambda: os.mkdir(os.path.join(tasks, "2")))
+attempt("chmod_task", lambda: os.chmod(task, 0o777))
+attempt("chmod_worker", lambda: os.chmod(worker, 0o777))
+`
+ out, err := execPython(context.Background(), py, "probe", code, nil, f.work, nil, 30*time.Second, f.priv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("executor probe output:\n%s", out)
+ for _, want := range []string{
+ fmt.Sprintf("uid=%d gid=%d\n", DefaultExecUID, DefaultExecGID),
+ "cwd=" + f.work + "\n",
+ "own_write=done\n",
+ "chmod_task=EPERM\n", "chmod_worker=EPERM\n",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("want %q in the probe output:\n%s", want, out)
+ }
+ }
+ for _, name := range []string{
+ "rename_worker", "rename_worker_into_main", "rmdir_worker", "unlink_worker", "rename_main", "rmdir_main",
+ "create_in_task", "mkdir_in_task", "symlink_in_task", "create_in_tasks", "mkdir_in_tasks",
+ } {
+ if !strings.Contains(out, name+"=EACCES\n") && !strings.Contains(out, name+"=EPERM\n") {
+ t.Errorf("%s was not refused with EACCES or EPERM:\n%s", name, out)
+ }
+ }
+ if strings.Contains(out, "[exit:") {
+ t.Errorf("the probe failed:\n%s", out)
+ }
+ // Nothing moved and nothing was planted.
+ for dir, want := range map[string]string{tasks: "1", task: "i7 main"} {
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ for _, e := range entries {
+ names = append(names, e.Name())
+ }
+ if got := strings.Join(names, " "); got != want {
+ t.Errorf("%s holds %q, want %q", dir, got, want)
+ }
+ }
+ checkDir(t, task, 0, parentDirMode)
+ checkDir(t, worker, DefaultExecGID, leafDirMode)
+ checkDir(t, f.work, DefaultExecGID, leafDirMode)
+}
+
+// A data directory written before this layout: the task directory was the main
+// agent's working directory and was shared with the executor group. The start-up
+// pass takes the task directory back, shares its run directories and leaves the
+// files of the task directory where they are. A symlink planted where a run
+// directory goes is refused and its target is not changed.
+func TestRunDirLayoutOnExistingTreeAsRoot(t *testing.T) {
+ f := newExecRootFixture(t)
+ gid := int(DefaultExecGID)
+ task := filepath.Join(f.data, "tasks", "2")
+ oldWorker := filepath.Join(task, "i4")
+ nested := filepath.Join(oldWorker, "recon")
+ for _, dir := range []string{task, oldWorker, nested} {
+ if err := os.Mkdir(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The old state of the task directory: group-shared and setgid.
+ if err := os.Chown(task, 0, gid); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(task, 0o775|os.ModeSetgid); err != nil {
+ t.Fatal(err)
+ }
+ oldFile := filepath.Join(task, "notes.txt")
+ workerFile := filepath.Join(nested, "hosts.txt")
+ for _, file := range []string{oldFile, workerFile} {
+ if err := os.WriteFile(file, []byte("x"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(file, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ trap := filepath.Join(f.data, "trap")
+ if err := os.Mkdir(trap, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(trap, filepath.Join(task, "main")); err != nil {
+ t.Fatal(err)
+ }
+ stat := func(path string) (os.FileMode, uint32) {
+ t.Helper()
+ fi, err := os.Lstat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fi.Mode(), fi.Sys().(*syscall.Stat_t).Gid
+ }
+ oldMode, oldGid := stat(oldFile)
+
+ if err := PrepareExecPrivilege(&f.priv, f.data, "", ""); err != nil {
+ t.Fatal(err)
+ }
+ checkDir(t, task, 0, parentDirMode)
+ checkDir(t, oldWorker, DefaultExecGID, leafDirMode)
+ checkDir(t, nested, DefaultExecGID, 0o770|os.ModeSetgid)
+ if mode, g := stat(workerFile); mode.Perm() != 0o660 || g != DefaultExecGID {
+ t.Errorf("%s: %v gid %d, want 0660 with gid %d", workerFile, mode, g, DefaultExecGID)
+ }
+ // The file of the task directory is not moved and keeps its mode and group.
+ if mode, g := stat(oldFile); mode != oldMode || g != oldGid {
+ t.Errorf("%s: %v gid %d, want it left %v gid %d", oldFile, mode, g, oldMode, oldGid)
+ }
+ // The planted link is still a link; creating the main run directory through it
+ // fails, and the directory it points to keeps its owner and mode.
+ agent.EnsureRunDir(f.data, 2, 0)
+ if mode, _ := stat(filepath.Join(task, "main")); mode&os.ModeSymlink == 0 {
+ t.Errorf("tasks/2/main is %v, want the planted symlink left in place", mode)
+ }
+ if err := makeRunDir(f.data, filepath.Join(task, "main"), gid); err == nil {
+ t.Error("makeRunDir accepted a run directory that is a symlink")
+ }
+ checkDir(t, trap, 0, 0o700)
+ if entries, err := os.ReadDir(trap); err != nil || len(entries) != 0 {
+ t.Errorf("the symlink target holds %v (%v), want it empty", entries, err)
+ }
+}
+
+// A task archive round trip with the privilege drop on: the whole task directory is
+// packed, and the restore puts the layout back although the package keeps neither
+// owners nor directory modes.
+func TestTaskArchiveRestoreRunDirOwnershipAsRoot(t *testing.T) {
+ f := newExecRootFixture(t)
+ const taskID = "1"
+ task := filepath.Join(f.data, "tasks", taskID)
+ worker := agent.EnsureRunDir(f.data, 1, 7)
+ files := map[string]string{
+ filepath.Join(f.work, "uploads", "evidence.txt"): "task evidence",
+ filepath.Join(worker, "notes.txt"): "worker notes",
+ }
+ for path, body := range files {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ stage, err := stageTaskArchiveFiles(f.data, 1, taskID, 73)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(task); !os.IsNotExist(err) {
+ t.Fatalf("task directory still hot after staging: %v", err)
+ }
+ archivePath := taskArchivePath(f.data, 1, taskID)
+ snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 1, ExplorationID: 73}
+ _, _, checksum, err := writeTaskArchivePackage(archivePath, stage.payload, snapshot)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := stage.commit(); err != nil {
+ t.Fatal(err)
+ }
+ extracted := filepath.Join(f.data, "restore")
+ if err := extractTaskArchivePackage(archivePath, checksum, extracted); err != nil {
+ t.Fatal(err)
+ }
+ installed, err := installTaskArchiveFiles(f.data, extracted, taskID, 1, f.priv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := installed.commit(); err != nil {
+ t.Fatal(err)
+ }
+
+ checkDir(t, filepath.Join(f.data, "tasks"), 0, parentDirMode)
+ checkDir(t, task, 0, parentDirMode)
+ checkDir(t, f.work, DefaultExecGID, leafDirMode)
+ checkDir(t, worker, DefaultExecGID, leafDirMode)
+ checkDir(t, filepath.Join(f.work, "uploads"), DefaultExecGID, 0o770|os.ModeSetgid)
+ for path, want := range files {
+ got, err := os.ReadFile(path)
+ if err != nil || string(got) != want {
+ t.Fatalf("restored %s = %q, %v; want %q", path, got, err, want)
+ }
+ fi, err := os.Lstat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := fi.Sys().(*syscall.Stat_t); st.Gid != DefaultExecGID || fi.Mode().Perm()&0o060 != 0o060 {
+ t.Errorf("%s: %v gid %d, want group read/write with gid %d", path, fi.Mode(), st.Gid, DefaultExecGID)
+ }
+ }
+ // The executor works in the restored run directory again.
+ c := exec.Command("sh", "-c", "echo more >> uploads/evidence.txt && echo new > after-restore.txt && id -u")
+ c.Dir = f.work
+ applyExecCredential(c, f.priv)
+ out, err := c.CombinedOutput()
+ if err != nil || strings.TrimSpace(string(out)) != fmt.Sprint(DefaultExecUID) {
+ t.Fatalf("executor write in the restored run directory: %v\n%s", err, out)
+ }
+}
diff --git a/server/server.go b/server/server.go
index 6ffd703..e95dafb 100644
--- a/server/server.go
+++ b/server/server.go
@@ -4343,9 +4343,9 @@ func (s *Server) chat(w http.ResponseWriter, r *http.Request) {
maTaskID, _ := strconv.ParseInt(t.ID, 10, 64)
resume := func() { s.reviveTask(t) } // set_goals added a goal → pulls the task back to running
// Splice the list of [absolute paths] of uploaded attachments into the message sent to the agent; it uses them to open files via Read/Bash.
- // taskDir = the agent's working directory (CWD), consistent with chatUpload's target dir and ensureRunDir.
- taskDir := filepath.Join(s.m.dir, "tasks", t.ID)
- agentMsg := composeAgentMessage(agentMessage, req.Attachments, taskDir)
+ // mainDir = the main agent's run directory (its CWD, tasks/<id>/main), the same call as chatUpload's target dir and the agent itself.
+ mainDir := agent.EnsureRunDir(s.m.dir, maTaskID, 0)
+ agentMsg := composeAgentMessage(agentMessage, req.Attachments, mainDir)
// Tag the turn for the target gate: the task, the "mainagent" lane and the approval scope.
gctx := intercept.WithTaskContext(ctx, t.ID, "mainagent", func(a db.Activity) {
a.Worker = "mainagent"
diff --git a/server/task_archive_package.go b/server/task_archive_package.go
index f23c4c8..8311494 100644
--- a/server/task_archive_package.go
+++ b/server/task_archive_package.go
@@ -227,7 +227,10 @@ func (s *taskArchiveFileStage) commit() error {
return os.RemoveAll(s.root)
}
-func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID int64) (*taskArchiveRestoreFiles, error) {
+// installTaskArchiveFiles moves the extracted workspace and transcripts back under
+// the data directory. The workspace is the whole task directory, run directories
+// (main/, i<N>/) included; priv puts their ownership back.
+func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID int64, priv ExecPrivilege) (*taskArchiveRestoreFiles, error) {
stage := &taskArchiveRestoreFiles{extracted: extractedDir}
numericTaskID, err := strconv.ParseInt(taskID, 10, 64)
if err != nil || numericTaskID <= 0 {
@@ -235,8 +238,11 @@ func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID int
}
sources := []restoredArchivePath{}
workspace := filepath.Join(extractedDir, "files", "tasks", taskID)
+ taskDir := filepath.Join(dataDir, "tasks", taskID)
+ hasWorkspace := false
if _, err := os.Lstat(workspace); err == nil {
- sources = append(sources, restoredArchivePath{Source: workspace, Destination: filepath.Join(dataDir, "tasks", taskID)})
+ sources = append(sources, restoredArchivePath{Source: workspace, Destination: taskDir})
+ hasWorkspace = true
} else if !os.IsNotExist(err) {
return nil, err
}
@@ -272,6 +278,12 @@ func installTaskArchiveFiles(dataDir, extractedDir, taskID string, archiveID int
return nil, err
}
}
+ if hasWorkspace {
+ if err := shareRestoredTaskDir(priv, taskDir); err != nil {
+ _ = stage.rollback()
+ return nil, fmt.Errorf("restore the run directory ownership of %s: %w", taskDir, err)
+ }
+ }
return stage, nil
}
diff --git a/server/task_archive_package_test.go b/server/task_archive_package_test.go
index e3af4ea..8a8e10d 100644
--- a/server/task_archive_package_test.go
+++ b/server/task_archive_package_test.go
@@ -16,11 +16,14 @@ func TestTaskArchivePackageFilesRoundTrip(t *testing.T) {
dataDir := t.TempDir()
taskID := "42"
explorationID := int64(73)
- taskFile := filepath.Join(dataDir, "tasks", taskID, "uploads", "evidence.txt")
+ // The task directory packs whole: the main agent's run directory and a worker's.
+ taskFile := filepath.Join(dataDir, "tasks", taskID, "main", "uploads", "evidence.txt")
+ workerFile := filepath.Join(dataDir, "tasks", taskID, "i7", "notes.txt")
transcriptFile := filepath.Join(dataDir, "transcripts", "exp73-worker-1.jsonl")
unrelatedTranscript := filepath.Join(dataDir, "transcripts", "exp74-worker-1.jsonl")
for path, body := range map[string]string{
taskFile: "task evidence",
+ workerFile: "worker notes",
transcriptFile: "transcript",
unrelatedTranscript: "leave me hot",
} {
@@ -36,8 +39,10 @@ func TestTaskArchivePackageFilesRoundTrip(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if _, err := os.Stat(taskFile); !os.IsNotExist(err) {
- t.Fatalf("task file still hot after staging: %v", err)
+ for _, path := range []string{taskFile, workerFile} {
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("task file %s still hot after staging: %v", path, err)
+ }
}
if _, err := os.Stat(transcriptFile); !os.IsNotExist(err) {
t.Fatalf("task transcript still hot after staging: %v", err)
@@ -76,14 +81,20 @@ func TestTaskArchivePackageFilesRoundTrip(t *testing.T) {
if got, err := os.ReadFile(filepath.Join(extracted, filepath.FromSlash(pgdb.TaskArchiveLLMRecordsPath))); err != nil || !bytes.Equal(got, streamBody) {
t.Fatalf("streamed LLM archive payload=%q err=%v", got, err)
}
- installed, err := installTaskArchiveFiles(dataDir, extracted, taskID, 1)
+ // The package holds the run directories under files/tasks/<id>/.
+ for _, rel := range []string{filepath.Join("main", "uploads", "evidence.txt"), filepath.Join("i7", "notes.txt")} {
+ if _, err := os.Stat(filepath.Join(extracted, "files", "tasks", taskID, rel)); err != nil {
+ t.Fatalf("package entry files/tasks/%s/%s: %v", taskID, rel, err)
+ }
+ }
+ installed, err := installTaskArchiveFiles(dataDir, extracted, taskID, 1, ExecPrivilege{})
if err != nil {
t.Fatal(err)
}
if err := installed.commit(); err != nil {
t.Fatal(err)
}
- for path, want := range map[string]string{taskFile: "task evidence", transcriptFile: "transcript"} {
+ for path, want := range map[string]string{taskFile: "task evidence", workerFile: "worker notes", transcriptFile: "transcript"} {
got, err := os.ReadFile(path)
if err != nil || string(got) != want {
t.Fatalf("restored %s = %q, %v; want %q", path, got, err, want)
@@ -129,7 +140,7 @@ func TestTaskArchivePackageSkipsSymlink(t *testing.T) {
func TestTaskArchiveStageJournalRollsBackInterruptedMoves(t *testing.T) {
dataDir := t.TempDir()
- taskFile := filepath.Join(dataDir, "tasks", "42", "evidence.txt")
+ taskFile := filepath.Join(dataDir, "tasks", "42", "main", "evidence.txt")
transcriptFile := filepath.Join(dataDir, "transcripts", "exp73-worker.jsonl")
for _, path := range []string{taskFile, transcriptFile} {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
@@ -168,18 +179,18 @@ func TestTaskArchiveStageJournalRollsBackInterruptedMoves(t *testing.T) {
func TestTaskArchiveRestoreJournalRollsBackInterruptedInstall(t *testing.T) {
dataDir := t.TempDir()
extracted := filepath.Join(dataDir, "archives", "tasks", ".restore", "11-test")
- source := filepath.Join(extracted, "files", "tasks", "42", "evidence.txt")
+ source := filepath.Join(extracted, "files", "tasks", "42", "main", "evidence.txt")
if err := os.MkdirAll(filepath.Dir(source), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(source, []byte("evidence"), 0o600); err != nil {
t.Fatal(err)
}
- _, err := installTaskArchiveFiles(dataDir, extracted, "42", 11)
+ _, err := installTaskArchiveFiles(dataDir, extracted, "42", 11, ExecPrivilege{})
if err != nil {
t.Fatal(err)
}
- destination := filepath.Join(dataDir, "tasks", "42", "evidence.txt")
+ destination := filepath.Join(dataDir, "tasks", "42", "main", "evidence.txt")
if _, err := os.Stat(destination); err != nil {
t.Fatal(err)
}
diff --git a/server/task_archives.go b/server/task_archives.go
index 836c2d8..8a61632 100644
--- a/server/task_archives.go
+++ b/server/task_archives.go
@@ -316,7 +316,7 @@ func (s *Server) restoreTaskArchivePayload(job *pgdb.TaskArchive, snapshot *pgdb
}
}
_ = s.m.pg.UpdateTaskArchiveProgress(job.ID, "restore_files", 55)
- files, err := installTaskArchiveFiles(s.m.dir, extracted, strconv.FormatInt(job.TaskID, 10), job.ID)
+ files, err := installTaskArchiveFiles(s.m.dir, extracted, strconv.FormatInt(job.TaskID, 10), job.ID, s.execPriv)
if err != nil {
return err
}