mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-04 05:33:55 +08:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a4fa45245 | ||
|
|
aeb094d5ef | ||
|
|
eb05248804 | ||
|
|
130fe9a0c4 | ||
|
|
e4f6de91d2 | ||
|
|
6f544185cf |
@@ -6,6 +6,9 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Security
|
||||
|
||||
- **`ask_operator` reads run-directory images through a task-rooted handle.** The copy path resolved the asking run directory with `EvalSymlinks` and then opened the resolved path, so a worker that replaced its run directory with a symlink to `/` made the confinement root `/`: an absolute `image_path` to a symlink named `*.png` could have the panel copy `/proc/1/environ` or `/app/keys/jwt.key` into `tasks/<id>/uploads`, where the worker reads it. The read and the upload write are now both anchored with `os.Root` at `tasks/<id>`; the run directory must be a real directory, no path component may be a symlink, the opened file must be the one `Lstat` saw, and the copy is bounded to 10 MB. Existing `..`, outside-path and non-image refusals are unchanged.
|
||||
- **Task archives no longer follow a directory swapped for a symlink while the task is packed.** The packer, running as root, listed each directory of the staged run tree and then opened its files by full path, so code running as the executor uid that kept a working directory inside the run tree could replace a listed directory with a symlink (for example to `/app/keys`) and have root-only files such as the session signing key copied into the archive, then read them back from the run directory after a restore. The packer now walks and opens the payload through an `os.Root` anchored at it, so no lookup can leave the payload, and refuses the archive when a file it opens is not the regular file the walk listed (device and inode compared). Symlinks already present in the run tree are still skipped and never followed. Behaviour change: an archive whose run tree changes this way while it is packed fails instead of completing, and the task stays in place.
|
||||
- **Agent sessions no longer offer Norma's background-task tools.** Norma adds `Monitor`, `TaskOutput`, `TaskStop` and `TaskList` to every session that does not opt out, and only the connection test and the goal decomposer opted out. `Monitor` starts a shell command in the panel process, not through the sandbox that `Bash` uses, so in `ARTEX_SANDBOX=required` mode a worker, planner, chat or main-agent model could run commands in the panel container, outside the task's worker, and read or write other tasks' workspaces and transcripts. Every agent session is now built through one constructor. It turns these tools off while the sandbox is required, and always for a session that has neither `Bash` nor the interactive shell, so an orchestration agent cannot gain a shell through `Monitor`. Sessions that do have `Bash` or `shell_*` keep them when the sandbox is off: their background runs, PTY sessions and the pause kill switch depend on the same task manager. The constructor also turns a nil tool list into an empty one, because Norma reads nil as "use my own default tools" and installs its unconfined `Bash` and file tools; the tool catalogue resolver also returns an empty list instead of nil when the tools table cannot be read, the case of the Auto chat agent, whose base list is empty.
|
||||
- **The target gate honors operator-approved egress grants.** The gate compared every target with pins only, while the sandbox proxy allowed every port of an operator-approved CIDR grant: a host already inside a granted task or company scope still raised per-port and bare-host approval prompts (pins match `host:port`, and a request naming the host without a port is covered only by a port-0 pin). `CheckTargets` now also consults the grants the operator approved for the task (its approved, unexpanded `task_scope` rows and the entries frozen into `task_scope_egress` by approved company grants, normalized as the proxy allowlist is): a domain matching a granted domain, an address inside a granted CIDR, or a range fully inside one passes as covered by `scope_grant`, recorded once per process and target key as a system-decided allowed row with the target outcome `scope_grant`. Pins, stored exemptions, block rules and human approvals are unchanged: anything outside a grant is decided as before, and task allow rules play no role, as everywhere in the gate. Related to #830, the mirror gap on the network side.
|
||||
- **Chat-spawned tasks inherit fully operator-approved companies (#830).** Migration `0025_company_scope_approved.sql` made company scope an explicit operator decision, but `spawn_task` still stamped the whole company link `approved_by_operator=false`, so a chat-spawned task started with an empty egress allowlist and every connection was denied until an operator approved scope again per task (the trap #833 warns about). `CreateTaskWithOptions` now checks each LLM-selected company: one whose scope inventory exists and is entirely operator-approved and to which the calling task itself holds an operator-approved link carries standing consent, so its task link is inserted approved (a spawn with no task caller - chat session or direct API - inherits nothing, per review on #841) and its grant frozen into `task_scope_egress`, exactly as an operator selection does; a company holding any agent-written (unapproved) row, and one with no scope rows, stay coverage-only, so `add_company_scope`, the ScopeSentry sync and invented ids still grant nothing without a fresh operator decision. Provenance is preserved: `source` stays `agent` and the approval column records the inherited consent row by row. Related: #830, #833.
|
||||
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ import (
|
||||
// contiguous run is coalesced into a single record so the trace shows whole
|
||||
// messages, not dozens of fragments.
|
||||
func captureRun(ctx context.Context, opts agentcore.Options, input string, emit func(db.Activity)) (string, harness.TerminalReason, error) {
|
||||
s := agentcore.NewSession(opts)
|
||||
s := newSession(opts)
|
||||
defer s.Close() // release the session's background-task manager (temp dir + processes)
|
||||
return captureRunSession(ctx, s, input, emit)
|
||||
}
|
||||
|
||||
+1
-1
@@ -276,7 +276,7 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
|
||||
// experimental feature: when enabled, noa takes over context compression (archive centralized under <workDir>/noa/<SessionID>, persistent).
|
||||
enableNoa(&opts, c.noaEnabledFn, c.workDir, "chat-"+sessionID, noaWarn("chat-"+sessionID))
|
||||
ctx = attachSideCapture(ctx, &opts)
|
||||
s := agentcore.NewSession(opts)
|
||||
s := newSession(opts)
|
||||
defer s.Close()
|
||||
// reload prior conversation so the agent has context across turns (each Chat is
|
||||
// a fresh session). First turn: no file yet → Resume loads nothing and proceeds.
|
||||
|
||||
+1
-1
@@ -181,7 +181,7 @@ func DecomposeGoalsWithProvider(ctx context.Context, prov llm.Provider, dataDir,
|
||||
emit(r)
|
||||
}
|
||||
}
|
||||
session := agentcore.NewSession(agentcore.Options{
|
||||
session := newSession(agentcore.Options{
|
||||
Provider: prov,
|
||||
SystemPrompt: []string{sys},
|
||||
DynamicBoundary: 1, // the whole static system prompt gets a cache breakpoint across the turns
|
||||
|
||||
+1
-1
@@ -193,7 +193,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
|
||||
}
|
||||
enableNoa(&opts, m.noaEnabledFn, m.workDir, noaSession, noaWarn(noaSession))
|
||||
ctx = attachSideCapture(ctx, &opts)
|
||||
s := agentcore.NewSession(opts)
|
||||
s := newSession(opts)
|
||||
defer s.Close()
|
||||
// reload the prior conversation from the transcript so the agent has context
|
||||
// across turns (each Chat is a fresh session; without this it can't see earlier
|
||||
|
||||
@@ -2,10 +2,44 @@ package agent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/norma/agentcore"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// newSession builds every Norma session ARTEX runs. Norma's background-task
|
||||
// tools (Monitor, TaskOutput, TaskStop, TaskList) start commands in the panel
|
||||
// process, outside the sandbox that Bash goes through, so no session gets them
|
||||
// while the sandbox is required. With the sandbox off, a session that has no
|
||||
// shell tool still must not gain one through Monitor: orchestration agents get
|
||||
// no background tools at all. A session that does have Bash or the interactive
|
||||
// shell keeps the task manager when the sandbox is off: Bash backgrounds long
|
||||
// commands, the pause kill switch ends a command's whole process group, and the
|
||||
// interactive shell keeps its PTY sessions on the same manager.
|
||||
// A nil tool list makes Norma install its own unconfined file and shell tools,
|
||||
// so nil becomes an empty list.
|
||||
func newSession(opts agentcore.Options) *agentcore.Session {
|
||||
if opts.Tools == nil {
|
||||
opts.Tools = []actool.CoreTool{}
|
||||
}
|
||||
if SandboxRequired() || !hasShellTool(opts.Tools) {
|
||||
opts.DisableBackgroundTasks = true
|
||||
}
|
||||
return agentcore.NewSession(opts)
|
||||
}
|
||||
|
||||
// hasShellTool reports whether the session offers Bash or the interactive shell
|
||||
// (shell_open and its companions), the session tools that need the task manager.
|
||||
func hasShellTool(tools []actool.CoreTool) bool {
|
||||
for _, tool := range tools {
|
||||
if name := tool.Name(); name == "Bash" || strings.HasPrefix(name, "shell_") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// resumeSession reloads the persisted conversation of session id into s. Norma's
|
||||
// transcript.Store.Load treats a missing file as a fresh session (no records, no
|
||||
// error); any other failure, such as a corrupt line or an unreadable path, is
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
"github.com/Autumn-27/norma/agentcore"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// Norma's background-task tools run commands in the panel process, outside
|
||||
// the sandbox. While the sandbox is required, no production session may offer
|
||||
// them to the model.
|
||||
var backgroundTaskTools = []string{"Monitor", "TaskOutput", "TaskStop", "TaskList"}
|
||||
|
||||
// requireSandboxForTest puts the process in ARTEX_SANDBOX=required mode, with
|
||||
// no tool augmentation or catalogue, for the duration of the test.
|
||||
func requireSandboxForTest(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("ARTEX_SANDBOX", sandbox.ModeRequired)
|
||||
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
|
||||
oldEx, oldAug, oldRes := CurrentSandboxExecutor(), ToolAugment(), ToolResolve()
|
||||
t.Cleanup(func() {
|
||||
SetSandboxExecutor(oldEx)
|
||||
SetToolAugment(oldAug)
|
||||
SetToolResolve(oldRes)
|
||||
})
|
||||
SetSandboxExecutor(&SandboxExecutor{Mode: sandbox.ModeRequired})
|
||||
SetToolAugment(nil)
|
||||
SetToolResolve(nil)
|
||||
if !SandboxRequired() {
|
||||
t.Fatal("sandbox is not in required mode")
|
||||
}
|
||||
}
|
||||
|
||||
// requireSandboxOffForTest puts the process in ARTEX_SANDBOX=off mode, with no
|
||||
// tool augmentation or catalogue, for the duration of the test.
|
||||
func requireSandboxOffForTest(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("ARTEX_SANDBOX", sandbox.ModeOff)
|
||||
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
|
||||
oldEx, oldAug, oldRes := CurrentSandboxExecutor(), ToolAugment(), ToolResolve()
|
||||
t.Cleanup(func() {
|
||||
SetSandboxExecutor(oldEx)
|
||||
SetToolAugment(oldAug)
|
||||
SetToolResolve(oldRes)
|
||||
})
|
||||
SetSandboxExecutor(nil)
|
||||
SetToolAugment(nil)
|
||||
SetToolResolve(nil)
|
||||
if SandboxRequired() {
|
||||
t.Fatal("sandbox is still required")
|
||||
}
|
||||
}
|
||||
|
||||
// offeredTools returns the tool names of the first model request, failing the
|
||||
// test when the session never called the model.
|
||||
func offeredTools(t *testing.T, p *captureToolNamesProvider) map[string]bool {
|
||||
t.Helper()
|
||||
p.mu.Lock()
|
||||
called := p.names != nil
|
||||
p.mu.Unlock()
|
||||
if !called {
|
||||
t.Fatal("the session never sent a model request")
|
||||
}
|
||||
return p.seen()
|
||||
}
|
||||
|
||||
func assertNoBackgroundTaskTools(t *testing.T, p *captureToolNamesProvider) {
|
||||
t.Helper()
|
||||
got := offeredTools(t, p)
|
||||
for _, name := range backgroundTaskTools {
|
||||
if got[name] {
|
||||
t.Errorf("model was offered %s (offered: %v)", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductionSessionsOfferNoBackgroundTaskTools(t *testing.T) {
|
||||
requireSandboxForTest(t)
|
||||
workDir := t.TempDir()
|
||||
|
||||
t.Run("chat execution agent", func(t *testing.T) {
|
||||
prov := &captureToolNamesProvider{}
|
||||
c := NewChatAgent(prov, "test-model", workDir, nil, 100000)
|
||||
if _, err := c.Chat(t.Context(), "pentest", "conv-bgtools-pentest", "hello", 1, 0, false, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
})
|
||||
|
||||
// Auto's base list is nil. Norma reads a nil list as "install my own
|
||||
// unconfined file and shell tools", so none of those may appear either.
|
||||
t.Run("chat orchestration agent", func(t *testing.T) {
|
||||
// With finding-traffic binding on, the finding workflow keeps Auto's list
|
||||
// nil (with it off, it copies the list into a new empty slice), so this is
|
||||
// the setting under which a nil list reaches the session.
|
||||
oldBinding := FindingTrafficBindingEnabled()
|
||||
t.Cleanup(func() { SetFindingTrafficBindingEnabled(oldBinding) })
|
||||
SetFindingTrafficBindingEnabled(func() bool { return true })
|
||||
prov := &captureToolNamesProvider{}
|
||||
c := NewChatAgent(prov, "test-model", workDir, nil, 100000)
|
||||
if _, err := c.Chat(t.Context(), "auto", "conv-bgtools-auto", "hello", 1, 0, false, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
got := prov.seen()
|
||||
for _, name := range []string{"Bash", "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep"} {
|
||||
if got[name] {
|
||||
t.Errorf("auto was offered Norma's default tool %s", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("goal decomposition", func(t *testing.T) {
|
||||
prov := &captureToolNamesProvider{}
|
||||
// The fixture answers in plain text, so the decomposer reports a contract
|
||||
// error. Only the offered tools matter here.
|
||||
_, _ = DecomposeGoals(t.Context(), prov, t.TempDir(), "Audit auth on lab.local", "", nil, guardTaskStore(t), 0, nil)
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
})
|
||||
|
||||
t.Run("planner", func(t *testing.T) {
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
task, err := d.CreateTaskWithOptions("", "", db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
|
||||
ts := d.Exploration(task.ExplorationID)
|
||||
if _, err := ts.AddNode(db.KindGoal, map[string]any{"text": "Audit /admin"}, 0, "open", "goals", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ts.AddIntent(map[string]any{"summary": "Audit the fixture admin endpoint"}, 0, nil, "fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prov := &captureToolNamesProvider{}
|
||||
p := NewPlanner(prov, "test-model", workDir, nil, 0, 2)
|
||||
_, _, _ = p.Plan(t.Context(), task.ID, nil, ts, "", nil, nil, nil)
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
})
|
||||
|
||||
t.Run("main agent", func(t *testing.T) {
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
expID, err := d.CreateExploration("bgtools main agent", "no background-task tools")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
|
||||
prov := &captureToolNamesProvider{}
|
||||
m := NewMainAgent(prov, "test-model", workDir, nil, 0, 1)
|
||||
if _, err := m.Chat(t.Context(), expID, 0, nil, d.Exploration(expID), "verify goal", "status?", nil, nil, nil, nil, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
})
|
||||
|
||||
t.Run("worker", func(t *testing.T) {
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
expID, err := d.CreateExploration("bgtools worker", "no background-task tools")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
|
||||
es := d.Exploration(expID)
|
||||
payload := map[string]any{"summary": "probe"}
|
||||
intentID, err := es.AddNode("intent", payload, 0, "running", "planner", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := json.Marshal(payload)
|
||||
prov := &captureToolNamesProvider{}
|
||||
w := NewWorker(prov, "test-model", workDir, nil, 0, 1)
|
||||
if _, _, err := w.Execute(t.Context(), "work#1", expID, nil, es, &db.Node{ID: intentID, Payload: raw}, nil, nil, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
})
|
||||
|
||||
// captureRun is the constructor the planner uses. Check it on its own too,
|
||||
// with a nil tool list: Norma reads nil as "install my own unconfined file
|
||||
// and shell tools", so the model must be offered no tools at all.
|
||||
t.Run("captureRun", func(t *testing.T) {
|
||||
prov := &captureToolNamesProvider{}
|
||||
if _, _, err := captureRun(t.Context(), agentcore.Options{Provider: prov, MaxTurns: 1}, "hello", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := offeredTools(t, prov); len(got) != 0 {
|
||||
t.Fatalf("nil tool list offered %v, want no tools", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Without the sandbox, a session that has no Bash must still not gain a shell
|
||||
// through Norma's background-task tools. The planner is excluded because it
|
||||
// does have Bash, and then the task manager is needed for pause and background
|
||||
// runs.
|
||||
func TestSessionsWithoutBashOfferNoBackgroundTaskTools(t *testing.T) {
|
||||
requireSandboxOffForTest(t)
|
||||
workDir := t.TempDir()
|
||||
|
||||
t.Run("chat orchestration agent", func(t *testing.T) {
|
||||
// With finding-traffic binding on, the finding workflow keeps Auto's list
|
||||
// nil (with it off, it copies the list into a new empty slice), so this is
|
||||
// the setting under which a nil list reaches the session.
|
||||
oldBinding := FindingTrafficBindingEnabled()
|
||||
t.Cleanup(func() { SetFindingTrafficBindingEnabled(oldBinding) })
|
||||
SetFindingTrafficBindingEnabled(func() bool { return true })
|
||||
prov := &captureToolNamesProvider{}
|
||||
c := NewChatAgent(prov, "test-model", workDir, nil, 100000)
|
||||
if _, err := c.Chat(t.Context(), "auto", "conv-bgtools-auto-off", "hello", 1, 0, false, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
got := prov.seen()
|
||||
for _, name := range []string{"Bash", "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep"} {
|
||||
if got[name] {
|
||||
t.Errorf("auto was offered Norma's default tool %s", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("main agent", func(t *testing.T) {
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
expID, err := d.CreateExploration("bgtools main agent off", "no background-task tools")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) })
|
||||
prov := &captureToolNamesProvider{}
|
||||
m := NewMainAgent(prov, "test-model", workDir, nil, 0, 1)
|
||||
if _, err := m.Chat(t.Context(), expID, 0, nil, d.Exploration(expID), "verify goal", "status?", nil, nil, nil, nil, nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoBackgroundTaskTools(t, prov)
|
||||
})
|
||||
}
|
||||
|
||||
func TestHasShellTool(t *testing.T) {
|
||||
if hasShellTool(nil) {
|
||||
t.Fatal("nil tool list reported a shell tool")
|
||||
}
|
||||
if hasShellTool([]actool.CoreTool{dummyTool("Read"), dummyTool("Grep")}) {
|
||||
t.Fatal("a session without a shell tool reported one")
|
||||
}
|
||||
if !hasShellTool([]actool.CoreTool{dummyTool("Read"), dummyTool("Bash")}) {
|
||||
t.Fatal("a session with Bash was not detected")
|
||||
}
|
||||
if !hasShellTool(append([]actool.CoreTool{dummyTool("Read")}, actool.ShellSessionTools()...)) {
|
||||
t.Fatal("a session with the interactive shell was not detected")
|
||||
}
|
||||
}
|
||||
|
||||
// With the sandbox off, an agent whose interactive shell is on keeps the task
|
||||
// manager its PTY sessions live on, even when Bash is not bound to it.
|
||||
func TestInteractiveShellWithoutBashKeepsTaskManager(t *testing.T) {
|
||||
requireSandboxOffForTest(t)
|
||||
prov := &captureToolNamesProvider{}
|
||||
s := newSession(agentcore.Options{Provider: prov, Tools: actool.ShellSessionTools(), NonStreaming: true, WorkingDir: t.TempDir()})
|
||||
defer s.Close()
|
||||
for _, err := range s.Prompt(t.Context(), "hello") {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := offeredTools(t, prov); !got["TaskList"] {
|
||||
t.Fatalf("a session with shell_open has no task manager (offered: %v)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNoDirectNormaSessions keeps every session behind newSession: a direct
|
||||
// agentcore.NewSession call would bring the background-task tools back. It covers
|
||||
// the server and command packages too, and keeps agentcore.Run to the connection
|
||||
// test, which sets the flag itself.
|
||||
func TestNoDirectNormaSessions(t *testing.T) {
|
||||
for _, root := range []string{".", "../server", "../cmd"} {
|
||||
err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
if filepath.Base(path) == "session.go" && filepath.Clean(filepath.Dir(path)) == "." {
|
||||
return nil
|
||||
}
|
||||
src, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
text := string(src)
|
||||
if strings.Contains(text, "agentcore.NewSession(") {
|
||||
t.Errorf("%s calls agentcore.NewSession directly; use newSession", path)
|
||||
}
|
||||
if strings.Contains(text, "agentcore.Run(") && path != "provider.go" {
|
||||
t.Errorf("%s calls agentcore.Run directly; only the connection test may", path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -778,7 +778,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
|
||||
noaSession := WorkerSessionID(ts.ID(), intent.ID)
|
||||
enableNoa(&opts, w.noaEnabledFn, w.workDir, noaSession, noaWarn(noaSession))
|
||||
ctx = attachSideCapture(ctx, &opts)
|
||||
s := agentcore.NewSession(opts)
|
||||
s := newSession(opts)
|
||||
defer s.Close() // release the session's background-task manager (temp dir + processes)
|
||||
|
||||
// Resume prior conversation if this intent was paused/blocked/exhausted and is
|
||||
|
||||
+112
-49
@@ -170,10 +170,11 @@ func askOperatorActivity(text string, att []chatAttachment, derived []string) db
|
||||
return a
|
||||
}
|
||||
|
||||
// resolveAskOperatorImage maps image_path onto a regular file inside runDir, the
|
||||
// run directory of the agent that asks (its CWD). Relative paths are resolved from it.
|
||||
// ".." segments, paths that EvalSymlinks outside runDir, and non-images are refused.
|
||||
func resolveAskOperatorImage(runDir, src string) (string, error) {
|
||||
// askOperatorImageRel maps image_path onto a path relative to the task root.
|
||||
// Relative paths resolve from runName, the run directory of the agent that asks
|
||||
// (i<intentID>, or main). An absolute path must be inside that run directory.
|
||||
// ".." segments, paths outside the run directory and non-images are refused.
|
||||
func askOperatorImageRel(taskDir, runName, src string) (string, error) {
|
||||
src = strings.TrimSpace(src)
|
||||
ext := strings.ToLower(filepath.Ext(src))
|
||||
if !askOperatorImageExt[ext] {
|
||||
@@ -182,34 +183,54 @@ func resolveAskOperatorImage(runDir, src string) (string, error) {
|
||||
if slices.Contains(strings.Split(filepath.ToSlash(src), "/"), "..") {
|
||||
return "", fmt.Errorf("image_path must stay inside the run directory")
|
||||
}
|
||||
if !filepath.IsAbs(src) {
|
||||
src = filepath.Join(runDir, src)
|
||||
var rel string
|
||||
if filepath.IsAbs(src) {
|
||||
r, err := filepath.Rel(taskDir, filepath.Clean(src))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("image_path must stay inside the run directory")
|
||||
}
|
||||
rel = r
|
||||
} else {
|
||||
rel = filepath.Join(runName, src)
|
||||
}
|
||||
realRoot, err := filepath.EvalSymlinks(runDir)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("image not readable")
|
||||
}
|
||||
real, err := filepath.EvalSymlinks(src)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("image not readable")
|
||||
}
|
||||
rel, err := filepath.Rel(realRoot, real)
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
if !filepath.IsLocal(rel) || (rel != runName && !strings.HasPrefix(rel, runName+string(filepath.Separator))) {
|
||||
return "", fmt.Errorf("image_path must stay inside the run directory")
|
||||
}
|
||||
return real, nil
|
||||
return rel, nil
|
||||
}
|
||||
|
||||
// openAskOperatorImage opens the image at path and requires the opened file to be
|
||||
// the regular file lst describes, lst being the Lstat of path. Between the
|
||||
// EvalSymlinks of resolveAskOperatorImage and this open, the agent can replace the
|
||||
// file with a symlink: Lstat does not follow one and the open does, so the two then
|
||||
// name different files and the image is refused.
|
||||
func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
|
||||
// askOperatorRejectSymlinks refuses a symlink in any component of rel below the
|
||||
// task root. os.Root follows links that stay inside the root, so a link from the
|
||||
// run directory to a sibling would otherwise be read.
|
||||
func askOperatorRejectSymlinks(root *os.Root, rel string) error {
|
||||
parts := strings.Split(rel, string(filepath.Separator))
|
||||
prefix := parts[0]
|
||||
for i, part := range parts {
|
||||
if i > 0 {
|
||||
prefix = filepath.Join(prefix, part)
|
||||
}
|
||||
info, err := root.Lstat(prefix)
|
||||
if err != nil {
|
||||
return fmt.Errorf("image not readable")
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("image_path must stay inside the run directory")
|
||||
}
|
||||
if i < len(parts)-1 && !info.IsDir() {
|
||||
return fmt.Errorf("image not readable")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// openAskOperatorImage opens rel under the task root and requires the opened file
|
||||
// to be the regular file lst describes. The root refuses a path outside the task
|
||||
// and a symlink that leaves it; Lstat does not follow the last component.
|
||||
func openAskOperatorImage(root *os.Root, rel string, lst os.FileInfo) (*os.File, error) {
|
||||
if !lst.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("image_path must be a regular file")
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
f, err := root.Open(rel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("image not readable")
|
||||
}
|
||||
@@ -220,18 +241,22 @@ func openAskOperatorImage(path string, lst os.FileInfo) (*os.File, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// askOperatorUploadsDir returns tasks/<id>/uploads, created when absent. A symlink
|
||||
// or anything else that is not a directory is refused: the copy would be written
|
||||
// through it.
|
||||
func askOperatorUploadsDir(taskDir string) (string, error) {
|
||||
dir := filepath.Join(taskDir, "uploads")
|
||||
if err := os.Mkdir(dir, 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
|
||||
return "", err
|
||||
// askOperatorUploadsRoot returns tasks/<id>/uploads as a root anchored at the
|
||||
// task directory. A symlink or anything else that is not a directory is refused:
|
||||
// the copy would be written through it.
|
||||
func askOperatorUploadsRoot(taskRoot *os.Root) (*os.Root, error) {
|
||||
if err := taskRoot.Mkdir("uploads", 0o755); err != nil && !errors.Is(err, fs.ErrExist) {
|
||||
return nil, err
|
||||
}
|
||||
if fi, err := os.Lstat(dir); err != nil || !fi.IsDir() {
|
||||
return "", fmt.Errorf("the task uploads directory is not a directory")
|
||||
fi, err := taskRoot.Lstat("uploads")
|
||||
if err != nil || fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() {
|
||||
return nil, fmt.Errorf("the task uploads directory is not a directory")
|
||||
}
|
||||
return dir, nil
|
||||
uploads, err := taskRoot.OpenRoot("uploads")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the task uploads directory is not a directory")
|
||||
}
|
||||
return uploads, nil
|
||||
}
|
||||
|
||||
// askOperatorStageTries bounds the names tried for one staged copy.
|
||||
@@ -257,33 +282,57 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
|
||||
if src == "" {
|
||||
return nil, nil
|
||||
}
|
||||
taskDir := filepath.Join(dataDir, "tasks", strconv.FormatInt(taskID, 10))
|
||||
resolved, err := resolveAskOperatorImage(agent.EnsureRunDir(dataDir, taskID, intentID), src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
taskRel := filepath.Join("tasks", strconv.FormatInt(taskID, 10))
|
||||
runName := "main"
|
||||
if intentID > 0 {
|
||||
runName = "i" + strconv.FormatInt(intentID, 10)
|
||||
}
|
||||
st, err := os.Lstat(resolved)
|
||||
// Every lookup is anchored at the task directory: a run directory or an
|
||||
// intermediate directory swapped for a symlink cannot leave the task.
|
||||
dataRoot, err := os.OpenRoot(dataDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("image not readable")
|
||||
}
|
||||
in, err := openAskOperatorImage(resolved, st)
|
||||
defer dataRoot.Close()
|
||||
taskRoot, err := dataRoot.OpenRoot(taskRel)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("image not readable")
|
||||
}
|
||||
defer taskRoot.Close()
|
||||
runInfo, err := taskRoot.Lstat(runName)
|
||||
if err != nil || runInfo.Mode()&os.ModeSymlink != 0 || !runInfo.IsDir() {
|
||||
return nil, fmt.Errorf("image_path must stay inside the run directory")
|
||||
}
|
||||
rel, err := askOperatorImageRel(filepath.Join(dataDir, taskRel), runName, src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := askOperatorRejectSymlinks(taskRoot, rel); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st, err := taskRoot.Lstat(rel)
|
||||
if err != nil || !st.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("image not readable")
|
||||
}
|
||||
if st.Size() > askOperatorMaxImage {
|
||||
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
|
||||
}
|
||||
in, err := openAskOperatorImage(taskRoot, rel, st)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer in.Close()
|
||||
if st.Size() > askOperatorMaxImage {
|
||||
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(st.Size()))
|
||||
}
|
||||
dir, err := askOperatorUploadsDir(taskDir)
|
||||
uploads, err := askOperatorUploadsRoot(taskRoot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(resolved))
|
||||
defer uploads.Close()
|
||||
ext := strings.ToLower(filepath.Ext(rel))
|
||||
var name string
|
||||
var out *os.File
|
||||
for try := 1; ; try++ {
|
||||
name = askOperatorStageName(ext)
|
||||
out, err = os.OpenFile(filepath.Join(dir, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
|
||||
out, err = uploads.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
@@ -291,9 +340,23 @@ func stageAskOperatorImage(dataDir string, taskID, intentID int64, src string) (
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
defer out.Close()
|
||||
if _, err := io.Copy(out, in); err != nil {
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
_ = out.Close()
|
||||
_ = uploads.Remove(name)
|
||||
}
|
||||
}()
|
||||
n, err := io.Copy(out, io.LimitReader(in, askOperatorMaxImage+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: st.Size()}}, nil
|
||||
if n > askOperatorMaxImage {
|
||||
return nil, fmt.Errorf("image too large (%s, max 10MB)", humanBytes(n))
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
committed = true
|
||||
return []chatAttachment{{Name: name, Path: "uploads/" + name, Size: n}}, nil
|
||||
}
|
||||
|
||||
@@ -282,16 +282,22 @@ func TestStageAskOperatorImageNeverOverwrites(t *testing.T) {
|
||||
// elsewhere.
|
||||
func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
|
||||
dir, taskDir := askOperatorRunDirs(t)
|
||||
root, err := os.OpenRoot(taskDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = root.Close() })
|
||||
src := filepath.Join(taskDir, "i3", "shot.png")
|
||||
rel := filepath.Join("i3", "shot.png")
|
||||
outside := filepath.Join(dir, "outside.png")
|
||||
if err := os.WriteFile(outside, []byte("outside"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lst, err := os.Lstat(src)
|
||||
lst, err := root.Lstat(rel)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := openAskOperatorImage(src, lst)
|
||||
f, err := openAskOperatorImage(root, rel, lst)
|
||||
if err != nil {
|
||||
t.Fatalf("unchanged file: %v", err)
|
||||
}
|
||||
@@ -305,32 +311,95 @@ func TestOpenAskOperatorImageRefusesSwap(t *testing.T) {
|
||||
if err := os.Rename(other, src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f, err := openAskOperatorImage(src, lst); err == nil {
|
||||
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
|
||||
f.Close()
|
||||
t.Fatal("opened a file that replaced the checked one")
|
||||
}
|
||||
|
||||
// A symlink to a file outside the run directory takes the path.
|
||||
// A symlink to a file outside the run directory takes the path. os.Root
|
||||
// refuses the absolute target because it leaves the task root.
|
||||
if err := os.Remove(src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, src); err != nil {
|
||||
t.Skipf("no symlink here: %v", err)
|
||||
}
|
||||
if f, err := openAskOperatorImage(src, lst); err == nil {
|
||||
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
|
||||
f.Close()
|
||||
t.Fatal("opened the target of a symlink that replaced the checked file")
|
||||
}
|
||||
// The swap came before the Lstat: the last component is a symlink.
|
||||
if lst, err = os.Lstat(src); err != nil {
|
||||
if lst, err = root.Lstat(rel); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f, err := openAskOperatorImage(src, lst); err == nil {
|
||||
if f, err := openAskOperatorImage(root, rel, lst); err == nil {
|
||||
f.Close()
|
||||
t.Fatal("opened a path whose last component is a symlink")
|
||||
}
|
||||
}
|
||||
|
||||
// A run directory replaced by a symlink must not turn the task root into the
|
||||
// confinement root: the read stays anchored at tasks/<id>.
|
||||
func TestStageAskOperatorImageRejectsRunDirSymlink(t *testing.T) {
|
||||
dir, taskDir := askOperatorRunDirs(t)
|
||||
runDir := filepath.Join(taskDir, "i3")
|
||||
moved := filepath.Join(taskDir, "i3.real")
|
||||
if err := os.Rename(runDir, moved); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = os.Remove(runDir)
|
||||
_ = os.Rename(moved, runDir)
|
||||
})
|
||||
if err := os.Symlink("/", runDir); err != nil {
|
||||
t.Skipf("no symlink here: %v", err)
|
||||
}
|
||||
// taskDir/shot.png is outside the run directory but inside the task. With the
|
||||
// run directory symlinked to /, the old confinement root resolved to / and
|
||||
// accepted it; the task root must not move.
|
||||
outsideRun := filepath.Join(taskDir, "shot.png")
|
||||
if err := os.WriteFile(outsideRun, []byte("outside the run dir"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if att, err := stageAskOperatorImage(dir, 7, 3, outsideRun); err == nil {
|
||||
t.Fatalf("staged %v through a symlinked run directory", att)
|
||||
}
|
||||
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
|
||||
t.Fatalf("staged %v through a symlinked run directory", att)
|
||||
}
|
||||
}
|
||||
|
||||
// A symlink inside the run directory must not lead to a sibling run directory.
|
||||
func TestStageAskOperatorImageRejectsSiblingSymlink(t *testing.T) {
|
||||
dir, taskDir := askOperatorRunDirs(t)
|
||||
link := filepath.Join(taskDir, "i3", "sibling")
|
||||
if err := os.Symlink(filepath.Join("..", "main"), link); err != nil {
|
||||
t.Skipf("no symlink here: %v", err)
|
||||
}
|
||||
if att, err := stageAskOperatorImage(dir, 7, 3, filepath.Join("sibling", "shot.png")); err == nil {
|
||||
t.Fatalf("staged %v through a sibling symlink", att)
|
||||
}
|
||||
}
|
||||
|
||||
// uploads/ swapped for a symlink must not redirect the copy outside the task.
|
||||
func TestStageAskOperatorImageRejectsUploadsSymlink(t *testing.T) {
|
||||
dir, taskDir := askOperatorRunDirs(t)
|
||||
outside := t.TempDir()
|
||||
if err := os.Symlink(outside, filepath.Join(taskDir, "uploads")); err != nil {
|
||||
t.Skipf("no symlink here: %v", err)
|
||||
}
|
||||
if att, err := stageAskOperatorImage(dir, 7, 3, "shot.png"); err == nil {
|
||||
t.Fatalf("staged %v through a symlinked uploads directory", att)
|
||||
}
|
||||
entries, err := os.ReadDir(outside)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("wrote %d file(s) outside the task", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
// The emitted activity must carry the {text, attachments} Detail shape the
|
||||
// transcript parser expects, so the operator sees the question with the
|
||||
// attachment card for the screenshot.
|
||||
|
||||
@@ -307,6 +307,11 @@ func wireTools(pg *db.DB, domainReg map[string]actool.CoreTool) {
|
||||
rows, err := pg.ListTools()
|
||||
if err != nil {
|
||||
log.Printf("[tools] failed to read tools table, passing through with code defaults: %v", err)
|
||||
// Auto's base list is nil, and Norma reads nil as "use its own
|
||||
// unconfined default tools". Keep it an empty list.
|
||||
if tools == nil {
|
||||
return []actool.CoreTool{}
|
||||
}
|
||||
return tools
|
||||
}
|
||||
byKey := make(map[string]*db.Tool, len(rows))
|
||||
|
||||
@@ -28,6 +28,11 @@ const (
|
||||
maxArchiveBytes = int64(1 << 47) // 128 TiB safety ceiling for corrupt headers.
|
||||
)
|
||||
|
||||
// taskArchiveBeforeOpenHook is an optional test hook invoked with the payload-relative
|
||||
// name of each regular file immediately before writeTaskArchivePackage opens it,
|
||||
// allowing deterministic TOCTOU regression tests (always nil in production).
|
||||
var taskArchiveBeforeOpenHook func(name string)
|
||||
|
||||
type archiveFileMove struct {
|
||||
Source string `json:"source"`
|
||||
Relative string `json:"relative"`
|
||||
@@ -700,15 +705,24 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
|
||||
if err != nil {
|
||||
return 0, 0, "", err
|
||||
}
|
||||
// Code running as the executor uid can keep a working directory inside the moved run
|
||||
// directory and swap a directory for a symlink after it was listed. Walk and open
|
||||
// through a root anchored at the payload so no lookup can leave it, and check that
|
||||
// each opened file is the one the walk saw.
|
||||
root, err := os.OpenRoot(payloadDir)
|
||||
if err != nil {
|
||||
return 0, 0, "", err
|
||||
}
|
||||
defer root.Close()
|
||||
tarWriter := tar.NewWriter(encoder)
|
||||
walkErr := filepath.WalkDir(payloadDir, func(current string, entry fs.DirEntry, walkErr error) error {
|
||||
walkErr := walkTaskArchiveRoot(root, ".", func(relative string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
relative, err := filepath.Rel(payloadDir, current)
|
||||
if err != nil || relative == "." {
|
||||
return err
|
||||
if relative == "." {
|
||||
return nil
|
||||
}
|
||||
current := filepath.Join(payloadDir, filepath.FromSlash(relative))
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -730,7 +744,7 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
header.Name = filepath.ToSlash(relative)
|
||||
header.Name = relative
|
||||
if err := tarWriter.WriteHeader(header); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -738,10 +752,21 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
|
||||
return nil
|
||||
}
|
||||
originalSize += info.Size()
|
||||
input, err := os.Open(current)
|
||||
if taskArchiveBeforeOpenHook != nil {
|
||||
taskArchiveBeforeOpenHook(relative)
|
||||
}
|
||||
input, err := root.Open(filepath.FromSlash(relative))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opened, err := input.Stat()
|
||||
if err == nil && (!opened.Mode().IsRegular() || !os.SameFile(info, opened)) {
|
||||
err = fmt.Errorf("task archive entry %s changed while it was packed", relative)
|
||||
}
|
||||
if err != nil {
|
||||
_ = input.Close()
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(tarWriter, input)
|
||||
closeErr := input.Close()
|
||||
return errors.Join(copyErr, closeErr)
|
||||
@@ -780,6 +805,39 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
|
||||
return originalSize, compressedSize, checksum, nil
|
||||
}
|
||||
|
||||
// walkTaskArchiveRoot walks dir inside root like fs.WalkDir, in lexical order, with
|
||||
// slash-separated names. It does not go through root.FS(), which refuses names that
|
||||
// are not valid UTF-8, so a run tree holding such a file can still be archived as
|
||||
// before. Entries come from ReadDir on a handle opened in root, so their FileInfo is
|
||||
// read relative to that handle, never through a path that could leave the root.
|
||||
func walkTaskArchiveRoot(root *os.Root, dir string, fn fs.WalkDirFunc) error {
|
||||
handle, err := root.Open(filepath.FromSlash(dir))
|
||||
if err != nil {
|
||||
return fn(dir, nil, err)
|
||||
}
|
||||
entries, err := handle.ReadDir(-1)
|
||||
_ = handle.Close()
|
||||
if err != nil {
|
||||
return fn(dir, nil, err)
|
||||
}
|
||||
slices.SortFunc(entries, func(a, b fs.DirEntry) int { return strings.Compare(a.Name(), b.Name()) })
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if dir != "." {
|
||||
name = dir + "/" + name
|
||||
}
|
||||
if err := fn(name, entry, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() {
|
||||
if err := walkTaskArchiveRoot(root, name, fn); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func extractTaskArchivePackage(path, expectedSHA, destination string) error {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
//go:build unix
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
pgdb "github.com/Autumn-27/artex/db"
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
const archiveOutsideSecret = "root-only secret outside the payload"
|
||||
|
||||
// sameSizeAsSecret returns a filler as long as archiveOutsideSecret, so a tar header
|
||||
// taken from the listed file still matches the bytes read through a swapped path.
|
||||
func sameSizeAsSecret(fill string) string {
|
||||
return strings.Repeat(fill, len(archiveOutsideSecret))
|
||||
}
|
||||
|
||||
// archiveSymlinkFixture builds a payload with main/zzz/{a_big,jwt.key} and, next to
|
||||
// the payload, an outside directory holding jwt.key with archiveOutsideSecret.
|
||||
func archiveSymlinkFixture(t *testing.T) (payload, outside string) {
|
||||
t.Helper()
|
||||
base := t.TempDir()
|
||||
payload = filepath.Join(base, "payload")
|
||||
outside = filepath.Join(base, "keys")
|
||||
for path, body := range map[string]string{
|
||||
filepath.Join(payload, "main", "zzz", "a_big"): "earlier sibling",
|
||||
filepath.Join(payload, "main", "zzz", "jwt.key"): sameSizeAsSecret("d"),
|
||||
filepath.Join(outside, "jwt.key"): archiveOutsideSecret,
|
||||
} {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return payload, outside
|
||||
}
|
||||
|
||||
// swapBeforeOpen runs swap once, right before the packer opens the file named at.
|
||||
func swapBeforeOpen(t *testing.T, at string, swap func() error) {
|
||||
t.Helper()
|
||||
taskArchiveBeforeOpenHook = func(name string) {
|
||||
if name != at {
|
||||
return
|
||||
}
|
||||
taskArchiveBeforeOpenHook = nil
|
||||
if err := swap(); err != nil {
|
||||
t.Errorf("swap: %v", err)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { taskArchiveBeforeOpenHook = nil })
|
||||
}
|
||||
|
||||
// readArchiveEntries returns the regular file contents of a task archive by name.
|
||||
func readArchiveEntries(t *testing.T, path string) map[string]string {
|
||||
t.Helper()
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
decoder, err := zstd.NewReader(file)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer decoder.Close()
|
||||
entries := map[string]string{}
|
||||
tr := tar.NewReader(decoder)
|
||||
for {
|
||||
header, err := tr.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return entries
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := io.ReadAll(tr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries[header.Name] = string(body)
|
||||
}
|
||||
}
|
||||
|
||||
// packSwapped writes the archive and fails the test if the outside secret, or the
|
||||
// content of a file other than the one the walk listed, reached it.
|
||||
func packSwapped(t *testing.T, payload string, unexpected string) {
|
||||
t.Helper()
|
||||
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
|
||||
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
|
||||
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
|
||||
if err != nil {
|
||||
t.Logf("refused: %v", err)
|
||||
return
|
||||
}
|
||||
for name, body := range readArchiveEntries(t, archivePath) {
|
||||
if strings.Contains(body, unexpected) {
|
||||
t.Fatalf("archive entry %s holds %q, read through a swapped path", name, body)
|
||||
}
|
||||
}
|
||||
t.Fatal("the archive was written although a path changed under the packer")
|
||||
}
|
||||
|
||||
// A directory swapped for a symlink to an outside directory after it was listed and
|
||||
// an earlier child packed: its later children must not be read through the link.
|
||||
func TestTaskArchivePackageDirSwappedForOutsideSymlink(t *testing.T) {
|
||||
payload, outside := archiveSymlinkFixture(t)
|
||||
dir := filepath.Join(payload, "main", "zzz")
|
||||
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
|
||||
if err := os.Rename(dir, dir+".original"); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Symlink(outside, dir)
|
||||
})
|
||||
packSwapped(t, payload, archiveOutsideSecret)
|
||||
}
|
||||
|
||||
// A regular file swapped for a symlink to an outside file after it was listed.
|
||||
func TestTaskArchivePackageFileSwappedForOutsideSymlink(t *testing.T) {
|
||||
payload, outside := archiveSymlinkFixture(t)
|
||||
target := filepath.Join(payload, "main", "zzz", "jwt.key")
|
||||
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
|
||||
if err := os.Remove(target); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Symlink(filepath.Join(outside, "jwt.key"), target)
|
||||
})
|
||||
packSwapped(t, payload, archiveOutsideSecret)
|
||||
}
|
||||
|
||||
// A directory swapped for a relative symlink climbing out with ../ segments.
|
||||
func TestTaskArchivePackageDirSwappedForDotDotSymlink(t *testing.T) {
|
||||
payload, _ := archiveSymlinkFixture(t)
|
||||
dir := filepath.Join(payload, "main", "zzz")
|
||||
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
|
||||
if err := os.Rename(dir, dir+".original"); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Symlink("../../keys", dir)
|
||||
})
|
||||
packSwapped(t, payload, archiveOutsideSecret)
|
||||
}
|
||||
|
||||
// A directory swapped for a symlink after its parent was listed but before the walk
|
||||
// descends into it (outside and ../ targets): listing its children must not leave the
|
||||
// payload either. The same-file check cannot catch this case, because the children
|
||||
// would be listed and opened through the same link.
|
||||
func TestTaskArchivePackageDirSwappedBeforeDescent(t *testing.T) {
|
||||
for name, link := range map[string]string{"outside": "", "dotdot": "../../keys"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
payload, outside := archiveSymlinkFixture(t)
|
||||
if err := os.WriteFile(filepath.Join(payload, "main", "a_first"), []byte("earlier file"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target := link
|
||||
if target == "" {
|
||||
target = outside
|
||||
}
|
||||
dir := filepath.Join(payload, "main", "zzz")
|
||||
swapBeforeOpen(t, "main/a_first", func() error {
|
||||
if err := os.Rename(dir, dir+".original"); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Symlink(target, dir)
|
||||
})
|
||||
packSwapped(t, payload, archiveOutsideSecret)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A directory swapped for a symlink that stays inside the payload: the file opened
|
||||
// is not the one the walk listed, so it is refused rather than packed under the
|
||||
// listed name.
|
||||
func TestTaskArchivePackageDirSwappedForInsideSymlink(t *testing.T) {
|
||||
payload, _ := archiveSymlinkFixture(t)
|
||||
other := filepath.Join(payload, "main", "other")
|
||||
if err := os.MkdirAll(other, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(other, "jwt.key"), []byte(sameSizeAsSecret("o")), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := filepath.Join(payload, "main", "zzz")
|
||||
swapBeforeOpen(t, "main/zzz/jwt.key", func() error {
|
||||
if err := os.Rename(dir, dir+".original"); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Symlink("other", dir)
|
||||
})
|
||||
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
|
||||
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
|
||||
_, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot)
|
||||
if err == nil {
|
||||
got := readArchiveEntries(t, archivePath)["main/zzz/jwt.key"]
|
||||
t.Fatalf("archive written with main/zzz/jwt.key = %q after the directory was swapped", got)
|
||||
}
|
||||
t.Logf("refused: %v", err)
|
||||
}
|
||||
|
||||
// Symlinks already present to an outside file and an outside directory are skipped:
|
||||
// neither the file nor the directory's children are packed.
|
||||
func TestTaskArchivePackageSkipsOutsideSymlinks(t *testing.T) {
|
||||
payload, outside := archiveSymlinkFixture(t)
|
||||
if err := os.Symlink(filepath.Join(outside, "jwt.key"), filepath.Join(payload, "main", "key-link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(payload, "main", "keys-link")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
|
||||
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
|
||||
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
|
||||
t.Fatalf("archive should skip symlinks, not fail: %v", err)
|
||||
}
|
||||
entries := readArchiveEntries(t, archivePath)
|
||||
for name, body := range entries {
|
||||
if strings.Contains(body, archiveOutsideSecret) || strings.HasPrefix(name, "main/key") {
|
||||
t.Fatalf("outside symlink packed as %s = %q", name, body)
|
||||
}
|
||||
}
|
||||
if entries["main/zzz/jwt.key"] != sameSizeAsSecret("d") {
|
||||
t.Fatalf("regular file not packed: %q", entries["main/zzz/jwt.key"])
|
||||
}
|
||||
}
|
||||
|
||||
// File and directory names that are not valid UTF-8 are packed as before: a run tree
|
||||
// may hold them (tool output, extracted target data), and refusing them would make
|
||||
// the task impossible to archive.
|
||||
func TestTaskArchivePackageKeepsNonUTF8Names(t *testing.T) {
|
||||
payload, _ := archiveSymlinkFixture(t)
|
||||
dir := filepath.Join(payload, "main", "\xfe-dir")
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range []string{filepath.Join(payload, "main", "\xff\xfe.txt"), filepath.Join(dir, "inner.txt")} {
|
||||
if err := os.WriteFile(path, []byte("body"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
archivePath := filepath.Join(filepath.Dir(payload), "archive.tar.zst")
|
||||
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42}
|
||||
if _, _, _, err := writeTaskArchivePackage(archivePath, payload, snapshot); err != nil {
|
||||
t.Fatalf("archive with non-UTF-8 names failed: %v", err)
|
||||
}
|
||||
entries := readArchiveEntries(t, archivePath)
|
||||
for _, name := range []string{"main/\xff\xfe.txt", "main/\xfe-dir/inner.txt"} {
|
||||
if entries[name] != "body" {
|
||||
t.Fatalf("entry %q = %q, want body", name, entries[name])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restoring never creates a link or writes outside the destination: a symlink or hard
|
||||
// link entry followed by a regular entry written through it, and nested ../ names.
|
||||
func TestTaskArchiveExtractRefusesLinksAndNestedTraversal(t *testing.T) {
|
||||
type entry struct {
|
||||
header tar.Header
|
||||
body string
|
||||
}
|
||||
reg := func(name string) entry {
|
||||
return entry{tar.Header{Name: name, Mode: 0o600, Size: 5, Typeflag: tar.TypeReg}, "pwned"}
|
||||
}
|
||||
cases := map[string][]entry{
|
||||
"symlink then write through it": {
|
||||
{header: tar.Header{Name: "link", Linkname: "OUTSIDE", Typeflag: tar.TypeSymlink, Mode: 0o777}},
|
||||
reg("link/pwned"),
|
||||
},
|
||||
"hard link then write through it": {
|
||||
{header: tar.Header{Name: "link", Linkname: "OUTSIDE/pwned", Typeflag: tar.TypeLink, Mode: 0o600}},
|
||||
reg("link"),
|
||||
},
|
||||
"nested dotdot": {reg("a/../../pwned")},
|
||||
"deep nested dotdot": {reg("a/b/../../../pwned")},
|
||||
"dotdot after directory": {{header: tar.Header{Name: "a/", Typeflag: tar.TypeDir, Mode: 0o700}}, reg("a/../../pwned")},
|
||||
}
|
||||
for name, entries := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
outside := filepath.Join(base, "outside")
|
||||
if err := os.MkdirAll(outside, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var compressed bytes.Buffer
|
||||
encoder, err := zstd.NewWriter(&compressed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tw := tar.NewWriter(encoder)
|
||||
for _, e := range entries {
|
||||
header := e.header
|
||||
header.Linkname = strings.ReplaceAll(header.Linkname, "OUTSIDE", outside)
|
||||
if err := tw.WriteHeader(&header); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e.body != "" {
|
||||
if _, err := tw.Write([]byte(e.body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := encoder.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(base, "malicious.tar.zst")
|
||||
if err := os.WriteFile(path, compressed.Bytes(), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
destination := filepath.Join(base, "restore", "dest")
|
||||
if err := extractTaskArchivePackage(path, "", destination); err == nil {
|
||||
t.Fatal("unsafe archive was accepted")
|
||||
}
|
||||
for _, escaped := range []string{
|
||||
filepath.Join(outside, "pwned"),
|
||||
filepath.Join(base, "restore", "pwned"),
|
||||
filepath.Join(base, "pwned"),
|
||||
} {
|
||||
if _, err := os.Lstat(escaped); !os.IsNotExist(err) {
|
||||
t.Fatalf("extraction wrote %s: %v", escaped, err)
|
||||
}
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(destination, "link")); !os.IsNotExist(err) {
|
||||
t.Fatalf("extraction created a link entry: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// When the tools table cannot be read, Auto's nil base list must come back as
|
||||
// an empty list: Norma reads nil as "install my own unconfined default tools".
|
||||
func TestToolResolveCatalogFailureReturnsEmptyList(t *testing.T) {
|
||||
sqlDB, err := sql.Open("pgx", "postgres://127.0.0.1:1/unused?sslmode=disable")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = sqlDB.Close() // every query now fails without touching the network
|
||||
oldBinding, oldCapture := agent.FindingTrafficBindingEnabled(), agent.TrafficCaptureEnabled()
|
||||
t.Cleanup(func() {
|
||||
agent.SetToolResolve(nil)
|
||||
agent.SetFindingTrafficBindingEnabled(oldBinding)
|
||||
agent.SetTrafficCaptureEnabled(oldCapture)
|
||||
})
|
||||
wireTools(&db.DB{DB: sqlDB}, nil)
|
||||
|
||||
got := agent.ToolResolve()(context.Background(), "auto", nil)
|
||||
if got == nil || len(got) != 0 {
|
||||
t.Fatalf("catalogue failure returned %#v, want an empty non-nil list", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user