Compare commits

...
Author SHA1 Message Date
BaaRai 40b4d41b26 ci: trigger the workflow on the ready pull request 2026-12-02 20:10:30 +01:00
BaaRai 3f610625ae fix(server): keep task delete staging out of the executor share
Since #822 a task deletion stages its files in an owner-only
.delete-staging-<id>-* directory next to each source, inside data/tasks,
data/spill/tasks and data/transcripts. shareRunDirs treated every
directory under data/tasks as a task directory, so a staging directory
left by a crash, or kept by a failed rollback or purge, became 0755 and
its staged workspace was shared with the executor group at the next
start with the executor drop enabled.

shareRunDirs now shares only directories named by a canonical task ID.
NewManager settles leftover staging before any task runs: the staging of
a task that is no longer in the database is removed, the staged entries
of a live task move back when their original path is free, and an entry
whose path exists again, or an unexpected name, stays staged and is
logged. Only exact .delete-staging-<id>-<digits> directories are
considered, and symlinks are never followed.
2026-12-02 18:04:31 +01:00
5 changed files with 448 additions and 0 deletions
+1
View File
@@ -10,6 +10,7 @@ All notable changes to this project are documented in this file. The format is b
- **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out.
- **`WebFetch` redirects through a proxy are checked against the sandbox egress policy.** In `ARTEX_SANDBOX=required` mode only the first URL of a `WebFetch` call was checked against the task's egress policy. With an operator or recording proxy configured, the sandbox dialer only connects to the proxy, so a redirect from an allowed URL to a cloud metadata address (169.254.169.254), a loopback or private address, or a domain outside the task scope was followed. Every redirect hop is now checked against the same egress policy before it is followed, and a hop the policy does not allow fails the call.
- **Sandbox egress URL checks fail closed on DNS and check every resolved address.** In `ARTEX_SANDBOX=required` mode, `EgressPolicy.CheckURL` (the check WebFetch, the shared browser and the custom HTTP tool run on a target URL) allowed an in-scope name whose lookup failed or returned no addresses, and allowed a name that resolved to several addresses as soon as the first allowed one was found, even when the others were private, loopback, IPv6 or the cloud metadata address. Through an explicit proxy or the shared browser, which resolve the target themselves, this is the only check on the target. A lookup error or an empty answer is now a denial, and every resolved address (A and AAAA, all answers) must be allowed. Sandboxed custom HTTP tool transports now disable keep-alives on every transport, including an operator proxy and the recording proxy, so each request opens a new connection that the sandbox dialer checks again (#794). Behaviour change: an in-scope name the panel cannot resolve is refused, even when the proxy or the browser could resolve it, and a name that answers a private, loopback, link-local or IPv6 address next to a public one is refused unless that address is in the scope CIDRs.
- **An interrupted task deletion no longer shares its staging directory with the executor group.** Since #822 a task deletion stages the task files in an owner-only `.delete-staging-<id>-*` directory next to each source (`data/tasks`, `data/spill/tasks`, `data/transcripts`). A staging directory left by a crash, or kept on purpose by a failed rollback or purge, was treated as a task directory at the next start with the executor drop enabled: the start made it world-readable and shared the staged workspace with the executor group. The start now shares only directories named by a task ID, and settles leftover staging before any task runs: the staging of a deleted task is removed, the staged files of a live task move back when their original path is free, and an entry whose path exists again stays staged, unshared, and is logged.
### Added
+6
View File
@@ -509,6 +509,12 @@ func shareRunDirs(dataDir string, gid int) error {
}
dir := filepath.Join(root, e.Name())
if sub == "tasks" {
// Only a canonical task ID names a task directory. A delete staging
// directory (.delete-staging-<id>-*) left by an interrupted deletion
// stays owner-only, like any other entry.
if id, ok := canonicalTaskID(e.Name()); !ok || id != e.Name() {
continue
}
err = shareTaskDir(dir, gid)
} else {
err = shareRunDir(dir, gid)
+120
View File
@@ -470,6 +470,14 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
if err := pg.EnsureLLMUsageTable(); err != nil {
log.Printf("[llmusage] create table: %v", err)
}
// Before any task runs: settle the file staging of a deletion that did not
// finish. What cannot be settled stays staged and is reported.
if err := recoverTaskFileStages(dir, func(id int64) (bool, error) {
task, err := pg.GetTask(id)
return task != nil, err
}); err != nil {
log.Printf("[task-delete] recover file staging: %v", err)
}
m := &Manager{
dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg),
taskUserAgents: cfg.TaskUserAgents,
@@ -1966,6 +1974,118 @@ func deleteTaskFiles(dataDir, taskID string, explorationID int64) (bool, error)
return deleted, nil
}
const taskFileStagePrefix = ".delete-staging-"
// taskFileStageID returns the task ID in the name of a directory stageTaskFiles
// creates: .delete-staging-<canonical task ID>-<decimal os.MkdirTemp suffix>.
func taskFileStageID(name string) (string, bool) {
rest, ok := strings.CutPrefix(name, taskFileStagePrefix)
if !ok {
return "", false
}
id, suffix, ok := strings.Cut(rest, "-")
if !ok || suffix == "" || strings.Trim(suffix, "0123456789") != "" {
return "", false
}
if canonical, ok := canonicalTaskID(id); !ok || canonical != id {
return "", false
}
return id, true
}
// taskFileStageEntryValid reports whether name can be an entry stageTaskFiles
// moved from parent for taskID: the task workspace or spill directory, or an
// exploration transcript (exp<N>-...).
func taskFileStageEntryValid(dataDir, parent, taskID, name string) bool {
if parent != filepath.Join(dataDir, "transcripts") {
return name == taskID
}
digits, _, ok := strings.Cut(strings.TrimPrefix(name, "exp"), "-")
return strings.HasPrefix(name, "exp") && ok && digits != "" && strings.Trim(digits, "0123456789") == ""
}
// recoverTaskFileStages resolves the staging directories a task deletion leaves
// next to the files it moves when it does not finish: a crash between staging and
// the purge, or a failed rollback or purge. taskAlive reports whether the task is
// still in the database. The staging of a deleted task is removed. The staged
// entries of a live task move back when their original path is free; an entry
// whose path exists again, or an unexpected name, stays in the owner-only staging
// directory, which shareRunDirs does not share. Symlinks are never followed.
func recoverTaskFileStages(dataDir string, taskAlive func(int64) (bool, error)) error {
var errs []error
// The parents stageTaskFiles stages in: the task workspace, the spill
// directory (agent.TaskSpillDir) and the transcripts.
parents := []string{
filepath.Join(dataDir, "tasks"),
filepath.Join(dataDir, "spill", "tasks"),
filepath.Join(dataDir, "transcripts"),
}
for _, parent := range parents {
entries, err := os.ReadDir(parent)
if os.IsNotExist(err) {
continue
}
if err != nil {
errs = append(errs, err)
continue
}
for _, entry := range entries {
taskID, ok := taskFileStageID(entry.Name())
if !ok || !entry.IsDir() {
continue
}
stageDir := filepath.Join(parent, entry.Name())
n, _ := strconv.ParseInt(taskID, 10, 64)
alive, err := taskAlive(n)
if err != nil {
errs = append(errs, fmt.Errorf("check task %s for %s: %w", taskID, stageDir, err))
continue
}
if !alive {
if err := os.RemoveAll(stageDir); err != nil {
errs = append(errs, fmt.Errorf("remove task file stage %s: %w", stageDir, err))
}
continue
}
if err := restoreTaskFileStage(dataDir, parent, stageDir, taskID); err != nil {
errs = append(errs, err)
}
}
}
return errors.Join(errs...)
}
// restoreTaskFileStage moves the entries of stageDir back into parent, never over
// an existing path, and removes stageDir once it is empty.
func restoreTaskFileStage(dataDir, parent, stageDir, taskID string) error {
staged, err := os.ReadDir(stageDir)
if err != nil {
return err
}
var errs []error
for _, e := range staged {
if !taskFileStageEntryValid(dataDir, parent, taskID, e.Name()) {
errs = append(errs, fmt.Errorf("unexpected entry %q kept in task file stage %s", e.Name(), stageDir))
continue
}
dest := filepath.Join(parent, e.Name())
if _, err := os.Lstat(dest); err == nil {
errs = append(errs, fmt.Errorf("restore destination already exists, kept in task file stage %s: %s", stageDir, dest))
continue
} else if !os.IsNotExist(err) {
errs = append(errs, fmt.Errorf("inspect restore destination %s: %w", dest, err))
continue
}
if err := os.Rename(filepath.Join(stageDir, e.Name()), dest); err != nil {
errs = append(errs, fmt.Errorf("restore %s: %w", dest, err))
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return os.Remove(stageDir)
}
func (m *Manager) Task(id string) (*Task, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
+181
View File
@@ -0,0 +1,181 @@
//go:build linux
package server
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
// leaveTaskFileStage stages task 78 without committing or rolling back, as a crash
// between the two would, and returns the staging directories.
func leaveTaskFileStage(t *testing.T, dataDir string) []string {
t.Helper()
for rel, body := range stageFixtureFiles {
writeStageFixture(t, filepath.Join(dataDir, rel), body)
}
stage, err := stageTaskFiles(dataDir, "78", 5)
if err != nil {
t.Fatal(err)
}
if len(stage.stageDirs) != 3 {
t.Fatalf("staging directories = %v, want one per parent", stage.stageDirs)
}
return stage.stageDirs
}
func taskAliveFunc(alive map[int64]bool) func(int64) (bool, error) {
return func(id int64) (bool, error) { return alive[id], nil }
}
func TestRecoverTaskFileStagesRemovesStagingOfDeletedTask(t *testing.T) {
dataDir := t.TempDir()
stages := leaveTaskFileStage(t, dataDir)
if err := recoverTaskFileStages(dataDir, taskAliveFunc(nil)); err != nil {
t.Fatal(err)
}
for _, dir := range stages {
assertPathMissing(t, dir)
}
for rel := range stageFixtureFiles {
assertPathMissing(t, filepath.Join(dataDir, rel))
}
}
func TestRecoverTaskFileStagesRestoresLiveTask(t *testing.T) {
dataDir := t.TempDir()
stages := leaveTaskFileStage(t, dataDir)
if err := recoverTaskFileStages(dataDir, taskAliveFunc(map[int64]bool{78: true})); err != nil {
t.Fatal(err)
}
for _, dir := range stages {
assertPathMissing(t, dir)
}
for rel, body := range stageFixtureFiles {
if got, err := os.ReadFile(filepath.Join(dataDir, rel)); err != nil || string(got) != body {
t.Fatalf("%s after recovery = %q, %v; want %q", rel, got, err, body)
}
}
}
// A live task whose workspace exists again keeps the staged copy: nothing is
// overwritten, the other entries come back, and the staging directory stays
// owner-only and unshared at the next start.
func TestRecoverTaskFileStagesKeepsConflictUnsharedAsRoot(t *testing.T) {
if os.Geteuid() != 0 {
t.Skip("needs root")
}
dataDir := t.TempDir()
stages := leaveTaskFileStage(t, dataDir)
writeStageFixture(t, filepath.Join(dataDir, "tasks", "78", "main", "new.txt"), "new workspace")
err := recoverTaskFileStages(dataDir, taskAliveFunc(map[int64]bool{78: true}))
if err == nil || !strings.Contains(err.Error(), "restore destination already exists") {
t.Fatalf("recovery err = %v, want the conflict reported", err)
}
if got, err := os.ReadFile(filepath.Join(dataDir, "tasks", "78", "main", "new.txt")); err != nil || string(got) != "new workspace" {
t.Fatalf("existing workspace changed: %q, %v", got, err)
}
assertPathMissing(t, filepath.Join(dataDir, "tasks", "78", "main", "notes.txt"))
var kept string
for _, dir := range stages {
if filepath.Dir(dir) == filepath.Join(dataDir, "tasks") {
kept = dir
continue
}
assertPathMissing(t, dir)
}
if got, err := os.ReadFile(filepath.Join(kept, "78", "main", "notes.txt")); err != nil || string(got) != "workspace" {
t.Fatalf("staged workspace = %q, %v; want it kept", got, err)
}
for _, rel := range []string{filepath.Join("spill", "tasks", "78", "output-1-1.txt"), filepath.Join("transcripts", "exp5-main.jsonl")} {
assertPathExists(t, filepath.Join(dataDir, rel))
}
if err := shareRunDirs(dataDir, os.Getgid()); err != nil {
t.Fatal(err)
}
for _, path := range []string{kept, filepath.Join(kept, "78"), filepath.Join(kept, "78", "main")} {
fi, err := os.Lstat(path)
if err != nil {
t.Fatal(err)
}
if fi.Mode()&(os.ModeSetgid|0o020) != 0 || (path == kept && fi.Mode().Perm() != 0o700) {
t.Errorf("%s shared after recovery and shareRunDirs: %v", path, fi.Mode())
}
}
}
// Only .delete-staging-<canonical task ID>-<digits> directories are recovered.
// Other names, symlinks and files are left alone, whatever the database says.
func TestRecoverTaskFileStagesIgnoresOtherNames(t *testing.T) {
dataDir := t.TempDir()
tasks := filepath.Join(dataDir, "tasks")
outside := t.TempDir()
writeStageFixture(t, filepath.Join(outside, "78", "keep"), "outside")
names := []string{
".delete-staging-078-123",
".delete-staging-+78-123",
".delete-staging-0-123",
".delete-staging--1-123",
".delete-staging-78-",
".delete-staging-78-12a",
".delete-staging-78",
".delete-staging-abc-123",
"delete-staging-78-123",
".delete-stagingx78-123",
}
for _, name := range names {
writeStageFixture(t, filepath.Join(tasks, name, "78", "keep"), "x")
}
if err := os.Symlink(outside, filepath.Join(tasks, ".delete-staging-78-555")); err != nil {
t.Fatal(err)
}
writeStageFixture(t, filepath.Join(tasks, ".delete-staging-78-556"), "a file")
called := false
err := recoverTaskFileStages(dataDir, func(int64) (bool, error) {
called = true
return false, nil
})
if err != nil || called {
t.Fatalf("recovery err=%v, task lookup called=%v; want neither", err, called)
}
for _, name := range names {
assertPathExists(t, filepath.Join(tasks, name, "78", "keep"))
}
assertPathExists(t, filepath.Join(tasks, ".delete-staging-78-555"))
assertPathExists(t, filepath.Join(tasks, ".delete-staging-78-556"))
assertPathExists(t, filepath.Join(outside, "78", "keep"))
assertPathMissing(t, filepath.Join(tasks, "78"))
}
// An unexpected entry inside a staging directory is never moved into the parent,
// and a failed task lookup leaves the staging untouched.
func TestRecoverTaskFileStagesKeepsUnexpectedEntriesAndLookupErrors(t *testing.T) {
dataDir := t.TempDir()
tasks := filepath.Join(dataDir, "tasks")
writeStageFixture(t, filepath.Join(tasks, ".delete-staging-78-1", "79", "keep"), "other task")
writeStageFixture(t, filepath.Join(dataDir, "transcripts", ".delete-staging-78-2", "notes.jsonl"), "not a transcript")
writeStageFixture(t, filepath.Join(tasks, ".delete-staging-80-3", "80", "keep"), "lookup failed")
lookupErr := errors.New("database unavailable")
err := recoverTaskFileStages(dataDir, func(id int64) (bool, error) {
if id == 80 {
return false, lookupErr
}
return true, nil
})
if err == nil || !errors.Is(err, lookupErr) || !strings.Contains(err.Error(), "unexpected entry") {
t.Fatalf("recovery err = %v, want the unexpected entries and the lookup error", err)
}
assertPathExists(t, filepath.Join(tasks, ".delete-staging-78-1", "79", "keep"))
assertPathMissing(t, filepath.Join(tasks, "79"))
assertPathExists(t, filepath.Join(dataDir, "transcripts", ".delete-staging-78-2", "notes.jsonl"))
assertPathMissing(t, filepath.Join(dataDir, "transcripts", "notes.jsonl"))
assertPathExists(t, filepath.Join(tasks, ".delete-staging-80-3", "80", "keep"))
assertPathMissing(t, filepath.Join(tasks, "80"))
}
+140
View File
@@ -0,0 +1,140 @@
//go:build linux
package server
import (
"os"
"path/filepath"
"syscall"
"testing"
)
// mountTmpfs mounts a private tmpfs on dir, or skips the test when this process
// may not mount (an unprivileged run outside a mount namespace).
func mountTmpfs(t *testing.T, dir string) {
t.Helper()
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := syscall.Mount("tmpfs", dir, "tmpfs", 0, "size=8m"); err != nil {
t.Skipf("cannot mount a tmpfs to simulate separate mounts: %v", err)
}
t.Cleanup(func() { _ = syscall.Unmount(dir, syscall.MNT_DETACH) })
}
func writeStageFixture(t *testing.T, path, body string) {
t.Helper()
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)
}
}
// stageFixtureFiles are the files task 78 (exploration 5) owns in every parent
// stageTaskFiles stages in.
var stageFixtureFiles = map[string]string{
filepath.Join("tasks", "78", "main", "notes.txt"): "workspace",
filepath.Join("spill", "tasks", "78", "output-1-1.txt"): "spill",
filepath.Join("transcripts", "exp5-main.jsonl"): "transcript",
filepath.Join("transcripts", "exp5-worker-i2", "sidechain.jsonl"): "sidechain",
}
// The task workspace, spill and transcript parents can each be a separate mount.
// Staging, rollback and commit must stay on each source mount (no EXDEV).
func TestStageTaskFilesAcrossMounts(t *testing.T) {
dataDir := t.TempDir()
for _, sub := range []string{"tasks", filepath.Join("spill", "tasks"), "transcripts"} {
mountTmpfs(t, filepath.Join(dataDir, sub))
}
for rel, body := range stageFixtureFiles {
writeStageFixture(t, filepath.Join(dataDir, rel), body)
}
stage, err := stageTaskFiles(dataDir, "78", 5)
if err != nil {
t.Fatalf("stage across mounts: %v", err)
}
for rel := range stageFixtureFiles {
assertPathMissing(t, filepath.Join(dataDir, rel))
}
if err := stage.rollback(); err != nil {
t.Fatalf("rollback across mounts: %v", err)
}
for rel, body := range stageFixtureFiles {
if got, err := os.ReadFile(filepath.Join(dataDir, rel)); err != nil || string(got) != body {
t.Fatalf("%s after rollback = %q, %v; want %q", rel, got, err, body)
}
}
deleted, err := deleteTaskFiles(dataDir, "78", 5)
if err != nil || !deleted {
t.Fatalf("delete across mounts: deleted=%v err=%v", deleted, err)
}
for rel := range stageFixtureFiles {
assertPathMissing(t, filepath.Join(dataDir, rel))
}
for _, sub := range []string{"tasks", filepath.Join("spill", "tasks"), "transcripts"} {
if left, _ := filepath.Glob(filepath.Join(dataDir, sub, ".delete-staging-*")); len(left) != 0 {
t.Fatalf("staging left in %s: %v", sub, left)
}
}
}
// A deletion interrupted between staging and its commit leaves an owner-only
// staging directory in data/tasks. Preparing the executor drop at the next start
// must not share it with the executor group.
func TestShareRunDirsSkipsDeleteStagingAsRoot(t *testing.T) {
if os.Geteuid() != 0 {
t.Skip("needs root")
}
dataDir := t.TempDir()
writeStageFixture(t, filepath.Join(dataDir, "tasks", "78", "main", "notes.txt"), "workspace")
writeStageFixture(t, filepath.Join(dataDir, "tasks", "79", "main", "notes.txt"), "other task")
if _, err := stageTaskFiles(dataDir, "78", 5); err != nil {
t.Fatal(err)
}
stages, err := filepath.Glob(filepath.Join(dataDir, "tasks", ".delete-staging-78-*"))
if err != nil || len(stages) != 1 {
t.Fatalf("staging directories = %v (%v), want one", stages, err)
}
type snapshot struct {
mode os.FileMode
uid, gid uint32
}
take := func() map[string]snapshot {
out := map[string]snapshot{}
err := filepath.Walk(stages[0], func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
st := fi.Sys().(*syscall.Stat_t)
out[path] = snapshot{fi.Mode(), st.Uid, st.Gid}
return nil
})
if err != nil {
t.Fatal(err)
}
return out
}
before := take()
if got := before[stages[0]].mode.Perm(); got != 0o700 {
t.Fatalf("staging directory mode = %v, want 0700", got)
}
if err := shareRunDirs(dataDir, os.Getgid()); err != nil {
t.Fatalf("shareRunDirs: %v", err)
}
after := take()
if len(after) != len(before) {
t.Fatalf("staging entries changed: before %v, after %v", before, after)
}
for path, want := range before {
if got := after[path]; got != want {
t.Errorf("%s: %v uid %d gid %d after shareRunDirs, want %v uid %d gid %d", path, got.mode, got.uid, got.gid, want.mode, want.uid, want.gid)
}
}
// A real task directory is still shared.
checkDir(t, filepath.Join(dataDir, "tasks", "79", "main"), uint32(os.Getgid()), leafDirMode)
}