diff --git a/Dockerfile b/Dockerfile index 7bb5d96..183f8cb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -189,6 +189,10 @@ RUN npm install -g "@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}" "@playwright/cli@ && playwright install --with-deps chromium \ && "$(npm root -g)/@playwright/mcp/node_modules/.bin/playwright-core" install chromium \ && rm -rf /var/lib/apt/lists/* +# Agent processes run as the executor with HOME and XDG_CACHE_HOME in the data +# directory (server/execpriv_unix.go); the browsers installed above stay in root's +# cache, which /root's 0711 lets the executor reach. +ENV PLAYWRIGHT_BROWSERS_PATH=/root/.cache/ms-playwright WORKDIR /app # Binary compiled from source in the build stage above. COPY --from=build /out/artex /app/artex @@ -198,6 +202,10 @@ COPY --from=build /out/artex /app/artex COPY start.sh /app/start.sh RUN chmod +x /app/artex /app/start.sh && mkdir -p -m 0700 /app/keys \ && chmod 0711 /root +# No setuid or setgid programs (su, passwd, mount, bbot's chrome_sandbox, ...): an +# agent process runs as the executor and must not regain root through one, even +# when the container runs without docker-compose.yml's no-new-privileges. +RUN find / -xdev -perm /6000 -type f -exec chmod a-s {} + COPY skills/ /app/skills/ # persistence points: data/ (traffic index, task files, transcripts) and keys/ (jwt.key, secret.key, via ARTEX_JWT_KEY_DIR) VOLUME ["/app/data", "/app/keys"] diff --git a/SECURITY.md b/SECURITY.md index a8e2934..34f0289 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -51,7 +51,7 @@ Operators running self-hosted LLM gateways or Ollama on a LAN or Docker bridge c ## Agent Process Isolation -The server runs as root, but the processes an agent starts (Bash, the interactive shell, custom tools and stdio MCP servers) run as the unprivileged uid and gid set by `-exec-uid` and `-exec-gid` (default 10001). Only the task workspace tree, shared with that group, is writable by them; `keys/` (`jwt.key`, `secret.key`) and the config file are root-only, and the server's environment block no longer carries `ARTEX_PG_DSN`, `ARTEX_SECRET_KEY` or the LLM API keys (Linux). These are a containment layer, not a sandbox: an executor can still read world-readable files under the data directory, reach the loopback API and the database if the network allows it, and use any credential it was given through the platform. Persistence tools (custom tools, MCP servers, skills) need operator approval by default. +The server runs as root, but the processes an agent starts (Bash, the interactive shell, custom tools and stdio MCP servers) run as the unprivileged uid and gid set by `-exec-uid` and `-exec-gid` (default 10001). Only the task workspace tree, shared with that group, and their own home (`/exec-home`) are writable by them; `keys/` (`jwt.key`, `secret.key`), the config file and the MITM CA key are root-only, and the server's environment block no longer carries `ARTEX_PG_DSN`, `ARTEX_SECRET_KEY`, the LLM API keys or the LLM proxy and base URLs (Linux). The agent's file tools (Read, Write, Edit, MultiEdit, LS, Glob, Grep) run inside the server but reach only the run's working directory: paths are opened through `os.Root`, so absolute paths elsewhere, `..` and symlinks leading out are refused. The Docker image has no setuid programs and `docker-compose.yml` sets `no-new-privileges`. These are a containment layer, not a sandbox: an executor can still read world-readable files under the data directory, reach the loopback API and the database if the network allows it, and use any credential it was given through the platform. Persistence tools (custom tools, MCP servers, skills) need operator approval by default. ## What to Expect diff --git a/agent/chat.go b/agent/chat.go index 803daa8..2feca34 100644 --- a/agent/chat.go +++ b/agent/chat.go @@ -159,7 +159,7 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin // Pure assistant: DefaultTools as the base; AugmentTools layers in the key's // visible skills/MCP and lets the DB tools table filter/override. DefaultTools // have no tools-table rows, so they always pass through. - base := actool.DefaultTools() + base := defaultTools(c.workDir) // file tools confined to sessionWorkDir (filetools.go) ctx = WithRunInfo(ctx, RunInfo{SessionID: sessionID}) tools, def, cleanup := AugmentTools(ctx, agentKey, base) defer cleanup() diff --git a/agent/filetools.go b/agent/filetools.go new file mode 100644 index 0000000..e112196 --- /dev/null +++ b/agent/filetools.go @@ -0,0 +1,854 @@ +package agent + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strings" + + actool "github.com/Autumn-27/norma/tool" +) + +// Confined file tools. The SDK's Read/Write/Edit/MultiEdit/LS/Glob/Grep run inside +// the server process, which is root in the Docker image, and accept any absolute or +// relative path: they would read /app/keys or the config file, and write a skill or +// the config, while the agent's shell runs as the unprivileged executor. These +// replacements keep the SDK tools' names, descriptions and input schemas (the model +// sees no change) and open every path through an os.Root on the run's working +// directory. os.Root resolves each path component inside the root at the syscall +// level, so an absolute path outside, "..", or a symlink leading out of the working +// directory is refused, including a symlink the agent's shell swaps in while a call +// runs. Grep does not start ripgrep: that would read the files with root's rights by +// path. + +// confinedFileToolNames are the SDK default tools replaced by defaultTools. +var confinedFileToolNames = map[string]func(*workRoot, json.RawMessage, *actool.ToolContext) (actool.Result, error){ + "Read": runConfinedRead, + "Write": runConfinedWrite, + "Edit": runConfinedEdit, + "MultiEdit": runConfinedMultiEdit, + "LS": runConfinedLS, + "Glob": runConfinedGlob, + "Grep": runConfinedGrep, +} + +// defaultTools is actool.DefaultTools() with the file tools confined to the run's +// working directory under base (the data directory the agent's run directories +// live in). Every agent kind builds its tool set from it. +func defaultTools(base string) []actool.CoreTool { + all := actool.DefaultTools() + out := make([]actool.CoreTool, 0, len(all)) + for _, t := range all { + if run, ok := confinedFileToolNames[t.Name()]; ok { + t = &confinedFileTool{CoreTool: t, base: base, run: run} + } + out = append(out, t) + } + return out +} + +// confinedFileTool keeps the SDK tool's metadata and permission self-check and +// replaces only Call. +type confinedFileTool struct { + actool.CoreTool + base string + run func(*workRoot, json.RawMessage, *actool.ToolContext) (actool.Result, error) +} + +func (t *confinedFileTool) Call(_ context.Context, in json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + dir := "" + if tc != nil { + dir = tc.WorkingDir + } + w, err := openWorkRoot(t.base, dir) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error: %s cannot run: %v", t.Name(), err)), nil + } + defer w.Close() + return t.run(w, in, tc) +} + +// workRoot is the run's working directory opened as an os.Root. dir is the path the +// model knows it by: absolute paths inside it are accepted and outputs use it. +type workRoot struct { + *os.Root + dir string +} + +var ( + errOutsideWorkDir = errors.New("outside the working directory") + errNotRegular = errors.New("not a regular file") + errHardLinked = errors.New("the file has other hard links, which can lead outside the working directory") +) + +// openWorkRoot opens dir, which must lie strictly below base. base is set by the +// server and resolved as is; below it every component is opened inside its parent +// (os.Root.OpenRoot), so a run directory the agent's shell replaced with a symlink +// cannot move the root out of the parent workspace tree (to / or to the data +// directory, for instance). Fails closed on any error. +func openWorkRoot(base, dir string) (*workRoot, error) { + if strings.TrimSpace(dir) == "" { + return nil, errors.New("no working directory for this run") + } + absDir, err := filepath.Abs(dir) + if err != nil { + return nil, err + } + absBase, err := filepath.Abs(base) + if err != nil { + return nil, err + } + rel, err := filepath.Rel(absBase, absDir) + if err != nil || rel == "." || !filepath.IsLocal(rel) { + return nil, errors.New("the working directory is not inside the data directory") + } + realBase, err := filepath.EvalSymlinks(absBase) + if err != nil { + return nil, fmt.Errorf("data directory: %w", err) + } + r, err := os.OpenRoot(realBase) + if err != nil { + return nil, fmt.Errorf("data directory: %w", err) + } + for _, c := range strings.Split(rel, string(filepath.Separator)) { + next, err := r.OpenRoot(c) + r.Close() + if err != nil { + return nil, fmt.Errorf("open the working directory: %w", err) + } + r = next + } + return &workRoot{Root: r, dir: absDir}, nil +} + +// rel maps a model-supplied path to a path relative to the root. Empty means the +// working directory itself. An absolute path must lie inside the working directory; +// ".." leading out of it is refused here, and os.Root refuses any symlink that does. +func (w *workRoot) rel(p string) (string, error) { + if strings.ContainsRune(p, 0) { + return "", errOutsideWorkDir + } + if p == "" { + return ".", nil + } + if filepath.IsAbs(p) { + r, err := filepath.Rel(w.dir, filepath.Clean(p)) + if err != nil { + return "", errOutsideWorkDir + } + p = r + } + p = filepath.Clean(p) + if !filepath.IsLocal(p) { + return "", errOutsideWorkDir + } + return p, nil +} + +// refuse answers a path outside the working directory. +func (w *workRoot) refuse(p string) actool.Result { + return actool.Errorf(fmt.Sprintf("Error: %s is outside the working directory %s. File tools only reach paths inside it (a symlink that leads out of it is refused too). To read a file elsewhere that your shell may access, use Bash.", p, w.dir)) +} + +// readFile reads a regular file inside the root. A file with more than one hard +// link is refused: a link made in the working directory to a file outside it would +// otherwise be read with the server's rights. +func (w *workRoot) readFile(rel string) ([]byte, error) { + if fi, err := w.Stat(rel); err != nil { + return nil, err + } else if !fi.Mode().IsRegular() { + return nil, errNotRegular + } + f, err := w.Open(rel) + if err != nil { + return nil, err + } + defer f.Close() + if err := checkOpened(f); err != nil { + return nil, err + } + return io.ReadAll(f) +} + +// writeFile replaces the contents of rel, creating it when missing. The checks run +// on the opened file before it is truncated. +func (w *workRoot) writeFile(rel string, data []byte) error { + if fi, err := w.Stat(rel); err == nil && !fi.Mode().IsRegular() { + return errNotRegular + } + // 0664: the executor group shares the workspace tree (server/execpriv.go). + f, err := w.OpenFile(rel, os.O_WRONLY|os.O_CREATE, 0o664) + if err != nil { + return err + } + if err := checkOpened(f); err != nil { + f.Close() + return err + } + if err := f.Truncate(0); err != nil { + f.Close() + return err + } + if _, err := f.Write(data); err != nil { + f.Close() + return err + } + return f.Close() +} + +func checkOpened(f *os.File) error { + fi, err := f.Stat() + switch { + case err != nil: + return err + case !fi.Mode().IsRegular(): + return errNotRegular + case extraHardLinks(fi): + return errHardLinked + } + return nil +} + +// ---------- Read ---------- + +const confinedMaxLineLen = 2000 + +// confinedReadOutputBonus mirrors the SDK Read tool's extra output budget. +const confinedReadOutputBonus = 1000 + +func runConfinedRead(w *workRoot, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + var in struct { + FilePath string `json:"file_path"` + Offset int `json:"offset"` + Limit int `json:"limit"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Result{}, err + } + rel, err := w.rel(in.FilePath) + if err != nil { + return w.refuse(in.FilePath), nil + } + info, err := w.Stat(rel) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil + } + if info.IsDir() { + return actool.Errorf(fmt.Sprintf("Error: %s is a directory, not a file. Use LS or Glob to list its contents.", in.FilePath)), nil + } + data, err := w.readFile(rel) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil + } + if isBinaryData(data) { + return actool.Text(fmt.Sprintf("[binary file %s not shown — %d bytes]", in.FilePath, len(data))), nil + } + lines := strings.Split(string(data), "\n") + start := 0 + if in.Offset > 0 { + start = in.Offset - 1 + } + if start > len(lines) { + start = len(lines) + } + limit := in.Limit + if limit <= 0 { + limit = 2000 + } + end := min(start+limit, len(lines)) + var b strings.Builder + for i := start; i < end; i++ { + line := lines[i] + if len(line) > confinedMaxLineLen { + line = line[:confinedMaxLineLen] + "… [line truncated]" + } + fmt.Fprintf(&b, "%6d\t%s\n", i+1, line) + } + if b.Len() == 0 { + if len(data) == 0 { + return actool.Text("(file is empty)"), nil + } + return actool.Text("(no lines in the requested range)"), nil + } + return actool.Text(confinedReadCapture(tc, b.String(), start)), nil +} + +// confinedReadCapture bounds Read's output like the SDK tool: it cuts at a line +// boundary and tells the model the offset to continue from. +func confinedReadCapture(tc *actool.ToolContext, s string, start int) string { + limit := actool.MaxOutput(tc) + confinedReadOutputBonus + if len(s) <= limit { + return s + } + head := s[:limit] + if cut := strings.LastIndexByte(head, '\n'); cut >= 0 { + head = s[:cut+1] + } + next := start + strings.Count(head, "\n") + 1 + return head + fmt.Sprintf( + "\n... [Read truncated to fit the output limit. Continue reading the file with Read offset=%d (and an optional limit), or narrow with Grep/`sed -n`.] ...", next) +} + +// isBinaryData reports a NUL byte in the first chunk, the SDK's heuristic. +func isBinaryData(data []byte) bool { + return bytes.IndexByte(data[:min(len(data), 8000)], 0) >= 0 +} + +// ---------- Write / Edit / MultiEdit ---------- + +func runConfinedWrite(w *workRoot, input json.RawMessage, _ *actool.ToolContext) (actool.Result, error) { + var in struct { + FilePath string `json:"file_path"` + Content string `json:"content"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Result{}, err + } + rel, err := w.rel(in.FilePath) + if err != nil { + return w.refuse(in.FilePath), nil + } + existed := false + if info, err := w.Stat(rel); err == nil { + if info.IsDir() { + return actool.Errorf(fmt.Sprintf("Error: %s is an existing directory, not a file.", in.FilePath)), nil + } + existed = true + } + if dir := filepath.Dir(rel); dir != "." { + // 0775: the executor group shares the workspace tree (server/execpriv.go). + if err := w.MkdirAll(dir, 0o775); err != nil { + return actool.Errorf(fmt.Sprintf("Error creating directory: %v", err)), nil + } + } + if err := w.writeFile(rel, []byte(in.Content)); err != nil { + return actool.Errorf(fmt.Sprintf("Error writing %s: %v", in.FilePath, err)), nil + } + verb := "Created" + if existed { + verb = "Overwrote" + } + return actool.Text(fmt.Sprintf("%s %s (%d bytes)", verb, in.FilePath, len(in.Content))), nil +} + +func runConfinedEdit(w *workRoot, input json.RawMessage, _ *actool.ToolContext) (actool.Result, error) { + var in struct { + FilePath string `json:"file_path"` + OldString string `json:"old_string"` + NewString string `json:"new_string"` + ReplaceAll bool `json:"replace_all"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Result{}, err + } + if in.OldString == in.NewString { + return actool.Errorf("Error: old_string and new_string are identical"), nil + } + rel, err := w.rel(in.FilePath) + if err != nil { + return w.refuse(in.FilePath), nil + } + data, err := w.readFile(rel) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil + } + content := string(data) + count := strings.Count(content, in.OldString) + if count == 0 { + return actool.Errorf(fmt.Sprintf("Error: old_string not found in %s", in.FilePath)), nil + } + if count > 1 && !in.ReplaceAll { + return actool.Errorf(fmt.Sprintf("Error: old_string is not unique in %s (%d matches); add context or set replace_all", in.FilePath, count)), nil + } + var updated string + if in.ReplaceAll { + updated = strings.ReplaceAll(content, in.OldString, in.NewString) + } else { + updated = strings.Replace(content, in.OldString, in.NewString, 1) + } + if err := w.writeFile(rel, []byte(updated)); err != nil { + return actool.Errorf(fmt.Sprintf("Error writing %s: %v", in.FilePath, err)), nil + } + return actool.Text(fmt.Sprintf("Edited %s (%d replacement(s))", in.FilePath, count)), nil +} + +func runConfinedMultiEdit(w *workRoot, input json.RawMessage, _ *actool.ToolContext) (actool.Result, error) { + var in struct { + FilePath string `json:"file_path"` + Edits []struct { + OldString string `json:"old_string"` + NewString string `json:"new_string"` + ReplaceAll bool `json:"replace_all"` + } `json:"edits"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Result{}, err + } + if len(in.Edits) == 0 { + return actool.Errorf("Error: no edits provided"), nil + } + rel, err := w.rel(in.FilePath) + if err != nil { + return w.refuse(in.FilePath), nil + } + data, err := w.readFile(rel) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error reading %s: %v", in.FilePath, err)), nil + } + content := string(data) + total := 0 + for i, e := range in.Edits { + if e.OldString == e.NewString { + return actool.Errorf(fmt.Sprintf("Error in edit %d: old_string and new_string are identical", i+1)), nil + } + count := strings.Count(content, e.OldString) + if count == 0 { + return actool.Errorf(fmt.Sprintf("Error in edit %d: old_string not found", i+1)), nil + } + if count > 1 && !e.ReplaceAll { + return actool.Errorf(fmt.Sprintf("Error in edit %d: old_string is not unique (%d matches); add context or set replace_all", i+1, count)), nil + } + if e.ReplaceAll { + content = strings.ReplaceAll(content, e.OldString, e.NewString) + } else { + content = strings.Replace(content, e.OldString, e.NewString, 1) + } + total += count + } + if err := w.writeFile(rel, []byte(content)); err != nil { + return actool.Errorf(fmt.Sprintf("Error writing %s: %v", in.FilePath, err)), nil + } + return actool.Text(fmt.Sprintf("Applied %d edits to %s (%d replacement(s))", len(in.Edits), in.FilePath, total)), nil +} + +// ---------- LS ---------- + +func runConfinedLS(w *workRoot, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + var in struct { + Path string `json:"path"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Result{}, err + } + rel, err := w.rel(in.Path) + if err != nil { + return w.refuse(in.Path), nil + } + // Stat first: opening a FIFO to list it would block. + if info, err := w.Stat(rel); err == nil && !info.IsDir() { + return actool.Errorf(fmt.Sprintf("Error listing %s: not a directory", in.Path)), nil + } + entries, err := fs.ReadDir(w.FS(), filepath.ToSlash(rel)) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error listing %s: %v", in.Path, err)), nil + } + if len(entries) == 0 { + return actool.Text("(empty directory)"), nil + } + sort.Slice(entries, func(i, j int) bool { + if entries[i].IsDir() != entries[j].IsDir() { + return entries[i].IsDir() // directories first + } + return entries[i].Name() < entries[j].Name() + }) + var b strings.Builder + for _, e := range entries { + if e.IsDir() { + fmt.Fprintf(&b, "%s/\n", e.Name()) + continue + } + var size int64 + if info, err := w.Lstat(filepath.Join(rel, e.Name())); err == nil { + size = info.Size() + } + fmt.Fprintf(&b, "%s\t%d bytes\n", e.Name(), size) + } + return actool.Text(actool.Capture(tc, b.String())), nil +} + +// ---------- Glob ---------- + +var confinedSkipDirs = map[string]bool{".git": true, "node_modules": true, "vendor": true} + +// relUnder returns p relative to the walk base (both slash paths from fs.WalkDir). +func relUnder(base, p string) string { + if base == "." { + return p + } + if p == base { + return "." + } + return strings.TrimPrefix(p, base+"/") +} + +func runConfinedGlob(w *workRoot, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + var in struct { + Pattern string `json:"pattern"` + Path string `json:"path"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Result{}, err + } + rel, err := w.rel(in.Path) + if err != nil { + return w.refuse(in.Path), nil + } + base := filepath.ToSlash(rel) + type match struct { + path string + mod int64 + } + var matches []match + _ = fs.WalkDir(w.FS(), base, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + if confinedSkipDirs[d.Name()] { + return fs.SkipDir + } + return nil + } + if globMatch(in.Pattern, relUnder(base, p)) { + var mod int64 + if info, e := w.Lstat(filepath.FromSlash(p)); e == nil { + mod = info.ModTime().UnixNano() + } + matches = append(matches, match{filepath.Join(w.dir, filepath.FromSlash(p)), mod}) + } + return nil + }) + sort.Slice(matches, func(i, j int) bool { return matches[i].mod > matches[j].mod }) + if len(matches) == 0 { + return actool.Text("No files found"), nil + } + var b strings.Builder + for _, m := range matches { + b.WriteString(m.path) + b.WriteByte('\n') + } + return actool.Text(actool.Capture(tc, b.String())), nil +} + +// globMatch is the SDK Glob matcher: a pattern without "/" matches the base name, +// "**" matches any number of segments. +func globMatch(pattern, p string) bool { + pattern = filepath.ToSlash(pattern) + p = filepath.ToSlash(p) + if !strings.Contains(pattern, "/") { + if ok, _ := path.Match(pattern, path.Base(p)); ok { + return true + } + } + return globSegs(strings.Split(pattern, "/"), strings.Split(p, "/")) +} + +func globSegs(pat, name []string) bool { + if len(pat) == 0 { + return len(name) == 0 + } + if pat[0] == "**" { + for i := 0; i <= len(name); i++ { + if globSegs(pat[1:], name[i:]) { + return true + } + } + return false + } + if len(name) == 0 { + return false + } + if ok, _ := path.Match(pat[0], name[0]); !ok { + return false + } + return globSegs(pat[1:], name[1:]) +} + +// ---------- Grep ---------- + +func runConfinedGrep(w *workRoot, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) { + var in struct { + Pattern string `json:"pattern"` + Path string `json:"path"` + Glob string `json:"glob"` + Type string `json:"type"` + OutputMode string `json:"output_mode"` + IgnoreCase bool `json:"-i"` + LineNums *bool `json:"-n"` + After int `json:"-A"` + Before int `json:"-B"` + Context int `json:"-C"` + Multiline bool `json:"multiline"` + HeadLimit *int `json:"head_limit"` + Offset int `json:"offset"` + } + if err := json.Unmarshal(input, &in); err != nil { + return actool.Result{}, err + } + before, after := in.Before, in.After + if in.Context > 0 { + before, after = in.Context, in.Context + } + flags := "" + if in.IgnoreCase { + flags += "i" + } + if in.Multiline { + flags += "s" + } + pat := in.Pattern + if flags != "" { + pat = "(?" + flags + ")" + pat + } + re, err := regexp.Compile(pat) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error: invalid regex: %v", err)), nil + } + rel, err := w.rel(in.Path) + if err != nil { + return w.refuse(in.Path), nil + } + mode := in.OutputMode + if mode == "" { + mode = "files_with_matches" + } + showLines := true + if in.LineNums != nil { + showLines = *in.LineNums + } + typeGlobs := grepTypeGlobs(in.Type) + var results []grepFileHit + scan := func(p, shown string) { + data, err := w.readFile(filepath.FromSlash(p)) + if err != nil || isBinaryData(data) { + return + } + if h := grepScan(data, filepath.FromSlash(shown), re, mode, showLines, in.Multiline, before, after); h != nil { + results = append(results, *h) + } + } + base := filepath.ToSlash(rel) + info, err := w.Stat(rel) + if err != nil { + return actool.Errorf(fmt.Sprintf("Error: %v", err)), nil + } + if info.IsDir() { + _ = fs.WalkDir(w.FS(), base, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil + } + if d.IsDir() { + if confinedSkipDirs[d.Name()] { + return fs.SkipDir + } + return nil + } + name := path.Base(p) + if in.Glob != "" { + if ok, _ := path.Match(in.Glob, name); !ok { + return nil + } + } + if len(typeGlobs) > 0 && !grepMatchAny(typeGlobs, name) { + return nil + } + scan(p, relUnder(base, p)) + return nil + }) + } else { + scan(base, path.Base(base)) + } + if len(results) == 0 { + return actool.Text("No matches found"), nil + } + sort.Slice(results, func(i, j int) bool { return results[i].path < results[j].path }) + + var lines []string + switch mode { + case "content": + for _, r := range results { + lines = append(lines, r.lines...) + } + case "count": + for _, r := range results { + lines = append(lines, fmt.Sprintf("%s: %d", r.path, r.count)) + } + default: // files_with_matches + for _, r := range results { + lines = append(lines, r.path) + } + } + headLimit := 250 + if in.HeadLimit != nil { + headLimit = *in.HeadLimit + } + kept, more := grepPage(lines, headLimit, in.Offset) + out := strings.Join(kept, "\n") + if len(kept) > 0 { + out += "\n" + } + if more > 0 { + out += fmt.Sprintf("... [%d more result(s) — page with offset=%d, or head_limit=0 for all] ...\n", more, in.Offset+len(kept)) + } + return actool.Text(actool.Capture(tc, out)), nil +} + +// grepFileTypes maps a ripgrep-style file type to its globs (the SDK's subset). +var grepFileTypes = map[string][]string{ + "go": {"*.go"}, + "py": {"*.py", "*.pyi"}, + "python": {"*.py", "*.pyi"}, + "js": {"*.js", "*.jsx", "*.mjs", "*.cjs", "*.vue"}, + "ts": {"*.ts", "*.tsx", "*.mts", "*.cts"}, + "rust": {"*.rs"}, + "java": {"*.java"}, + "kotlin": {"*.kt", "*.kts"}, + "c": {"*.c", "*.h"}, + "cpp": {"*.cpp", "*.cc", "*.cxx", "*.hpp", "*.hh", "*.hxx", "*.h"}, + "cs": {"*.cs"}, + "rb": {"*.rb"}, + "ruby": {"*.rb"}, + "php": {"*.php"}, + "swift": {"*.swift"}, + "sh": {"*.sh", "*.bash", "*.zsh"}, + "html": {"*.html", "*.htm"}, + "css": {"*.css", "*.scss", "*.sass", "*.less"}, + "json": {"*.json"}, + "yaml": {"*.yaml", "*.yml"}, + "toml": {"*.toml"}, + "xml": {"*.xml"}, + "md": {"*.md", "*.markdown"}, + "markdown": {"*.md", "*.markdown"}, + "sql": {"*.sql"}, + "proto": {"*.proto"}, +} + +// grepTypeGlobs resolves a type name to its globs; an unknown type is treated as a +// bare extension (type:foo → *.foo). Empty type → nil. +func grepTypeGlobs(t string) []string { + if t == "" { + return nil + } + if g, ok := grepFileTypes[strings.ToLower(t)]; ok { + return g + } + return []string{"*." + t} +} + +func grepMatchAny(globs []string, name string) bool { + for _, g := range globs { + if ok, _ := path.Match(g, name); ok { + return true + } + } + return false +} + +// grepPage skips the first offset entries then keeps at most limit (0 = unlimited). +func grepPage(lines []string, limit, offset int) (kept []string, more int) { + if offset > 0 { + if offset >= len(lines) { + return nil, 0 + } + lines = lines[offset:] + } + if limit > 0 && len(lines) > limit { + return lines[:limit], len(lines) - limit + } + return lines, 0 +} + +type grepFileHit struct { + path string + lines []string + count int +} + +// grepScan is the SDK Grep's per-file scan over data already read; shown is the +// path printed for the file. +func grepScan(data []byte, shown string, re *regexp.Regexp, mode string, showLines, multiline bool, before, after int) *grepFileHit { + lines := strings.Split(string(data), "\n") + if n := len(lines); n > 0 && lines[n-1] == "" { + lines = lines[:n-1] // drop the empty element from a trailing newline + } + var matches []int + if multiline { + lineStart := make([]int, len(lines)) + off := 0 + for i, ln := range lines { + lineStart[i] = off + off += len(ln) + 1 + } + hit := make([]bool, len(lines)) + for _, loc := range re.FindAllIndex(data, -1) { + s, e := loc[0], loc[1] + for i := range lines { + ls, le := lineStart[i], lineStart[i]+len(lines[i]) + if s <= le && e > ls { + hit[i] = true + } + } + } + for i, h := range hit { + if h { + matches = append(matches, i) + } + } + } else { + for i, ln := range lines { + if re.MatchString(ln) { + matches = append(matches, i) + } + } + } + if len(matches) == 0 { + return nil + } + res := &grepFileHit{path: shown, count: len(matches)} + if mode != "content" { + return res + } + isMatch := make(map[int]bool, len(matches)) + for _, m := range matches { + isMatch[m] = true + } + var order []int + seen := map[int]bool{} + for _, m := range matches { + lo, hi := max(m-before, 0), min(m+after, len(lines)-1) + for j := lo; j <= hi; j++ { + if !seen[j] { + seen[j] = true + order = append(order, j) + } + } + } + sort.Ints(order) + hasContext := before > 0 || after > 0 + prev := -2 + for _, j := range order { + if hasContext && prev >= 0 && j != prev+1 { + res.lines = append(res.lines, "--") + } + sep := "-" + if isMatch[j] { + sep = ":" + } + if showLines { + res.lines = append(res.lines, fmt.Sprintf("%s%s%d%s%s", shown, sep, j+1, sep, lines[j])) + } else { + res.lines = append(res.lines, fmt.Sprintf("%s%s%s", shown, sep, lines[j])) + } + prev = j + } + return res +} diff --git a/agent/filetools_other.go b/agent/filetools_other.go new file mode 100644 index 0000000..0fd5461 --- /dev/null +++ b/agent/filetools_other.go @@ -0,0 +1,9 @@ +//go:build !unix + +package agent + +import "io/fs" + +// extraHardLinks: the link count is not available here; the executor identity that +// could plant a link only exists on unix (server/execpriv_unix.go). +func extraHardLinks(fs.FileInfo) bool { return false } diff --git a/agent/filetools_test.go b/agent/filetools_test.go new file mode 100644 index 0000000..65146f9 --- /dev/null +++ b/agent/filetools_test.go @@ -0,0 +1,312 @@ +package agent + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + + actool "github.com/Autumn-27/norma/tool" +) + +const confinedSecret = "TOPSECRET-confined-tools" + +type confinedFixture struct { + base, work, secret string + tools map[string]actool.CoreTool + tc *actool.ToolContext +} + +// newConfinedFixture lays out a data directory like the server's: the run's +// working directory under sessions/, and a key file outside it, plus symlinks in +// the working directory that lead to the key (absolute, relative, through a dir). +func newConfinedFixture(t *testing.T) *confinedFixture { + t.Helper() + base := t.TempDir() + work := filepath.Join(base, "sessions", "s1") + keys := filepath.Join(base, "keys") + for _, d := range []string{work, keys} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + secret := filepath.Join(keys, "jwt.key") + if err := os.WriteFile(secret, []byte(confinedSecret+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(work, "in.txt"), []byte("hello\nworld\n"), 0o644); err != nil { + t.Fatal(err) + } + links := map[string]string{ + "lnabs": secret, + "lnrel": filepath.Join("..", "..", "keys", "jwt.key"), + "lndir": filepath.Join("..", "..", "keys"), + "lnin": "in.txt", + } + for name, target := range links { + if err := os.Symlink(target, filepath.Join(work, name)); err != nil { + if runtime.GOOS == "windows" { + t.Skipf("symlinks unavailable: %v", err) + } + t.Fatal(err) + } + } + tools := map[string]actool.CoreTool{} + for _, tl := range defaultTools(base) { + tools[tl.Name()] = tl + } + return &confinedFixture{base: base, work: work, secret: secret, tools: tools, tc: &actool.ToolContext{WorkingDir: work}} +} + +func (f *confinedFixture) call(t *testing.T, tool string, in map[string]any) actool.Result { + t.Helper() + raw, _ := json.Marshal(in) + res, err := f.tools[tool].Call(context.Background(), raw, f.tc) + if err != nil { + t.Fatalf("%s(%s): %v", tool, raw, err) + } + return res +} + +func (f *confinedFixture) secretUnchanged(t *testing.T) { + t.Helper() + b, err := os.ReadFile(f.secret) + if err != nil || string(b) != confinedSecret+"\n" { + t.Fatalf("key file changed: %q %v", b, err) + } + if _, err := os.Stat(filepath.Join(filepath.Dir(f.secret), "new.txt")); err == nil { + t.Fatal("a file was created next to the key") + } +} + +// outsidePaths reach the key file or another file outside the working directory. +func (f *confinedFixture) outsidePaths() []string { + sep := string(filepath.Separator) + return []string{ + f.secret, + filepath.Join("..", "..", "keys", "jwt.key"), + f.work + sep + ".." + sep + ".." + sep + "keys" + sep + "jwt.key", // unclean on purpose + "lnabs", + "lnrel", + filepath.Join("lndir", "jwt.key"), + "/proc/self/environ", + "/etc/passwd", + } +} + +func refused(res actool.Result) bool { return res.IsError } + +// checkRefusals runs every confined tool against every outside path. Nothing may +// succeed, nothing may print the key, and the key must stay unchanged. +func checkRefusals(t *testing.T, f *confinedFixture) { + t.Helper() + for _, p := range f.outsidePaths() { + cases := []struct { + tool string + in map[string]any + }{ + {"Read", map[string]any{"file_path": p}}, + {"Write", map[string]any{"file_path": p, "content": "pwned"}}, + {"Edit", map[string]any{"file_path": p, "old_string": confinedSecret, "new_string": "pwned"}}, + {"MultiEdit", map[string]any{"file_path": p, "edits": []any{map[string]any{"old_string": confinedSecret, "new_string": "pwned"}}}}, + {"LS", map[string]any{"path": filepath.Dir(p)}}, + {"Glob", map[string]any{"pattern": "*", "path": filepath.Dir(p)}}, + {"Grep", map[string]any{"pattern": "TOPSECRET", "path": p, "output_mode": "content"}}, + {"Grep", map[string]any{"pattern": "TOPSECRET", "path": filepath.Dir(p), "output_mode": "content"}}, + } + for _, c := range cases { + res := f.call(t, c.tool, c.in) + out := res.Flatten() + if strings.Contains(out, confinedSecret) { + t.Errorf("%s %v leaked the key: %s", c.tool, c.in, out) + } + // Listing or searching "." (the working directory, the parent of the links) + // is allowed, and Glob skips a symlinked directory without an error; + // everything else must fail. + dir, _ := c.in["path"].(string) + mayPass := dir == "." && (c.tool == "LS" || c.tool == "Glob" || c.tool == "Grep") || + dir == "lndir" && c.tool == "Glob" + if !refused(res) && !mayPass { + t.Errorf("%s %v was not refused: %s", c.tool, c.in, out) + } + } + f.secretUnchanged(t) + } + // Searching the working directory itself must not follow the links out of it. + for _, in := range []map[string]any{ + {"pattern": "TOPSECRET", "output_mode": "content"}, + {"pattern": "TOPSECRET", "path": "lndir", "output_mode": "content"}, + } { + if out := f.call(t, "Grep", in).Flatten(); strings.Contains(out, confinedSecret) { + t.Errorf("Grep %v leaked the key: %s", in, out) + } + } + if res := f.call(t, "LS", map[string]any{"path": "lndir"}); !refused(res) || strings.Contains(res.Flatten(), "jwt.key") { + t.Errorf("LS through a symlinked directory was not refused: %s", res.Flatten()) + } + if res := f.call(t, "Glob", map[string]any{"pattern": "*", "path": "lndir"}); strings.Contains(res.Flatten(), "jwt.key") { + t.Errorf("Glob through a symlinked directory listed the key: %s", res.Flatten()) + } +} + +// The refusal does not depend on privilege: the test user can read the key file +// itself, and the tools still refuse every path that leads to it. +func TestConfinedFileToolsRefuseOutsidePaths(t *testing.T) { + f := newConfinedFixture(t) + if _, err := os.ReadFile(f.secret); err != nil { + t.Fatalf("the process must be able to read the key itself: %v", err) + } + checkRefusals(t, f) +} + +// As root the server can read any file; the tools must still refuse a root-only file +// outside the working directory and the server's own environment. +func TestConfinedFileToolsAsRoot(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() != 0 { + t.Skip("needs root") + } + f := newConfinedFixture(t) + if fi, err := os.Stat(f.secret); err != nil || fi.Mode().Perm() != 0o600 { + t.Fatalf("key file must be 0600: %v %v", fi, err) + } + if _, err := os.ReadFile("/proc/1/environ"); err != nil { + t.Fatalf("root must be able to read /proc/1/environ itself: %v", err) + } + checkRefusals(t, f) + for _, p := range []string{"/proc/1/environ", "/proc/self/root/etc/shadow"} { + if res := f.call(t, "Read", map[string]any{"file_path": p}); !refused(res) { + t.Errorf("Read %s was not refused: %s", p, res.Flatten()) + } + } +} + +func TestConfinedFileToolsWorkInside(t *testing.T) { + f := newConfinedFixture(t) + ok := func(tool string, in map[string]any, want string) { + t.Helper() + res := f.call(t, tool, in) + if res.IsError || !strings.Contains(res.Flatten(), want) { + t.Fatalf("%s %v = %q (error %v), want %q", tool, in, res.Flatten(), res.IsError, want) + } + } + ok("Read", map[string]any{"file_path": "in.txt"}, " 2\tworld") + ok("Read", map[string]any{"file_path": filepath.Join(f.work, "in.txt")}, "hello") + ok("Read", map[string]any{"file_path": "lnin"}, "hello") // a symlink that stays inside + ok("Write", map[string]any{"file_path": "sub/dir/new.txt", "content": "alpha beta\n"}, "Created") + ok("Write", map[string]any{"file_path": filepath.Join(f.work, "sub", "dir", "new.txt"), "content": "alpha beta\n"}, "Overwrote") + ok("Edit", map[string]any{"file_path": "sub/dir/new.txt", "old_string": "alpha", "new_string": "gamma"}, "1 replacement") + ok("MultiEdit", map[string]any{"file_path": "sub/dir/new.txt", "edits": []any{ + map[string]any{"old_string": "gamma", "new_string": "delta"}, + map[string]any{"old_string": "beta", "new_string": "epsilon"}, + }}, "Applied 2 edits") + ok("Read", map[string]any{"file_path": "sub/dir/new.txt"}, "delta epsilon") + ok("LS", map[string]any{}, "in.txt") + ok("LS", map[string]any{"path": "sub"}, "dir/") + ok("Glob", map[string]any{"pattern": "**/*.txt"}, filepath.Join(f.work, "sub", "dir", "new.txt")) + ok("Grep", map[string]any{"pattern": "wor.d", "output_mode": "content"}, "in.txt:2:world") + ok("Grep", map[string]any{"pattern": "epsilon", "path": "sub"}, filepath.Join("dir", "new.txt")) + ok("Grep", map[string]any{"pattern": "hello", "path": "in.txt", "output_mode": "count"}, "in.txt: 1") +} + +// A hard link in the working directory to a file outside it is a second name for +// that file: reading or writing through it is refused. +func TestConfinedFileToolsRefuseHardLinks(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("link counts are unix-only") + } + f := newConfinedFixture(t) + if err := os.Link(f.secret, filepath.Join(f.work, "hl")); err != nil { + t.Skipf("cannot create a hard link here: %v", err) + } + for _, c := range []struct { + tool string + in map[string]any + }{ + {"Read", map[string]any{"file_path": "hl"}}, + {"Write", map[string]any{"file_path": "hl", "content": "pwned"}}, + {"Edit", map[string]any{"file_path": "hl", "old_string": confinedSecret, "new_string": "pwned"}}, + } { + res := f.call(t, c.tool, c.in) + if !res.IsError || strings.Contains(res.Flatten(), confinedSecret) { + t.Errorf("%s through a hard link was not refused: %s", c.tool, res.Flatten()) + } + } + if out := f.call(t, "Grep", map[string]any{"pattern": "TOPSECRET", "output_mode": "content"}).Flatten(); strings.Contains(out, confinedSecret) { + t.Errorf("Grep read the key through a hard link: %s", out) + } + f.secretUnchanged(t) +} + +// The agent's shell can replace its own run directory with a symlink. The root is +// opened component by component, so the swapped directory cannot lead to / or to +// the rest of the data directory. +func TestConfinedFileToolsRunDirSymlinkSwap(t *testing.T) { + for _, target := range []string{"/", filepath.Join("..", "keys"), filepath.Join("..", "..", "keys")} { + f := newConfinedFixture(t) + if err := os.RemoveAll(f.work); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, f.work); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + tool string + in map[string]any + }{ + {"Read", map[string]any{"file_path": "jwt.key"}}, + {"Read", map[string]any{"file_path": "keys/jwt.key"}}, + {"Read", map[string]any{"file_path": "etc/passwd"}}, + {"LS", map[string]any{}}, + {"Write", map[string]any{"file_path": "new.txt", "content": "pwned"}}, + } { + res := f.call(t, c.tool, c.in) + if !res.IsError || strings.Contains(res.Flatten(), confinedSecret) || strings.Contains(res.Flatten(), "jwt.key") { + t.Errorf("run dir -> %s: %s %v was not refused: %s", target, c.tool, c.in, res.Flatten()) + } + } + f.secretUnchanged(t) + } +} + +// Missing or misplaced working directories fail closed. +func TestConfinedFileToolsNeedWorkDirUnderBase(t *testing.T) { + f := newConfinedFixture(t) + for _, dir := range []string{"", f.base, filepath.Dir(f.base)} { + f.tc = &actool.ToolContext{WorkingDir: dir} + if res := f.call(t, "Read", map[string]any{"file_path": f.secret}); !res.IsError { + t.Errorf("working dir %q: Read was not refused: %s", dir, res.Flatten()) + } + } +} + +// The model sees the SDK tools unchanged: same names, descriptions, prompts, schemas +// and read-only flags. +func TestConfinedFileToolsKeepSDKContract(t *testing.T) { + sdk := map[string]actool.CoreTool{} + for _, tl := range actool.DefaultTools() { + sdk[tl.Name()] = tl + } + got := defaultTools(t.TempDir()) + if len(got) != len(sdk) { + t.Fatalf("defaultTools has %d tools, the SDK %d", len(got), len(sdk)) + } + for _, tl := range got { + want := sdk[tl.Name()] + if want == nil { + t.Fatalf("unexpected tool %s", tl.Name()) + } + _, confined := tl.(*confinedFileTool) + if _, replace := confinedFileToolNames[tl.Name()]; replace != confined { + t.Errorf("%s: confined=%v, want %v", tl.Name(), confined, replace) + } + if tl.Description() != want.Description() || tl.Prompt() != want.Prompt() || + !reflect.DeepEqual(tl.InputSchema(), want.InputSchema()) || + tl.IsReadOnly(json.RawMessage(`{}`)) != want.IsReadOnly(json.RawMessage(`{}`)) { + t.Errorf("%s: metadata differs from the SDK tool", tl.Name()) + } + } +} diff --git a/agent/filetools_unix.go b/agent/filetools_unix.go new file mode 100644 index 0000000..eea8886 --- /dev/null +++ b/agent/filetools_unix.go @@ -0,0 +1,14 @@ +//go:build unix + +package agent + +import ( + "io/fs" + "syscall" +) + +// extraHardLinks reports a file that has a name besides the one being opened. +func extraHardLinks(fi fs.FileInfo) bool { + st, ok := fi.Sys().(*syscall.Stat_t) + return ok && st.Nlink > 1 +} diff --git a/agent/mainagent.go b/agent/mainagent.go index 92eb443..adc4858 100644 --- a/agent/mainagent.go +++ b/agent/mainagent.go @@ -126,7 +126,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db. tsx.steerWork = m.steerWork // enable steer_work tool (nil = unavailable) // domain tools + basic default toolset (Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash) // when the asset coverage feature is off, drop add_task_scope/list_untested_assets (not in the prompt). - base := append(tsx.DropCoverageTools(tsx.MainAgentTools()), actool.DefaultTools()...) + base := append(tsx.DropCoverageTools(tsx.MainAgentTools()), defaultTools(m.workDir)...) ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)}) tools, def, cleanup := AugmentTools(ctx, "mainagent", base) defer cleanup() diff --git a/agent/planner.go b/agent/planner.go index 43e5fea..4b8809e 100644 --- a/agent/planner.go +++ b/agent/planner.go @@ -486,7 +486,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts } // Domain tools + the basic default tool set (Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash). // When the asset-coverage feature is off, drop add_task_scope/list_untested_assets (not in the prompt). - base := append(tsx.DropCoverageTools(tsx.PlannerTools()), actool.DefaultTools()...) + base := append(tsx.DropCoverageTools(tsx.PlannerTools()), defaultTools(p.workDir)...) ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)}) tools, def, cleanup := AugmentTools(WithToolQuery(ctx, plannerToolQuery(goal, triggers)), "planner", base) defer cleanup() diff --git a/agent/provider.go b/agent/provider.go index 4c3a538..96d39a6 100644 --- a/agent/provider.go +++ b/agent/provider.go @@ -27,6 +27,7 @@ import ( "github.com/Autumn-27/norma/compaction" "github.com/Autumn-27/norma/llm" acperm "github.com/Autumn-27/norma/permission" + actool "github.com/Autumn-27/norma/tool" "github.com/Autumn-27/norma/transcript" ) @@ -648,6 +649,7 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error reply, err := agentcore.Run(ctx, agentcore.Options{ Provider: prov, SystemPrompt: []string{"You are a connection test. Just output the two characters OK — no thinking, no explanation, nothing else."}, + Tools: []actool.CoreTool{}, // not nil: nil means the SDK's unconfined file and shell tools PermissionMode: acperm.ModeBypass, MaxTurns: 1, MaxTokens: 8192, diff --git a/agent/side_questions_test.go b/agent/side_questions_test.go index 176a57d..52cf40b 100644 --- a/agent/side_questions_test.go +++ b/agent/side_questions_test.go @@ -59,7 +59,11 @@ func TestSideActualChatCheckpointToolResultAndTranscriptIsolation(t *testing.T) for _, streaming := range []bool{false, true} { t.Run(map[bool]string{true: "stream", false: "atomic"}[streaming], func(t *testing.T) { dir := t.TempDir() - file := filepath.Join(dir, "asset.txt") + // Inside the chat's session working directory: the file tools reach nothing else. + file := filepath.Join(dir, "sessions", "conv-987654", "asset.txt") + if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + t.Fatal(err) + } if err := os.WriteFile(file, []byte("controlled-homepage-result"), 0600); err != nil { t.Fatal(err) } diff --git a/agent/worker.go b/agent/worker.go index b8a29c3..2b5a947 100644 --- a/agent/worker.go +++ b/agent/worker.go @@ -174,14 +174,14 @@ func NewWorker(prov llm.Provider, model, workDir string, tx *transcript.Store, w return &Worker{prov: prov, model: model, workDir: workDir, tx: tx, window: window, maxTurns: maxTurns, extraTools: extra} } -// defaultToolsExcept returns actool.DefaultTools() minus the named tools (by +// defaultToolsExcept returns defaultTools(base) minus the named tools (by // CoreTool.Name()). Used to trim SDK default tools an agent shouldn't have. -func defaultToolsExcept(exclude ...string) []actool.CoreTool { +func defaultToolsExcept(base string, exclude ...string) []actool.CoreTool { drop := make(map[string]bool, len(exclude)) for _, n := range exclude { drop[n] = true } - all := actool.DefaultTools() + all := defaultTools(base) out := make([]actool.CoreTool, 0, len(all)) for _, t := range all { if !drop[t.Name()] { @@ -445,7 +445,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db. // searching goes through Bash(grep/find) — narrowing the tool surface and reducing // low-value calls. The rest of the SDK default tools (Read/Write/Edit/LS/Bash/Sleep) // are kept as usual. - base = append(base, defaultToolsExcept("MultiEdit", "Glob", "Grep")...) + base = append(base, defaultToolsExcept(w.workDir, "MultiEdit", "Glob", "Grep")...) ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts), IntentID: intent.ID}) tools, def, cleanup := AugmentTools(WithToolQuery(ctx, nodeSummary(intent)), "worker", base) defer cleanup() diff --git a/db/intercept_persistence_seed.go b/db/intercept_persistence_seed.go index 71e7166..479a938 100644 --- a/db/intercept_persistence_seed.go +++ b/db/intercept_persistence_seed.go @@ -33,10 +33,14 @@ func (d *DB) seedPersistenceApprovalRules() error { message: "Approval needed: the agent asks to create or change a skill file. Every agent that sees the skill loads its content as instructions.", }, } + // intercept_rules.name has no unique index, so ON CONFLICT cannot apply: the insert + // is conditional on the name instead. A start that stopped between these inserts + // and SetSetting re-runs them without duplicating a rule. for _, r := range rules { if _, err := d.Exec(` INSERT INTO intercept_rules(name, enabled, priority, match_target, match_type, pattern, action, message, timeout_enabled, timeout_seconds, timeout_action) -VALUES ($1, true, 95, 'tool_name', 'regex', $2, 'ask', $3, false, 60, 'deny')`, +SELECT $1, true, 95, 'tool_name', 'regex', $2, 'ask', $3, false, 60, 'deny' +WHERE NOT EXISTS (SELECT 1 FROM intercept_rules WHERE name = $1)`, r.name, r.pattern, r.message, ); err != nil { return fmt.Errorf("rule %q: %w", r.name, err) diff --git a/db/intercept_persistence_seed_test.go b/db/intercept_persistence_seed_test.go new file mode 100644 index 0000000..275e2ca --- /dev/null +++ b/db/intercept_persistence_seed_test.go @@ -0,0 +1,34 @@ +package db + +import "testing" + +// A start that stopped after the rule inserts and before the settings flag runs the +// seed again on the next start: it must succeed and must not duplicate a rule. +func TestSeedPersistenceApprovalRulesIsIdempotent(t *testing.T) { + d := openTargetDB(t) // Open already ran the seed once + names := []string{ + "[built-in] Persistent change: custom tool", + "[built-in] Persistent change: MCP server", + "[built-in] Persistent change: skill", + } + for range 2 { + if _, err := d.Exec(`DELETE FROM settings WHERE key = 'intercept_persistence_rules_v1'`); err != nil { + t.Fatal(err) + } + if err := d.seedPersistenceApprovalRules(); err != nil { + t.Fatalf("seed re-run failed: %v", err) + } + } + for _, name := range names { + var n int + if err := d.QueryRow(`SELECT count(*) FROM intercept_rules WHERE name = $1`, name).Scan(&n); err != nil { + t.Fatal(err) + } + if n != 1 { + t.Errorf("%q: %d rows, want 1", name, n) + } + } + if v, _, _ := d.GetSetting("intercept_persistence_rules_v1"); v != "done" { + t.Errorf("settings flag = %q, want done", v) + } +} diff --git a/docker-compose.yml b/docker-compose.yml index ecfb72b..00e28c5 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -23,6 +23,10 @@ services: args: ARTEX_VERSION: ${ARTEX_VERSION:-dev} image: artex:local + # Agent processes run as an unprivileged executor (-exec-uid): no setuid program + # or file capability may raise them back to root. + security_opt: + - "no-new-privileges:true" depends_on: postgres: condition: service_healthy diff --git a/server/customtool.go b/server/customtool.go index 1dc8999..79d05e8 100644 --- a/server/customtool.go +++ b/server/customtool.go @@ -515,7 +515,6 @@ func execPython(ctx context.Context, interp, key, code string, params map[string runCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() c := exec.CommandContext(runCtx, interp, tmp) - applyExecCredential(c, priv) c.Dir = workDir c.Env = append(os.Environ(), sessionEnv...) // session proxy env for k, v := range params { // scalar params mirrored as TOOL_ @@ -523,6 +522,7 @@ func execPython(ctx context.Context, interp, key, code string, params map[string c.Env = append(c.Env, "TOOL_"+strings.ToUpper(k)+"="+sv) } } + applyExecCredential(c, priv) // after c.Env: it sets the executor's HOME there pj, _ := json.Marshal(params) c.Stdin = bytes.NewReader(pj) // parameter JSON goes via stdin out, err := c.CombinedOutput() diff --git a/server/env_scrub.go b/server/env_scrub.go index 44e57a1..c591ff9 100644 --- a/server/env_scrub.go +++ b/server/env_scrub.go @@ -4,7 +4,9 @@ import "os" // secretEnv lists the credentials read from the environment only at startup: // ARTEX_PG_DSN and ARTEX_SECRET_KEY by NewManager, the API keys by agent.FromEnv inside New. -var secretEnv = []string{"ARTEX_PG_DSN", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY"} +// agent.FromEnv also reads ARTEX_LLM_PROXY and ARTEX_LLM_BASE_URL: both are URLs that +// can carry credentials in their userinfo (http://user:pass@proxy:3128). +var secretEnv = []string{"ARTEX_PG_DSN", "ARTEX_SECRET_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "ARTEX_LLM_PROXY", "ARTEX_LLM_BASE_URL"} // ScrubSecretEnv removes secretEnv from the process environment once startup has // read it. Child processes (agent shells, custom tools, MCP stdio servers) copy diff --git a/server/env_scrub_test.go b/server/env_scrub_test.go index d840869..3479e62 100644 --- a/server/env_scrub_test.go +++ b/server/env_scrub_test.go @@ -6,6 +6,8 @@ import ( "os/exec" "strings" "testing" + + "github.com/Autumn-27/artex/agent" ) // A child process spawned after startup must not see the startup secrets, while @@ -64,3 +66,34 @@ func TestNewAppliesSecretScrubOption(t *testing.T) { t.Fatal("New did not apply WithSecretScrub: the secrets are still in the environment") } } + +// The LLM proxy and endpoint URLs can carry user:pass@ credentials. They are +// scrubbed and sealed like the keys, and a child spawned after the scrub sees +// neither, while agent.FromEnv still read them before it. +func TestSecretEnvCoversCredentialURLs(t *testing.T) { + sh, err := exec.LookPath("sh") + if err != nil { + t.Skip("no sh in PATH") + } + for _, k := range []string{"ARTEX_LLM_PROXY", "ARTEX_LLM_BASE_URL"} { + if !isSecretName(k) { + t.Errorf("%s is not in secretEnv", k) + } + } + t.Setenv("ARTEX_LLM_PROVIDER", "openai") + t.Setenv("OPENAI_API_KEY", "sk-test") + t.Setenv("ARTEX_LLM_PROXY", "http://proxyuser:proxypass@proxy.internal:3128") + t.Setenv("ARTEX_LLM_BASE_URL", "https://apiuser:apipass@llm.internal/v1") + cfg, ok := agent.FromEnv() + if !ok || cfg.Proxy != "http://proxyuser:proxypass@proxy.internal:3128" || cfg.BaseURL != "https://apiuser:apipass@llm.internal/v1" { + t.Fatalf("FromEnv must read the URLs before the scrub: ok=%v proxy=%q base=%q", ok, cfg.Proxy, cfg.BaseURL) + } + ScrubSecretEnv() + out, err := exec.Command(sh, "-c", "env").Output() + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(out), "proxypass") || strings.Contains(string(out), "apipass") { + t.Fatalf("a child process still sees the proxy or endpoint credentials:\n%s", out) + } +} diff --git a/server/envseal_linux_test.go b/server/envseal_linux_test.go index 2bae807..0a58fbb 100644 --- a/server/envseal_linux_test.go +++ b/server/envseal_linux_test.go @@ -54,6 +54,9 @@ func TestSealedEnvironmentHandoff(t *testing.T) { "ARTEX_SECRET_KEY": "", "ANTHROPIC_API_KEY": "sk-ant-test", "OPENAI_API_KEY": "=leading-equals", + // Proxy and endpoint URLs can carry credentials in their userinfo. + "ARTEX_LLM_PROXY": "http://proxyuser:proxypass@proxy.internal:3128", + "ARTEX_LLM_BASE_URL": "https://apiuser:apipass@llm.internal/v1", } env := os.Environ() for k, v := range want { diff --git a/server/execpriv_root_linux_test.go b/server/execpriv_root_linux_test.go new file mode 100644 index 0000000..6fc2d1e --- /dev/null +++ b/server/execpriv_root_linux_test.go @@ -0,0 +1,173 @@ +//go:build linux + +package server + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + actool "github.com/Autumn-27/norma/tool" +) + +// Root tests of the three executor paths: the Bash tool through the PATH shim, a +// custom tool through SysProcAttr.Credential, and an MCP stdio command through the +// drop shim. Each runs the same probe as the agent would and must show the executor +// identity, no access to a 0600 root file or to the server's /proc environ, and a +// writable HOME and cache. + +type execRootFixture struct { + priv ExecPrivilege + home, secret, work string +} + +func newExecRootFixture(t *testing.T) *execRootFixture { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("needs root") + } + old := syscall.Umask(0o022) + syscall.Umask(old) + t.Cleanup(func() { syscall.Umask(old) }) + // InstallBashShim and PrepareExecPrivilege set these process-wide; restore them. + for _, k := range []string{"PATH", envExecBash, envExecUID, envExecGID, envExecHome} { + t.Setenv(k, os.Getenv(k)) + } + // A data directory like /app/data: root-owned and traversable. + dataDir, err := os.MkdirTemp("", "artex-exec-root-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dataDir) }) + if err := os.Chmod(dataDir, 0o755); err != nil { + t.Fatal(err) + } + priv, err := ResolveExecPrivilege(DefaultExecUID, DefaultExecGID, true) + if err != nil { + t.Fatal(err) + } + if err := PrepareExecPrivilege(priv, dataDir, "", ""); err != nil { + t.Fatal(err) + } + secret := filepath.Join(dataDir, "root-only.key") + if err := os.WriteFile(secret, []byte("root-secret\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := os.ReadFile(secret); err != nil { + t.Fatalf("root must read its own key: %v", err) + } + work := filepath.Join(dataDir, "tasks", "1") + if err := os.MkdirAll(work, 0o775); err != nil { + t.Fatal(err) + } + return &execRootFixture{priv: priv, home: filepath.Join(dataDir, execHomeDir), secret: secret, work: work} +} + +// probe is the shell script each path runs as the executor. +func (f *execRootFixture) probe() string { + return fmt.Sprintf(`echo "uid=$(id -u) gid=$(id -g) groups=$(id -G)" +if cat '%s' >/dev/null 2>&1; then echo secret=read; else echo secret=denied; fi +if cat /proc/%d/environ >/dev/null 2>&1; then echo environ=read; else echo environ=denied; fi +echo "home=$HOME cache=$XDG_CACHE_HOME" +if mkdir -p "$XDG_CACHE_HOME/probe" && echo ok > "$XDG_CACHE_HOME/probe/x"; then echo cache=written; else echo cache=failed; fi +`, f.secret, os.Getpid()) +} + +func (f *execRootFixture) check(t *testing.T, path, out string) { + t.Helper() + for _, want := range []string{ + fmt.Sprintf("uid=%d gid=%d groups=%d", DefaultExecUID, DefaultExecGID, DefaultExecGID), + "secret=denied", + "environ=denied", + "home=" + f.home + " cache=" + filepath.Join(f.home, ".cache"), + "cache=written", + } { + if !strings.Contains(out, want) { + t.Errorf("%s: want %q in the probe output:\n%s", path, want, out) + } + } + fi, err := os.Stat(filepath.Join(f.home, ".cache", "probe", "x")) + if err != nil { + t.Fatalf("%s: cache file missing: %v", path, err) + } + if st := fi.Sys().(*syscall.Stat_t); st.Uid != DefaultExecUID { + t.Errorf("%s: cache file owned by uid %d, want %d", path, st.Uid, DefaultExecUID) + } + t.Logf("%s probe output:\n%s", path, out) +} + +// Norma's Bash tool runs exec.Command("bash"): the PATH shim drops and execs bash. +func TestExecutorBashShimAsRoot(t *testing.T) { + f := newExecRootFixture(t) + if err := InstallBashShim(f.priv); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(filepath.SplitList(os.Getenv("PATH"))[0]) }) + in, _ := json.Marshal(map[string]string{"command": f.probe()}) + res, err := actool.NewBash().Call(context.Background(), in, &actool.ToolContext{WorkingDir: f.work}) + if err != nil { + t.Fatal(err) + } + f.check(t, "bash shim", res.Flatten()) +} + +// A custom script tool runs through execPython, which applies the credential. +func TestExecutorCustomToolAsRoot(t *testing.T) { + f := newExecRootFixture(t) + py, err := exec.LookPath("python3") + if err != nil { + t.Fatalf("python3 is needed for the custom-tool path: %v", err) + } + code := `import os, subprocess +print(subprocess.run(["sh", "-c", os.environ["PROBE"]], capture_output=True, text=True).stdout)` + out, err := execPython(context.Background(), py, "probe", code, nil, f.work, []string{"PROBE=" + f.probe()}, 30*time.Second, f.priv) + if err != nil { + t.Fatal(err) + } + f.check(t, "custom tool", out) +} + +// An MCP stdio command is started as ` __artex-exec-drop uid gid -- cmd`; +// mcp.NewStdioClient runs it with exec.Command and the server environment. +func TestExecutorMCPStdioAsRoot(t *testing.T) { + f := newExecRootFixture(t) + command, args, err := execDropCommand(f.priv, "sh", []string{"-c", f.probe()}) + if err != nil { + t.Fatal(err) + } + c := exec.Command(command, args...) + c.Dir = f.work + out, err := c.CombinedOutput() + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + f.check(t, "mcp stdio", string(out)) +} + +// applyExecCredential sets the credential and the executor's HOME; the later env +// entry wins in exec.Cmd. Runs without root: nothing is started. +func TestApplyExecCredentialSetsExecutorHome(t *testing.T) { + t.Setenv(envExecHome, "/data/exec-home") + c := exec.Command("true") + c.Env = []string{"HOME=/root", "KEEP=1"} + applyExecCredential(c, ExecPrivilege{Enabled: true, UID: 10001, GID: 10002}) + if cr := c.SysProcAttr.Credential; cr == nil || cr.Uid != 10001 || cr.Gid != 10002 { + t.Fatalf("credential = %+v", c.SysProcAttr.Credential) + } + want := []string{"HOME=/root", "KEEP=1", "HOME=/data/exec-home", "XDG_CACHE_HOME=/data/exec-home/.cache"} + if strings.Join(c.Env, "|") != strings.Join(want, "|") { + t.Fatalf("env = %v, want %v", c.Env, want) + } + disabled := exec.Command("true") + applyExecCredential(disabled, ExecPrivilege{}) + if disabled.SysProcAttr != nil || disabled.Env != nil { + t.Fatal("a disabled privilege must leave the command unchanged") + } +} diff --git a/server/execpriv_unix.go b/server/execpriv_unix.go index 7409058..38910ff 100644 --- a/server/execpriv_unix.go +++ b/server/execpriv_unix.go @@ -15,20 +15,27 @@ import ( "syscall" ) -// Environment names the Bash shim reads. They carry no secret: the executor id and -// the real bash path. +// Environment names the shims read. They carry no secret: the executor id, the real +// bash path and the executor's home directory. const ( envExecBash = "ARTEX_EXEC_BASH" envExecUID = "ARTEX_EXEC_UID" envExecGID = "ARTEX_EXEC_GID" + envExecHome = "ARTEX_EXEC_HOME" ) +// execHomeDir is the executor's home under the data directory. The server's HOME +// (/root in the image) is not writable for the executor, so caches of npm, go, pip, +// bbot or Playwright would fail there. +const execHomeDir = "exec-home" + func execPrivilegeSupported() bool { return true } func serverIsRoot() bool { return os.Geteuid() == 0 } // applyExecCredential runs c as the executor identity. The server's own children -// (custom tools) use it directly; the Norma children go through the shims. +// (custom tools) use it directly; the Norma children go through the shims. Call it +// after c.Env is set: it points HOME and XDG_CACHE_HOME at the executor's home. func applyExecCredential(c *exec.Cmd, p ExecPrivilege) { if !p.Enabled { return @@ -37,6 +44,49 @@ func applyExecCredential(c *exec.Cmd, p ExecPrivilege) { c.SysProcAttr = &syscall.SysProcAttr{} } c.SysProcAttr.Credential = &syscall.Credential{Uid: p.UID, Gid: p.GID, Groups: []uint32{p.GID}} + if home := execHomeEnv(); home != nil { + if c.Env == nil { + c.Env = os.Environ() + } + c.Env = append(c.Env, home...) // later entries win in exec.Cmd + } +} + +// execHomeEnv returns HOME and XDG_CACHE_HOME for an executor process, or nil when +// PrepareExecPrivilege has not set up the home. +func execHomeEnv() []string { + home := os.Getenv(envExecHome) + if home == "" { + return nil + } + return []string{"HOME=" + home, "XDG_CACHE_HOME=" + filepath.Join(home, ".cache")} +} + +// prepareExecHome creates the executor's home, owned by the executor, and records +// its path for the shims and applyExecCredential. +func prepareExecHome(p ExecPrivilege, dataDir string) error { + abs, err := filepath.Abs(dataDir) + if err != nil { + return err + } + home := filepath.Join(abs, execHomeDir) + if err := os.MkdirAll(home, 0o700); err != nil { + return err + } + fi, err := os.Lstat(home) + if err != nil { + return err + } + if !fi.IsDir() { + return fmt.Errorf("%s is not a directory", home) + } + if err := os.Lchown(home, int(p.UID), int(p.GID)); err != nil { + return err + } + if err := os.Chmod(home, 0o700); err != nil { + return err + } + return os.Setenv(envExecHome, home) } // prepareExecScript lets the executor read a script the server wrote: the file stays @@ -73,6 +123,9 @@ func PrepareExecPrivilege(p ExecPrivilege, dataDir, keyDir, configPath string) e return fmt.Errorf("share %s workspace with the executor group: %w", sub, err) } } + if err := prepareExecHome(p, dataDir); err != nil { + return fmt.Errorf("prepare the executor home: %w", err) + } tasks := filepath.Join(dataDir, "tasks") for _, name := range []string{"jwt.key", "secret.key"} { if keyDir == "" { @@ -189,12 +242,27 @@ func runBashShim(argv []string) { if err != nil { shimFail(err) } - if err := dropTo(uid, gid); err != nil { + if err := enterExecutor(uid, gid); err != nil { shimFail(err) } shimExec(os.Getenv(envExecBash), argv) } +// enterExecutor drops to uid and gid. When this call performs the switch (not in a +// nested shell already running as the executor, whose HOME the agent may have set), +// HOME and XDG_CACHE_HOME move to the executor's home first. +func enterExecutor(uid, gid int) error { + if os.Getuid() != uid || os.Getgid() != gid { + for _, kv := range execHomeEnv() { + k, v, _ := strings.Cut(kv, "=") + if err := os.Setenv(k, v); err != nil { + return err + } + } + } + return dropTo(uid, gid) +} + // runDropShim handles: -- . func runDropShim(args []string) { if len(args) < 3 || args[2] != "--" { @@ -214,7 +282,7 @@ func runDropShim(args []string) { } target = resolved } - if err := dropTo(uid, gid); err != nil { + if err := enterExecutor(uid, gid); err != nil { shimFail(err) } shimExec(target, args[3:]) diff --git a/server/testmain_test.go b/server/testmain_test.go index 13dd97a..d0cfb4a 100644 --- a/server/testmain_test.go +++ b/server/testmain_test.go @@ -13,6 +13,9 @@ import ( // server test suite so cross-package DELETE cleanup races with db/agent // packages are avoided when running `go test ./...`. func TestMain(m *testing.M) { + // The executor tests (execpriv_root_linux_test.go) start this binary as the bash + // shim and as the MCP drop shim, the way cmd/artex's main does. + RunExecShimIfRequested(os.Args) // Own database per package (#80): with separate databases, packages stop // contending on shared tables and the advisory lock below stops // serializing go test ./... across packages. diff --git a/traffic/ca_perm_test.go b/traffic/ca_perm_test.go new file mode 100644 index 0000000..38fb6ce --- /dev/null +++ b/traffic/ca_perm_test.go @@ -0,0 +1,47 @@ +package traffic + +import ( + "os" + "path/filepath" + "runtime" + "testing" +) + +// The MITM CA private key is the server's alone; the CA certificate stays readable +// for the agents' tools. Checked on first creation and on a restart that finds a +// key an older version left world-readable. +func TestOpenRestrictsCAKey(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("unix permission bits") + } + dir := t.TempDir() + key := filepath.Join(dir, "_ca", "mitmproxy-ca.pem") + check := func(stage string) { + t.Helper() + tr, err := Open(dir, "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + cert := tr.CACertPath() + tr.Close() + ki, err := os.Stat(key) + if err != nil { + t.Fatal(err) + } + if ki.Mode().Perm() != 0o600 { + t.Errorf("%s: CA key mode %o, want 600", stage, ki.Mode().Perm()) + } + ci, err := os.Stat(cert) + if err != nil { + t.Fatal(err) + } + if ci.Mode().Perm()&0o004 == 0 { + t.Errorf("%s: CA certificate mode %o must stay world-readable", stage, ci.Mode().Perm()) + } + } + check("created") + if err := os.Chmod(key, 0o644); err != nil { + t.Fatal(err) + } + check("reopened") +} diff --git a/traffic/traffic.go b/traffic/traffic.go index 4c5b65d..4c0cf75 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -272,6 +272,14 @@ func Open(dir, addr string) (*Traffic, error) { db.Close() return nil, err } + // go-mitmproxy writes the CA private key with os.Create (0666 less the umask), + // readable by every local user, the agents' executor included. Only the proxy + // in this process needs it. The certificate beside it (CACertPath) stays + // readable: the agents' tools trust it. + if err := os.Chmod(filepath.Join(dir, "_ca", "mitmproxy-ca.pem"), 0o600); err != nil { + db.Close() + return nil, fmt.Errorf("restrict the MITM CA key: %w", err) + } // Upstream selection. By default (no global egress proxy set) targets are // dialed DIRECTLY: go-mitmproxy's own default upstream uses // http.ProxyFromEnvironment, so an HTTP_PROXY/HTTPS_PROXY in the environment