fix(agent): scope the sandbox tools to the workspace they actually serve

Three inconsistencies in how the sandbox tools are granted and bounded.

Tool checkboxes that decide nothing. list/read/write/edit_sandbox_file,
shell_exec, read_skill and execute_skill_script were offered in the settings
UI, but registerSandboxFileTools, registerSandboxShellIfAllowed and
initializeSkillsManager all register from the capability (a sandbox with a
session filesystem, SkillsEnabled, install mode) and never consult
AllowedTools. Clearing a checkbox changed nothing. Drop them from
AvailableToolDefinitions the way search_memory and web_search already are,
so the switch that decides is the only thing shown.

Readers narrower than writers. write_sandbox_file accepts anything under
/workspace except the attachment tree, while list/read stopped at the
artifact output dir, so the agent could not read back the scratch script it
had just written and had to detour through `shell_exec cat`. Since
shell_exec reaches those files anyway the narrowing bought no safety; the
inspectable roots now cover /workspace, still ordered so a reported root
names the artifact or attachment tree when the path is inside one.

Two answers for one directory. A WEKNORA_SKILL_OUTPUT_DIR override was
validated on the execution path (falling back to /workspace/output) but
taken as-is from the host environment by the tools and ArtifactCollector, so
an override outside /workspace pointed the readers at a directory no skill
could write. Both now go through sandbox.ValidatedSessionOutputDir.
main
wizardchen 2026-09-02 16:10:24 +08:00 committed by lyingbug
parent 439443e1e1
commit 79995b996f
8 changed files with 136 additions and 48 deletions

View File

@ -4,7 +4,6 @@ import (
"context"
"fmt"
"os"
"path"
"strings"
"sync"
@ -71,15 +70,24 @@ const defaultArtifactOutputDir = "/workspace/output"
// callers such as ArtifactCollector can list the same directory when
// draining artifacts after Execute returns.
//
// Resolution order (first non-empty wins):
// 1. WEKNORA_SKILL_OUTPUT_DIR from the host environment (ops override).
// Resolution order (first usable wins):
// 1. WEKNORA_SKILL_OUTPUT_DIR from the host environment (ops override), when
// it names a directory inside the session workspace.
// 2. defaultArtifactOutputDir.
//
// The override goes through sandbox.ValidatedSessionOutputDir, the same gate
// the sandbox applies to a tenant's override. An operator who points this
// outside /workspace would otherwise send the readers (this function feeds the
// sandbox file tools and ArtifactCollector) to a directory no skill can write,
// since execution refuses the same path and falls back.
//
// Callers are expected to treat the returned string as read-only: the path
// is normalised (no trailing slash) so it can be joined safely.
func ArtifactOutputDir() string {
if v := strings.TrimSpace(os.Getenv(artifactOutputEnvVar)); v != "" {
return path.Clean(v)
if clean, ok := sandbox.ValidatedSessionOutputDir(v); ok {
return clean
}
}
return defaultArtifactOutputDir
}

View File

@ -20,14 +20,26 @@ const (
ToolDataSchema = "data_schema"
ToolWebSearch = "web_search"
ToolWebFetch = "web_fetch"
// Skills-related tools (only available when skills are enabled)
// Skills-related tools (only available when skills are enabled).
//
// Like the sandbox tools below, these are absent from
// AvailableToolDefinitions and DefaultAllowedTools: initializeSkillsManager
// registers them from SkillsEnabled plus a usable sandbox, so a tool
// checkbox could neither grant nor withhold them.
ToolExecuteSkillScript = "execute_skill_script"
ToolReadSkill = "read_skill"
// Sandbox filesystem tools (only available when the sandbox backend
// supports per-session files — Cube, E2B, Docker). list/read inspect
// output and staged attachments; write creates text files so generated
// the session workspace; write creates text files so generated
// scripts do not have to travel through a shell_exec heredoc; edit
// patches an existing file without regenerating it.
//
// Deliberately absent from AvailableToolDefinitions and
// DefaultAllowedTools, like search_memory and web_search: the sandbox
// switch already decides whether a run has a workspace at all, and
// registerSandboxFileTools registers these from that capability rather
// than from the allowlist. A checkbox would have been a lie — clearing
// it changed nothing.
ToolListSandboxFiles = "list_sandbox_files"
ToolReadSandboxFile = "read_sandbox_file"
ToolWriteSandboxFile = "write_sandbox_file"
@ -46,6 +58,10 @@ const (
// current session's sandbox (dependency installs, environment probing).
// Registered only when the resolved backend advertises the session shell
// capability (Cube, E2B, Docker). The command never runs on the WeKnora host.
//
// Also absent from AvailableToolDefinitions: registerSandboxShellIfAllowed
// keys it on SkillsEnabled (or install mode), so the shell follows the
// skills switch and not a per-agent tool checkbox.
ToolShellExec = "shell_exec"
// Wiki-related tools (only available when wiki KBs are in scope)
ToolWikiReadPage = "wiki_read_page"
@ -86,13 +102,6 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolDatabaseQuery, Label: "查询数据库", Description: "查询数据库中的信息"},
{Name: ToolDataAnalysis, Label: "数据分析", Description: "理解数据文件并进行数据分析"},
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},
{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
{Name: ToolListSandboxFiles, Label: "列出沙箱文件", Description: "列出当前会话沙箱产出目录下的文件"},
{Name: ToolReadSandboxFile, Label: "读取沙箱文件", Description: "读取当前会话沙箱中已生成的文件内容"},
{Name: ToolWriteSandboxFile, Label: "写入沙箱文件", Description: "向当前会话沙箱写入文本文件(脚本、报告等)"},
{Name: ToolEditSandboxFile, Label: "编辑沙箱文件", Description: "精确替换当前会话沙箱中已有文本文件的片段"},
{Name: ToolShellExec, Label: "执行沙箱命令", Description: "在当前会话沙箱中执行 shell 命令(如安装依赖、检查环境)"},
{Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},
{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
{Name: ToolWikiReadSourceDoc, Label: "精读源文档", Description: "使用知识点深入阅读特定原始文档"},

View File

@ -9,13 +9,11 @@
// - Session-scoped: the sandbox path is resolved from the tool exec
// context (`ToolExecContext.SessionID`). The LLM cannot pass an
// arbitrary session ID.
// - Directory guardrail: `path` must resolve underneath one of the
// inspectable roots — the artifact output dir
// (`$WEKNORA_SKILL_OUTPUT_DIR`, default `/workspace/output`) or the
// session input dir (`/workspace/input`). Output stays aligned with
// ArtifactCollector; input is where chat attachments are staged.
// Omitting `path` still lists output so a listing does not dump
// every attachment into context.
// - Directory guardrail: `path` must resolve underneath `/workspace`,
// the session's own tree — the same scope write_sandbox_file may
// create in. Omitting `path` lists the artifact output dir
// (`$WEKNORA_SKILL_OUTPUT_DIR`, default `/workspace/output`) so a
// listing does not dump every attachment and scratch file into context.
// - Read-only: this tool never creates, modifies or deletes anything
// inside the sandbox. Model-authored files go through write_sandbox_file.
// - Graceful "no sandbox": if the session has never spawned a sandbox
@ -91,14 +89,15 @@ var listSandboxFilesTool = BaseTool{
Call ` + "`read_skill(skill_name=...)`" + ` instead: that returns SKILL.md and
the skill's file list (scripts, docs). Those trees also contain
` + "`.venv`" + ` / ` + "`node_modules`" + `.
- Do not list ` + "`/workspace`" + ` itself, ` + "`/etc`" + `, or other system paths.
- Do not list ` + "`/etc`" + ` or other system paths.
## Path Rules
- ` + "`path`" + ` is optional. When omitted, the tool lists the default artifact
output directory (` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `).
- When provided, ` + "`path`" + ` MUST sit under the artifact output directory or
the session input directory (` + "`/workspace/input`" + `). Attempts to list
arbitrary sandbox paths (e.g. ` + "`/etc`" + `, ` + "`/home`" + `, skill image dirs) are rejected.
- When provided, ` + "`path`" + ` MUST sit under ` + "`/workspace`" + ` — anything
this session can write, including scratch files you created with
` + "`write_sandbox_file`" + `. Paths outside it (` + "`/etc`" + `, ` + "`/home`" + `,
skill image dirs) are rejected.
- Listing is recursive: sub-directories are traversed automatically and
only files are returned in the flat listing.
@ -115,8 +114,8 @@ var listSandboxFilesTool = BaseTool{
type ListSandboxFilesInput struct {
// Path is the absolute path inside the sandbox to list. When empty
// the tool falls back to skills.ArtifactOutputDir(). Must sit under
// the artifact output directory or /workspace/input.
Path string `json:"path,omitempty" jsonschema:"Optional absolute sandbox path to list. Defaults to the session's artifact output directory. Must sit under that directory or /workspace/input."`
// /workspace.
Path string `json:"path,omitempty" jsonschema:"Optional absolute sandbox path to list, under /workspace. Defaults to the session's artifact output directory."` //nolint:lll // one-line struct tag
// MaxEntries caps the listing size to protect the LLM context.
// Zero uses defaultListSandboxMaxEntries.
MaxEntries int `json:"max_entries,omitempty" jsonschema:"Optional cap on the number of entries returned. Defaults to 200, hard-capped at 500. Use a smaller value when you only need to check whether a specific file exists."`
@ -292,16 +291,25 @@ func resolveSessionID(ctx context.Context) string {
}
// sandboxInspectableRoots is the allowlist for list_sandbox_files and
// read_sandbox_file. Artifact output is where skills write downloadable
// files; session input is where chat attachments are staged. Anything
// else (including /workspace itself) stays unreachable so these tools
// cannot become a general-purpose filesystem reader.
// read_sandbox_file: the session workspace, and nothing outside it.
//
// It matches what write_sandbox_file may create. Narrowing the readers to
// artifacts and attachments used to leave the agent unable to read back the
// scratch script it had just written to /workspace, which bought no safety —
// shell_exec reaches the same files — and only forced a detour through `cat`.
//
// The list is ordered most specific first so the reported root still names the
// artifact or attachment tree when the path is inside one.
func sandboxInspectableRoots() []string {
return []string{skills.ArtifactOutputDir(), sandbox.SessionInputRoot}
return []string{
skills.ArtifactOutputDir(),
sandbox.SessionInputRoot,
sandbox.SessionWorkspaceRoot,
}
}
func inspectableRootsDescription() string {
return strings.Join(sandboxInspectableRoots(), ", ")
return sandbox.SessionWorkspaceRoot
}
// inspectablePathError explains a refused list/read path. Skill image
@ -309,13 +317,13 @@ func inspectableRootsDescription() string {
// in read_skill's environment section and retries with this tool or ls.
func inspectablePathError(requested string) string {
base := fmt.Sprintf(
"this tool only lists/reads session artifacts and attachments under %s. path %q is outside that scope",
"this tool only lists/reads the session workspace under %s. path %q is outside that scope",
inspectableRootsDescription(), requested,
)
clean := path.Clean(strings.TrimSpace(requested))
name, inImage := sandbox.SkillNameFromImagePath(clean)
if !inImage {
return base + ". Those tools only see session artifacts and attachments. Skill files: read_skill(skill_name=..., file_path=...)."
return base + ". Skill files: read_skill(skill_name=..., file_path=...)."
}
if name == "" {
return base + fmt.Sprintf(

View File

@ -8,10 +8,9 @@
// - Session-scoped: path must belong to the current session's sandbox,
// enforced by delegating to SandboxFileSource.ReadSessionFile which
// itself takes the session ID from context.
// - Directory guardrail: path must sit underneath the artifact output
// directory or /workspace/input. Output is a companion to
// ArtifactCollector; input is where chat attachments are staged.
// Skills that need to peek elsewhere should print via stdout.
// - Directory guardrail: path must sit underneath /workspace, matching
// what this session may write. Skills that need to peek outside it
// should print via stdout.
// - Stat-first size cap: files over 64 KiB are never downloaded. The
// model receives metadata and uses shell_exec with sed/head/tail/grep/awk
// to inspect only the relevant text section.
@ -69,12 +68,10 @@ var readSandboxFileTool = BaseTool{
with ` + "`skill_name`" + ` / ` + "`file_path`" + `.
## Path Rules
- ` + "`path`" + ` MUST be an absolute path returned by ` + "`list_sandbox_files`" + `
or listed in the current ` + "`<sandbox_attachments>`" + ` block.
- ` + "`path`" + ` MUST sit underneath the session's artifact output directory
(` + "`$WEKNORA_SKILL_OUTPUT_DIR`" + `, typically ` + "`/workspace/output`" + `) or the
session input directory (` + "`/workspace/input`" + `). Reads outside those
directories are rejected.
- ` + "`path`" + ` MUST be an absolute path under ` + "`/workspace`" + `: an
artifact under ` + "`/workspace/output`" + `, an attachment listed in
` + "`<sandbox_attachments>`" + `, or a scratch file you wrote yourself with
` + "`write_sandbox_file`" + `. Reads outside ` + "`/workspace`" + ` are rejected.
## Size Handling
- Files larger than 64 KiB are NOT downloaded or returned.
@ -92,8 +89,8 @@ var readSandboxFileTool = BaseTool{
// ReadSandboxFileInput defines the input parameters for read_sandbox_file.
type ReadSandboxFileInput struct {
// Path is the absolute path inside the sandbox to read. Required.
// Must sit underneath the artifact output directory or /workspace/input.
Path string `json:"path" jsonschema:"Absolute path inside the sandbox. Must sit under the session's artifact output directory (typically /workspace/output) or /workspace/input. Get valid paths from list_sandbox_files or the current sandbox_attachments block."`
// Must sit underneath /workspace.
Path string `json:"path" jsonschema:"Absolute path under /workspace: an artifact, an attachment, or a file you wrote yourself. Get paths from list_sandbox_files or sandbox_attachments."` //nolint:lll // one-line struct tag
// MaxBytes is the largest file the tool may download. Zero uses 64 KiB;
// callers may lower but never raise the hard 64 KiB ceiling.
MaxBytes int64 `json:"max_bytes,omitempty" jsonschema:"Optional maximum file size to read. Defaults to 65536 bytes and is hard-capped at 65536. Larger files are not downloaded; use shell_exec with sed/head/tail/grep/awk."`

View File

@ -179,13 +179,43 @@ func TestReadSandboxFileAllowsSessionInput(t *testing.T) {
assert.Equal(t, sandbox.SessionInputRoot, result.Data["root"])
}
// A file the agent wrote itself with write_sandbox_file must be readable
// again. The writers accept anything under /workspace outside the attachment
// tree, so readers that stopped at /workspace/output left the agent unable to
// re-read its own scratch script.
func TestReadSandboxFileAllowsWorkspaceScratchFile(t *testing.T) {
content := []byte("print('hi')\n")
source := &fakeSandboxFileSource{
stat: &sandbox.RemoteStatEntry{
Path: "/workspace/report.py",
Type: sandbox.RemoteEntryFile,
Size: int64(len(content)),
},
data: content,
}
result, err := NewReadSandboxFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/workspace/report.py"}`),
)
require.NoError(t, err)
require.True(t, result.Success)
assert.Contains(t, result.Output, string(content))
assert.Equal(t, sandbox.SessionWorkspaceRoot, result.Data["root"])
}
func TestReadSandboxFileRefusesOutsideInspectableRoots(t *testing.T) {
source := &fakeSandboxFileSource{
data: []byte("must not be read"),
stat: &sandbox.RemoteStatEntry{Path: "/etc/passwd", Type: sandbox.RemoteEntryFile, Size: 4},
}
for _, path := range []string{"/etc/passwd", "/workspace/other/file.txt", "/workspace"} {
for _, path := range []string{
"/etc/passwd",
"/home/user/.ssh/id_rsa",
"/opt/weknora/tenant/skills/pdf/SKILL.md",
} {
result, err := NewReadSandboxFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"`+path+`"}`),

View File

@ -141,6 +141,25 @@ func TestWriteSandboxFileRegistryHintsWhenPathMissing(t *testing.T) {
assert.Contains(t, result.Error, "put `path` first")
}
// The sandbox and skill tools are registered from the capability itself
// (registerSandboxFileTools / registerSandboxShellIfAllowed /
// initializeSkillsManager), never from the agent's tool allowlist. Offering
// them as checkboxes told the operator they could withhold a tool that would
// be registered anyway.
func TestSandboxCapabilityToolsAreNotToolListCheckboxes(t *testing.T) {
for _, name := range []string{
ToolListSandboxFiles, ToolReadSandboxFile,
ToolWriteSandboxFile, ToolEditSandboxFile, ToolShellExec,
ToolReadSkill, ToolExecuteSkillScript,
} {
require.NotContains(t, DefaultAllowedTools(), name)
for _, definition := range AvailableToolDefinitions() {
require.NotEqual(t, name, definition.Name,
"%s follows the sandbox switch, so a tool checkbox for it would do nothing", name)
}
}
}
func mustWriteSandboxArgs(path, content string) json.RawMessage {
raw, err := json.Marshal(map[string]string{"path": path, "content": content})
if err != nil {

View File

@ -389,7 +389,7 @@ func withWorkspaceEnvDefaults(env map[string]string) map[string]string {
func executionOutputDir(cfg *ExecuteConfig) string {
if cfg != nil && cfg.Env != nil {
if dir := strings.TrimSpace(cfg.Env[skillOutputEnvVar]); dir != "" {
if clean, err := cleanSessionWorkDir(dir, false); err == nil {
if clean, ok := ValidatedSessionOutputDir(dir); ok {
return clean
}
}

View File

@ -84,6 +84,23 @@ func RunnableWorkspaceScript(scriptPath string) (string, bool) {
return clean, true
}
// ValidatedSessionOutputDir normalises a configured artifact directory and
// reports whether it may be used.
//
// It is the single gate for every WEKNORA_SKILL_OUTPUT_DIR override, wherever
// it comes from: the host environment the app reads at startup, or a tenant's
// sandbox config. Without it the two disagreed — execution validated the path
// and fell back to SessionOutputRoot, while the tools and the artifact
// collector took the host value as-is, so an override pointing outside
// /workspace moved the readers somewhere the writers never wrote.
func ValidatedSessionOutputDir(dir string) (string, bool) {
clean, err := cleanSessionWorkDir(dir, false)
if err != nil {
return "", false
}
return clean, true
}
// ValidatedImageSkillDir reports whether skillDir is exactly one installed
// skill directory under SkillsImageRoot (for example /opt/weknora/tenant/skills/pdf).
func ValidatedImageSkillDir(skillDir string) (string, bool) {