mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 21:23:54 +08:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bec7320602 |
+1
-1
@@ -10,7 +10,6 @@ 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
|
||||
|
||||
@@ -25,6 +24,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
- **The OpenAI Responses format no longer defaults to `gpt-5`**: OpenAI shuts `gpt-5` down on 2026-12-11 and lists `gpt-6.2-sol` as its replacement, so `ARTEX_LLM_PROVIDER=openai-responses` without `ARTEX_LLM_MODEL` (or a profile saved through the API without a model) would start failing then. The default is now `gpt-6.2-sol`; a model set in the profile or in `ARTEX_LLM_MODEL` is kept as is. A gateway set with `ARTEX_LLM_BASE_URL` that does not serve `gpt-6.2-sol` needs `ARTEX_LLM_MODEL` set explicitly.
|
||||
- **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI.
|
||||
- **A paused task no longer times out**: the deadline coordinator kept counting while a task was paused, so a task paused past its deadline (or restored paused after a restart) ran a final planner round and was set to `timeout` before it could be resumed, and after a resume the engine still used the deadline cached before the pause. The coordinator now waits while the task is paused, and resuming refreshes the cached deadline with the paused interval credited back (#1).
|
||||
- **The empty sandbox egress warning is written once per task start.** In `ARTEX_SANDBOX=required` mode, the warning added in #833 for a task whose scope rows grant no egress was appended again, as an activity and a log line, on every `Engine.Run` call. The engine calls `Run` again on a task that is already running (resume, intent rerun, finding follow-up, goal decomposition, the active-task endpoint), so the activity feed filled up with copies. The check now runs only when the task really starts.
|
||||
|
||||
### Removed
|
||||
|
||||
|
||||
+14
-11
@@ -952,17 +952,6 @@ func (e *Engine) Run(ctx context.Context, t *Task) {
|
||||
}
|
||||
return
|
||||
}
|
||||
// Loud, not silent (#830): a chat-spawned task can carry scope rows that
|
||||
// grant no egress (agent-stamped company links stay unapproved), leaving
|
||||
// the proxy allowlist empty so every connection 403s with no hint why.
|
||||
if e.m != nil && t.Store != nil {
|
||||
if tid, perr := strconv.ParseInt(t.ID, 10, 64); perr == nil {
|
||||
if msg := emptyEgressScopeWarning(e.m.pg, tid, taskSandboxRunInfo(e.m.pg, e.sandboxDataDir, t.ID)); msg != "" {
|
||||
log.Printf("[sandbox] task %s: %s", t.ID, msg)
|
||||
_, _ = t.Store.AppendActivity(db.Activity{Kind: "system", IsError: true, Summary: msg})
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if e.sandboxMode == sandbox.ModeOff && t.Store != nil {
|
||||
_, _ = t.Store.AppendActivity(db.Activity{
|
||||
Kind: "system",
|
||||
@@ -986,6 +975,20 @@ func (e *Engine) Run(ctx context.Context, t *Task) {
|
||||
e.started.Delete(t.ID)
|
||||
return
|
||||
}
|
||||
// Loud, not silent (#830): a chat-spawned task can carry scope rows that
|
||||
// grant no egress (agent-stamped company links stay unapproved), leaving
|
||||
// the proxy allowlist empty so every connection 403s with no hint why.
|
||||
// Checked only once the task really starts: Run is called again on a task
|
||||
// that is already running (resume, intent rerun, follow-ups), and each of
|
||||
// those calls must not append another warning.
|
||||
if e.sandboxMode == sandbox.ModeRequired && e.m != nil && t.Store != nil {
|
||||
if tid, perr := strconv.ParseInt(t.ID, 10, 64); perr == nil {
|
||||
if msg := emptyEgressScopeWarning(e.m.pg, tid, taskSandboxRunInfo(e.m.pg, e.sandboxDataDir, t.ID)); msg != "" {
|
||||
log.Printf("[sandbox] task %s: %s", t.ID, msg)
|
||||
_, _ = t.Store.AppendActivity(db.Activity{Kind: "system", IsError: true, Summary: msg})
|
||||
}
|
||||
}
|
||||
}
|
||||
e.touch(t.ID)
|
||||
runTaskRoutine(rt, func(loopCtx context.Context) { e.plannerLoop(loopCtx, t) })
|
||||
runTaskRoutine(rt, func(loopCtx context.Context) { e.claimSweepLoop(loopCtx, t) })
|
||||
|
||||
@@ -509,12 +509,6 @@ 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)
|
||||
|
||||
@@ -470,14 +470,6 @@ 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,
|
||||
@@ -1974,118 +1966,6 @@ 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()
|
||||
|
||||
@@ -1,181 +0,0 @@
|
||||
//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"))
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
//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)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
)
|
||||
|
||||
const (
|
||||
emptyEgressPrefix = "sandbox egress empty"
|
||||
sandboxOffPrefix = "sandbox=off"
|
||||
)
|
||||
|
||||
// TestEmptyEgressWarningOncePerStart pins the #830 warning (added in #833) to a
|
||||
// real task start. Engine.Run is called again on a task that is already
|
||||
// running (resume, intent rerun, finding follow-up, POST /api/active, goal
|
||||
// decomposition), and those calls only nudge the planner: they must not append
|
||||
// another "sandbox egress empty" activity or log line each time.
|
||||
func TestEmptyEgressWarningOncePerStart(t *testing.T) {
|
||||
skipWithoutDSN(t)
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { m.Close() })
|
||||
if err := m.SetWorkers(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
suffix := strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
approvedCo, _, _, _, _, err := m.pg.Companies().CreateCompanyWithScope("WarnOnceCo-"+suffix, "",
|
||||
[]db.ScopeInput{{Kind: "cidr", Value: "203.0.113.0/24"}}, "test fixture", true)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCompanyWithScope: %v", err)
|
||||
}
|
||||
|
||||
newTask := func(t *testing.T, name string, opts db.TaskCreateOptions) *Task {
|
||||
t.Helper()
|
||||
task, err := m.CreateTaskWithOptions(name+"-"+suffix, "goal", opts)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTaskWithOptions(%s): %v", name, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = m.pg.DeleteTask(mustTaskID(t, task.ID)) })
|
||||
return task
|
||||
}
|
||||
newEngine := func(t *testing.T, mode string, task *Task) *Engine {
|
||||
t.Helper()
|
||||
e := NewEngine(m)
|
||||
e.SetSandbox(&stubSandboxClient{health: sandbox.HealthResponse{OK: true, Docker: true}}, mode, t.TempDir())
|
||||
t.Cleanup(func() { e.StopTask(task.ID) })
|
||||
return e
|
||||
}
|
||||
// run calls Engine.Run n times and returns how many warning log lines it wrote.
|
||||
run := func(t *testing.T, e *Engine, task *Task, n int) int {
|
||||
t.Helper()
|
||||
out := captureLog(t, func() {
|
||||
for i := 0; i < n; i++ {
|
||||
e.Run(context.Background(), task)
|
||||
}
|
||||
})
|
||||
return strings.Count(out, "[sandbox] task "+task.ID+": "+emptyEgressPrefix)
|
||||
}
|
||||
count := func(t *testing.T, task *Task) (warn, off int) {
|
||||
t.Helper()
|
||||
acts, _, err := task.Store.ActivityList(nil, 0, 500)
|
||||
if err != nil {
|
||||
t.Fatalf("ActivityList: %v", err)
|
||||
}
|
||||
for _, a := range acts {
|
||||
switch {
|
||||
case strings.HasPrefix(a.Summary, emptyEgressPrefix):
|
||||
warn++
|
||||
if !a.IsError || a.Kind != "system" {
|
||||
t.Errorf("warning activity must be a system error, got kind=%q is_error=%v", a.Kind, a.IsError)
|
||||
}
|
||||
case strings.HasPrefix(a.Summary, sandboxOffPrefix):
|
||||
off++
|
||||
}
|
||||
}
|
||||
return warn, off
|
||||
}
|
||||
|
||||
// The trap of #830: the agent stamped the company link, nothing is approved.
|
||||
t.Run("agent stamped company warns once per start", func(t *testing.T) {
|
||||
task := newTask(t, "warn-once-trap", db.TaskCreateOptions{CompanyIDs: []int64{approvedCo}, CompanyScopeByAgent: true})
|
||||
e := newEngine(t, sandbox.ModeRequired, task)
|
||||
if logs := run(t, e, task, 3); logs != 1 {
|
||||
t.Errorf("3 Run calls wrote %d warning log lines, want 1", logs)
|
||||
}
|
||||
if warn, off := count(t, task); warn != 1 || off != 0 {
|
||||
t.Fatalf("3 Run calls on one engine: warnings=%d off-notes=%d, want 1 and 0", warn, off)
|
||||
}
|
||||
// A new engine on the same task is a new real start (process restart, boot
|
||||
// restore): it warns again, once.
|
||||
e.StopTask(task.ID)
|
||||
e2 := newEngine(t, sandbox.ModeRequired, task)
|
||||
if logs := run(t, e2, task, 2); logs != 1 {
|
||||
t.Errorf("restart: 2 Run calls wrote %d warning log lines, want 1", logs)
|
||||
}
|
||||
if warn, _ := count(t, task); warn != 2 {
|
||||
t.Fatalf("after a restart: warnings=%d, want 2 (one per real start)", warn)
|
||||
}
|
||||
})
|
||||
|
||||
// The engine already runs the task (its own start is where the warning
|
||||
// belongs), so every later Run is a nudge and never warns.
|
||||
t.Run("already started task never warns on a nudge", func(t *testing.T) {
|
||||
task := newTask(t, "warn-once-started", db.TaskCreateOptions{CompanyIDs: []int64{approvedCo}, CompanyScopeByAgent: true})
|
||||
e := newEngine(t, sandbox.ModeRequired, task)
|
||||
e.started.Store(task.ID, true)
|
||||
if logs := run(t, e, task, 3); logs != 0 {
|
||||
t.Errorf("3 nudges wrote %d warning log lines, want 0", logs)
|
||||
}
|
||||
if warn, _ := count(t, task); warn != 0 {
|
||||
t.Fatalf("3 nudges on a running task: warnings=%d, want 0", warn)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("agent added root domain warns once", func(t *testing.T) {
|
||||
task := newTask(t, "warn-once-agent-domain", db.TaskCreateOptions{})
|
||||
if _, err := m.pg.Assets().AddAgentScope(mustTaskID(t, task.ID), "root_domain", "agent.example", "test fixture", "agent"); err != nil {
|
||||
t.Fatalf("AddAgentScope: %v", err)
|
||||
}
|
||||
e := newEngine(t, sandbox.ModeRequired, task)
|
||||
run(t, e, task, 2)
|
||||
if warn, _ := count(t, task); warn != 1 {
|
||||
t.Fatalf("agent root_domain only: warnings=%d, want 1", warn)
|
||||
}
|
||||
})
|
||||
|
||||
// A non-empty allowlist never warns, however many times Run is called.
|
||||
quiet := []struct {
|
||||
name string
|
||||
setup func(t *testing.T) *Task
|
||||
}{
|
||||
{"operator selected approved company", func(t *testing.T) *Task {
|
||||
return newTask(t, "warn-once-op-company", db.TaskCreateOptions{CompanyIDs: []int64{approvedCo}})
|
||||
}},
|
||||
{"agent company plus intercept allow rule", func(t *testing.T) *Task {
|
||||
task := newTask(t, "warn-once-intercept", db.TaskCreateOptions{CompanyIDs: []int64{approvedCo}, CompanyScopeByAgent: true})
|
||||
if _, err := m.pg.Exec(`INSERT INTO task_intercept_rules(task_id, enabled, action, kind, pattern) VALUES ($1,true,'allow','domain_suffix','example.test')`, mustTaskID(t, task.ID)); err != nil {
|
||||
t.Fatalf("insert intercept rule: %v", err)
|
||||
}
|
||||
return task
|
||||
}},
|
||||
{"agent company approved by the operator", func(t *testing.T) *Task {
|
||||
task := newTask(t, "warn-once-approved", db.TaskCreateOptions{CompanyIDs: []int64{approvedCo}, CompanyScopeByAgent: true})
|
||||
if _, err := m.pg.Assets().AddOperatorScope(mustTaskID(t, task.ID), "company", strconv.FormatInt(approvedCo, 10), "test fixture"); err != nil {
|
||||
t.Fatalf("AddOperatorScope(company): %v", err)
|
||||
}
|
||||
return task
|
||||
}},
|
||||
{"operator root domain", func(t *testing.T) *Task {
|
||||
task := newTask(t, "warn-once-op-domain", db.TaskCreateOptions{})
|
||||
if _, err := m.pg.Assets().AddOperatorScope(mustTaskID(t, task.ID), "root_domain", "operator.example", "test fixture"); err != nil {
|
||||
t.Fatalf("AddOperatorScope(root_domain): %v", err)
|
||||
}
|
||||
return task
|
||||
}},
|
||||
}
|
||||
for _, tc := range quiet {
|
||||
t.Run(tc.name+" does not warn", func(t *testing.T) {
|
||||
task := tc.setup(t)
|
||||
e := newEngine(t, sandbox.ModeRequired, task)
|
||||
run(t, e, task, 2)
|
||||
if warn, off := count(t, task); warn != 0 || off != 0 {
|
||||
t.Fatalf("non-empty allowlist: warnings=%d off-notes=%d, want 0 and 0", warn, off)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// sandbox=off has no egress proxy: no egress warning. The off note keeps its
|
||||
// existing behaviour (one per Run call, not changed here) and must not grow.
|
||||
t.Run("sandbox off never warns", func(t *testing.T) {
|
||||
task := newTask(t, "warn-once-off", db.TaskCreateOptions{CompanyIDs: []int64{approvedCo}, CompanyScopeByAgent: true})
|
||||
e := newEngine(t, sandbox.ModeOff, task)
|
||||
const runs = 3
|
||||
if logs := run(t, e, task, runs); logs != 0 {
|
||||
t.Errorf("sandbox=off wrote %d egress warning log lines, want 0", logs)
|
||||
}
|
||||
warn, off := count(t, task)
|
||||
t.Logf("sandbox=off: %d off-notes after %d Run calls", off, runs)
|
||||
if warn != 0 {
|
||||
t.Fatalf("sandbox=off: warnings=%d, want 0", warn)
|
||||
}
|
||||
if off < 1 || off > runs {
|
||||
t.Fatalf("sandbox=off: off-notes=%d after %d Run calls, want between 1 and %d", off, runs, runs)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user