fix(sandbox): separate file access from artifact publishing (#3356)

* fix(sandbox): separate file access from artifact publishing

* test(sandbox): align service coverage and pre-push checks with CI
main
lyingbug 2026-09-17 16:18:01 +08:00 committed by GitHub
parent 10973ed321
commit 5780cb0a71
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
27 changed files with 442 additions and 306 deletions

View File

@ -25,6 +25,8 @@ on:
- "licenses/**"
- "internal/textconv/data/**"
- "scripts/*license*.sh"
- "scripts/git-hooks/**"
- "scripts/test-git-hooks.sh"
- "cmd/desktop/build/windows/installer/project.nsi"
- ".github/workflows/app.yml"
pull_request:
@ -47,6 +49,8 @@ on:
- "licenses/**"
- "internal/textconv/data/**"
- "scripts/*license*.sh"
- "scripts/git-hooks/**"
- "scripts/test-git-hooks.sh"
- "cmd/desktop/build/windows/installer/project.nsi"
- ".github/workflows/app.yml"
workflow_dispatch:
@ -113,6 +117,9 @@ jobs:
exit 1
fi
- name: Verify Git hook test coverage
run: bash ./scripts/test-git-hooks.sh
- name: Vet and test
shell: bash
run: |

View File

@ -247,7 +247,7 @@ func formatToolGuidanceForMode(names []string, skillInstallMode bool) string {
}
if !skillInstallMode && (has("shell_exec") || has("write_sandbox_file")) {
b.WriteString("Session workspace: /workspace. Preserve uploaded originals in /workspace/input. " +
"/workspace/output is the only directory collected for download, " +
skills.ArtifactOutputDir() + " is the only directory collected for download, " +
"so it takes finished deliverables only; " +
"keep drafts and intermediate files in another directory under /workspace. " +
"Commands start from their specified working directory on every call. " +
@ -289,6 +289,15 @@ func sandboxArtifactReferenceGuidance() string {
var builder strings.Builder
builder.WriteString(" - Include key generated deliverables in your final answer as ")
builder.WriteString("`![description](sandbox:<file name>)` using the exact file name and no directory path\n")
builder.WriteString(" - Copy the exact links supplied in the tool result's appended Output files list. ")
builder.WriteString("Each list covers that call's changes; earlier supplied links remain usable. ")
builder.WriteString("A path or filename in stdout/stderr (including ls output) is not a user-visible file link. ")
builder.WriteString("Never construct sandbox: links from it.\n")
builder.WriteString(" - Files outside the output directory, including /tmp/task/previews, " +
"are internal working files. ")
builder.WriteString("Rendering pages for your own layout checks does not publish them to the user. ")
builder.WriteString("If the user requests those previews, copy the requested files into the output directory ")
builder.WriteString("and use the output links returned by the tool.\n")
builder.WriteString(" - Images render inline; charts, tables, and documents ")
builder.WriteString("render as a card the user clicks to preview\n")
builder.WriteString(" - Never reference a sandbox path (`/workspace/output/...`) ")

View File

@ -17,6 +17,9 @@ func TestToolGuidanceUsesActualCapabilities(t *testing.T) {
require.Contains(t, shell, "shell_exec(skill_name=")
require.Contains(t, shell, "/workspace/output")
require.Contains(t, shell, "sandbox:<file name>")
require.Contains(t, shell, "Copy the exact links supplied in the tool result's appended Output files list")
require.Contains(t, shell, "including /tmp/task/previews, are internal working files")
require.Contains(t, shell, "Rendering pages for your own layout checks does not publish them")
require.Contains(t, shell, "translate execute_skill_script")
require.NotContains(t, formatToolGuidance([]string{"knowledge_search"}), "/workspace")
require.NotContains(t, formatToolGuidance([]string{"read_file"}), "shell_exec")
@ -26,3 +29,10 @@ func TestToolGuidanceUsesActualCapabilities(t *testing.T) {
require.NotContains(t, shell, "Browser source:")
require.Contains(t, formatToolGuidance([]string{"local_browser"}), "requires no shell command")
}
func TestArtifactGuidanceUsesConfiguredOutputDirectory(t *testing.T) {
t.Setenv("WEKNORA_SKILL_OUTPUT_DIR", "/workspace/deliverables")
guidance := formatToolGuidance([]string{"shell_exec", "read_file"})
require.Contains(t, guidance, "/workspace/deliverables is the only directory collected for download")
require.NotContains(t, guidance, "/workspace/output is the only directory collected")
}

View File

@ -49,7 +49,10 @@ func changedOutputLinks(before, after map[string]sandbox.RemoteDirEntry) []strin
}
func sandboxOutputLinks(paths ...string) []string {
var links []string
// A non-nil empty list means inspection completed without finding output
// links. Keep it distinct from nil (inspection unavailable or failed) so the
// next model turn can distinguish stdout filenames from deliverables.
links := []string{}
bytes := 0
for _, filePath := range paths {
filePath = path.Clean(filePath)

View File

@ -7,6 +7,7 @@ import (
"testing"
"time"
"github.com/Tencent/WeKnora/internal/modelcontext"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
@ -70,6 +71,7 @@ func TestShellOutputLinksOmitUnverifiedOutputs(t *testing.T) {
result, err := NewShellExecTool(executor, nil).Execute(shellExecTestContext(), json.RawMessage(`{"command":"python3 generate.py"}`))
require.NoError(t, err)
require.Empty(t, result.OutputFiles)
require.Nil(t, result.OutputFiles, "failed inspection must not claim that no output files were found")
require.Equal(t, 1, executor.calls)
})
t.Run("failed command", func(t *testing.T) {
@ -96,9 +98,40 @@ func TestShellOutputLinksOmitUnverifiedOutputs(t *testing.T) {
})
}
func TestShellPreviewListingDoesNotBecomeDownloadLinks(t *testing.T) {
t.Setenv("WEKNORA_SKILL_OUTPUT_DIR", "/workspace/output")
doc := sandbox.RemoteDirEntry{Path: "/workspace/output/report.docx", Type: sandbox.RemoteEntryFile, Size: 100}
executor := &outputLinkExecutor{
fakeShellExecutor: fakeShellExecutor{result: &sandbox.ExecuteResult{
Stdout: "page-1.png\npage-2.png\npage-3.png\npage-4.png\n",
}},
before: []sandbox.RemoteDirEntry{doc},
after: []sandbox.RemoteDirEntry{doc},
}
result, err := NewShellExecTool(executor, nil).Execute(
shellExecTestContext(), json.RawMessage(`{"command":"ls /tmp/task/previews/"}`),
)
require.NoError(t, err)
require.True(t, result.Success)
require.Empty(t, result.OutputFiles)
require.NotNil(t, result.OutputFiles, "a completed inspection should explicitly report no output changes")
registry := modelcontext.NewRegistry(true)
modelOutput := registry.ModelToolResultForTool(ToolShellExec, result)
require.Contains(t, modelOutput, "page-1.png", "preserve stdout for the model to inspect")
require.Contains(t, modelOutput, "Output files: none identified by this call.")
require.NotContains(t, modelOutput, "sandbox:")
}
func TestOutputLinksEscapeNamesAndStayInsideOutputDirectory(t *testing.T) {
t.Setenv("WEKNORA_SKILL_OUTPUT_DIR", "/workspace/output")
links := sandboxOutputLinks("/workspace/output/report [1](final).pdf", "/workspace/script.py", "/workspace/output/../input/a.pdf")
links := sandboxOutputLinks(
"/workspace/output/report [1](final).pdf",
"/workspace/script.py",
"/workspace/output/../input/a.pdf",
"/tmp/task/previews/page-1.png",
"/workspace/output-previews/page-1.png",
"/workspace/output/../../tmp/task/previews/page-1.png",
)
require.Equal(t, []string{"sandbox:report%20%5B1%5D%28final%29.pdf"}, links)
require.Equal(t, []string{"sandbox:比赛信息.pptx"}, sandboxOutputLinks("/workspace/output/比赛信息.pptx"))
}

View File

@ -7,14 +7,14 @@ import (
"strings"
"github.com/Tencent/WeKnora/internal/agent/skills"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/utils"
)
// ReadFileTool exposes one read operation over capability-scoped sources.
// Skill resources use the manager's allowlist and bundle loader, never an
// arbitrary host path. Workspace files retain the sandbox reader's guards.
// arbitrary host path. Filesystem paths are resolved only inside the current
// session's sandbox and retain its file type, size, and output limits.
type ReadFileTool struct {
BaseTool
webPages WebPageSource
@ -24,7 +24,7 @@ type ReadFileTool struct {
}
type ReadFileInput struct {
Path string `json:"path" jsonschema:"Workspace path, skill:// resource, or saved web:// page"`
Path string `json:"path" jsonschema:"Path inside the current session sandbox (relative to /workspace), skill:// resource, or saved web:// page"` //nolint:lll // JSON schema tags must remain on one line.
LineOffset int `json:"line_offset,omitempty" jsonschema:"Web only: character offset within a long line"`
Offset int `json:"offset,omitempty" jsonschema:"1-based line number; continue at next_offset"`
Limit int `json:"limit,omitempty" jsonschema:"Maximum lines to return; defaults to 2000."`
@ -62,7 +62,9 @@ func (t *ReadFileTool) updateDescription() {
"as offset and line_offset to continue without a shell.")
}
if t.workspace != nil {
scopes = append(scopes, "Workspace files: absolute paths under /workspace or relative paths from /workspace. Known paths can be read directly.")
scopes = append(scopes, "Sandbox files: absolute paths inside the current session's sandbox, including /tmp; "+
"relative paths resolve from /workspace. "+
"This does not read host files or publish files as user-visible artifacts.")
}
if t.skills != nil && t.skills.IsEnabled() {
scopes = append(scopes, "Skill resources: skill://<name>/SKILL.md loads the allowed skill's instructions, file list and execution guidance; skill://<name>/<relative-file> reads a bundled resource. These are package resources, not shell paths or arbitrary host files.")
@ -77,7 +79,10 @@ func (t *ReadFileTool) Execute(ctx context.Context, args json.RawMessage) (*type
}
input.Path = strings.TrimSpace(input.Path)
if input.Path == "" {
return &types.ToolResult{Success: false, Error: "path is required; use a known workspace path or a skill resource from the available skills list"}, nil
return &types.ToolResult{
Success: false,
Error: "path is required; use a known sandbox path or a skill resource from the available skills list",
}, nil
}
if strings.HasPrefix(input.Path, "web://") {
if t.webPages == nil {
@ -92,10 +97,11 @@ func (t *ReadFileTool) Execute(ctx context.Context, args json.RawMessage) (*type
return t.readSkillResource(ctx, input), nil
}
if t.workspace == nil {
return &types.ToolResult{Success: false, Error: "workspace file access is unavailable; only listed skill resources can be read"}, nil
}
if _, ok := matchingInspectableRoot(sandbox.ResolveWorkspacePath(input.Path)); !ok {
return &types.ToolResult{Success: false, Error: "path is outside that scope: file access is limited to /workspace and listed skill:// resources; use the skill resource address from the available skills list to read its package"}, nil
return &types.ToolResult{
Success: false,
Error: "sandbox file access is unavailable; " +
"only listed skill resources or available saved web:// pages can be read",
}, nil
}
return t.workspace.read(ctx, input)
}

View File

@ -60,12 +60,21 @@ func TestReadFileCombinesSourcesWithoutGrantingHostAccess(t *testing.T) {
result = read("skill://allowed/guide.txt")
require.True(t, result.Success)
require.Contains(t, result.Output, "bundled guide")
for _, address := range []string{outside, "skill://other/SKILL.md", "skill://unknown/SKILL.md", "skill://allowed/../other/SKILL.md", "skill://allowed//guide.txt", "skill://allowed/link.txt"} {
result = read(outside)
require.True(t, result.Success)
require.Equal(t, outside, source.readPath)
require.Contains(t, result.Output, "workspace",
"absolute paths must read sandbox data, not the host file at that path")
require.NotContains(t, result.Output, "host secret")
for _, address := range []string{
"skill://other/SKILL.md", "skill://unknown/SKILL.md", "skill://allowed/../other/SKILL.md",
"skill://allowed//guide.txt", "skill://allowed/link.txt",
} {
result := read(address)
require.False(t, result.Success, address)
require.NotContains(t, result.Output, "host secret")
}
require.Equal(t, 1, source.readCalls, "skill and invalid paths must never touch workspace storage")
require.Equal(t, 2, source.readCalls, "skill and invalid skill paths must never touch sandbox storage")
}
func TestReadFileSkillPagesPreserveEveryLineAndSuppressBinary(t *testing.T) {

View File

@ -6,7 +6,7 @@
// regenerate the whole file — that burns tokens and often truncates.
//
// Design notes:
// - Same writable roots as write_sandbox_file: /workspace except
// - Same writable scope as write_sandbox_file: session sandbox except
// /workspace/input.
// - One input shape: every change is an entry in edits[]. Each entry resolves
// against the original content, so a batch is order-independent and
@ -47,7 +47,8 @@ type SandboxFileEditor interface {
var editSandboxFileTool = BaseTool{
name: ToolEditSandboxFile,
description: `Apply exact text replacements to an existing text file under /workspace, excluding /workspace/input.
description: `Apply exact text replacements to an existing text file inside the session sandbox,
excluding /workspace/input.
Read the relevant content first. Send edits as an array, even for one replacement. Every old_string matches the original file, must be unique unless replace_all=true, and must not overlap another edit. Include enough surrounding text to identify the intended occurrence.
All replacements are validated before writing; a failed match leaves the file unchanged. The result includes a diff. Use write_sandbox_file for new files.`,
schema: utils.GenerateSchema[EditSandboxFileInput](),
@ -95,7 +96,7 @@ func (l *sandboxEditList) UnmarshalJSON(data []byte) error {
// attaches to. Every replacement goes in edits[], and a single-element array is
// the ordinary way to change one thing.
type EditSandboxFileInput struct {
Path string `json:"path" jsonschema:"Absolute or /workspace-relative sandbox path of an existing text file under /workspace (not /workspace/input)."` //nolint:lll // one-line struct tag
Path string `json:"path" jsonschema:"Absolute or /workspace-relative sandbox path of an existing text file (not /workspace/input)."` //nolint:lll // one-line struct tag
Edits sandboxEditList `json:"edits" jsonschema:"Replacements to apply, as an array even for a single change. Each old_string is matched against the original file, not against the result of earlier edits, so they must not overlap. Send every change to one file in one call rather than calling the tool repeatedly."` //nolint:lll // one-line struct tag
}
@ -136,7 +137,7 @@ func (t *EditSandboxFileTool) Execute(ctx context.Context, args json.RawMessage)
if trimmed == "" {
return &types.ToolResult{
Success: false,
Error: "path is required; edit a file under /workspace (not /workspace/input)",
Error: "path is required; edit a file inside the session sandbox (not /workspace/input)",
}, nil
}

View File

@ -9,9 +9,8 @@
// - 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 `/workspace`,
// the session's own tree — the same scope write_sandbox_file may
// create in. Omitting `path` lists the artifact output dir
// - Paths are inside the current session's sandbox. Relative paths resolve
// from /workspace. 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
@ -26,7 +25,6 @@ import (
"context"
"encoding/json"
"fmt"
"path"
"sort"
"strings"
"time"
@ -62,17 +60,20 @@ const (
// Tool schema
var listSandboxFilesTool = BaseTool{
name: ToolListSandboxFiles,
description: `List files under /workspace when no shell executor is available. Omitted path lists the artifact output directory. Use known paths directly with read_file; list only to discover unknown files. Results are bounded by max_entries. An unprovisioned session returns an empty listing.`,
schema: utils.GenerateSchema[ListSandboxFilesInput](),
name: ToolListSandboxFiles,
description: `List files inside the current session's sandbox when no shell executor is available.
Relative paths resolve from /workspace; omitted path lists the artifact output directory.
Use known paths directly with read_file; list only to discover unknown files.
Results are bounded by max_entries. An unprovisioned session returns an empty listing.`,
schema: utils.GenerateSchema[ListSandboxFilesInput](),
}
// ListSandboxFilesInput defines the input parameters for list_sandbox_files.
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
// /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
// the tool falls back to skills.ArtifactOutputDir(). Relative paths resolve
// from /workspace inside the current session sandbox.
Path string `json:"path,omitempty" jsonschema:"Optional absolute or /workspace-relative sandbox path to list. 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."`
@ -136,10 +137,7 @@ func (t *ListSandboxFilesTool) Execute(ctx context.Context, args json.RawMessage
}
rootDir, ok := matchingInspectableRoot(targetDir)
if !ok {
return &types.ToolResult{
Success: false,
Error: inspectablePathError(input.Path),
}, nil
rootDir = "/"
}
maxEntries := input.MaxEntries
@ -247,15 +245,8 @@ func resolveSessionID(ctx context.Context) string {
return ""
}
// sandboxInspectableRoots is the allowlist for list_sandbox_files and
// read_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
// sandboxInspectableRoots labels familiar workspace paths in file metadata.
// It is not a read/list allowlist. Ordered most specific first, the root names the
// artifact or attachment tree when the path is inside one.
func sandboxInspectableRoots() []string {
return []string{
@ -265,23 +256,7 @@ func sandboxInspectableRoots() []string {
}
}
func inspectableRootsDescription() string {
return sandbox.SessionWorkspaceRoot
}
// inspectablePathError explains a refused list/read path. Skill image
// paths are the common miss: the model sees /opt/weknora/tenant/skills/<name>
// in read_file's environment section and retries with this tool or ls.
func inspectablePathError(requested string) string {
base := fmt.Sprintf("this tool only lists/reads /workspace. path %q is outside that scope", requested)
name, inImage := sandbox.SkillNameFromImagePath(path.Clean(requested))
if inImage && name != "" {
return base + fmt.Sprintf(". Use read_file(path=%q) for package instructions and file discovery. Do not ls the whole installed dependency tree.", "skill://"+name+"/SKILL.md")
}
return base + ". Use read_file with a listed skill:// resource for skill packages."
}
// matchingInspectableRoot returns the allowlisted root that contains
// matchingInspectableRoot returns the named workspace root that contains
// clean, or ("", false) when the path sits outside every root.
func matchingInspectableRoot(clean string) (string, bool) {
for _, root := range sandboxInspectableRoots() {
@ -293,8 +268,8 @@ func matchingInspectableRoot(clean string) (string, bool) {
}
// isUnderRoot reports whether clean sits at or underneath root. Both
// arguments must already be cleaned. The list/read tools use this as a
// scope check so they stay on artifacts and attachments; it is not a
// arguments must already be cleaned. Readers use this to label workspace roots;
// writers also use it to preserve attachment write protection. It is not a
// privilege boundary (shell_exec can already reach the same files).
func isUnderRoot(clean, root string) bool {
if clean == root {

View File

@ -6,7 +6,7 @@
//
// Design notes:
// - Session-scoped: the sandbox is resolved from ToolExecContext.SessionID.
// - Path guardrail: writes sit under /workspace and never under
// - Path guardrail: writes stay inside the session sandbox and never under
// /workspace/input (staged attachments are the user's, not ours).
// /workspace/output is what gets collected for download, so the
// description reserves it for finished deliverables and sends scratch
@ -96,7 +96,8 @@ type SandboxFileSink interface {
// writeSandboxFileDescription carries one %s, filled with the size guidance
// derived from the round's completion-token budget.
const writeSandboxFileDescription = `Create, overwrite, or append a text file under /workspace, excluding /workspace/input.
const writeSandboxFileDescription = `Create, overwrite, or append a text file inside the session sandbox,
excluding /workspace/input.
/workspace/output is collected for download, so it holds finished deliverables only; put drafts, scratch and
intermediate files in any other directory under /workspace. Send both path and content (path first).
Use edit_sandbox_file for small changes to an existing file. File content does not pass through shell quoting.
@ -110,9 +111,9 @@ Binary content is not accepted. The result reports the absolute path and total s
// depends on the agent's per-round token budget and is stated in the tool
// description, which is built per session.
type WriteSandboxFileInput struct {
Path string `json:"path" jsonschema:"Absolute or /workspace-relative sandbox path to write. Must sit under /workspace and must not sit under /workspace/input. Use /workspace/output for finished deliverables only; intermediate files belong elsewhere under /workspace."` //nolint:lll // JSON schema tags must remain on one line.
Content string `json:"content" jsonschema:"Text to write. In overwrite mode this is the full file; in append mode it is only the next chunk. Keep near the per-call size stated in the tool description so the response is not cut off. Do not send binary bytes."` //nolint:lll // one-line struct tag
Mode string `json:"mode,omitempty" jsonschema:"How to apply content: 'overwrite' (default) replaces the file, 'append' adds to the end of an existing file. Use append to build a large file across several calls."` //nolint:lll // one-line struct tag
Path string `json:"path" jsonschema:"Absolute or /workspace-relative sandbox path to write, excluding /workspace/input. Use the artifact output directory for finished deliverables only; intermediate files belong elsewhere."` //nolint:lll // JSON schema tags must remain on one line.
Content string `json:"content" jsonschema:"Text to write. In overwrite mode this is the full file; in append mode it is only the next chunk. Keep near the per-call size stated in the tool description so the response is not cut off. Do not send binary bytes."` //nolint:lll // one-line struct tag
Mode string `json:"mode,omitempty" jsonschema:"How to apply content: 'overwrite' (default) replaces the file, 'append' adds to the end of an existing file. Use append to build a large file across several calls."` //nolint:lll // one-line struct tag
}
// WriteSandboxFileTool writes a text file into the session sandbox.
@ -376,21 +377,21 @@ func (t *WriteSandboxFileTool) Cleanup(ctx context.Context) error {
}
// workspaceWriteScopeError explains a refused write/edit path. This is a
// tool-scope convention (attachments stay out of these tools; scripts go
// under /workspace), not a privilege check — shell_exec can already write
// tool-scope convention (attachments stay out of these tools), not a privilege
// check — shell_exec can already write
// the same session sandbox.
func workspaceWriteScopeError(requested string) string {
return fmt.Sprintf(
"this tool only writes files under %s (not under %s, and not the directory roots themselves). path %q is outside that scope; use shell_exec for other locations",
sandbox.SessionWorkspaceRoot, sandbox.SessionInputRoot, requested,
"path %q is outside that scope: write a file inside the session sandbox, "+
"not a directory root or a path under read-only %s",
requested, sandbox.SessionInputRoot,
)
}
// matchingWritableRoot returns the workspace root that contains clean, or
// ("", false) when the path is outside /workspace, is /workspace itself, or
// sits under the read-only attachment tree.
// matchingWritableRoot labels sandbox writes while excluding directory roots
// and the read-only attachment tree.
func matchingWritableRoot(clean string) (string, bool) {
if !isUnderRoot(clean, sandbox.SessionWorkspaceRoot) ||
if !path.IsAbs(clean) || clean == "/" ||
clean == sandbox.SessionWorkspaceRoot ||
clean == sandbox.SessionOutputRoot ||
isUnderRoot(clean, sandbox.SessionInputRoot) {
@ -399,5 +400,8 @@ func matchingWritableRoot(clean string) (string, bool) {
if isUnderRoot(clean, sandbox.SessionOutputRoot) {
return sandbox.SessionOutputRoot, true
}
return sandbox.SessionWorkspaceRoot, true
if isUnderRoot(clean, sandbox.SessionWorkspaceRoot) {
return sandbox.SessionWorkspaceRoot, true
}
return "/", true
}

View File

@ -134,7 +134,7 @@ func TestWriteSandboxFileRefusesSessionInput(t *testing.T) {
func TestWriteSandboxFileRefusesDirectoryPaths(t *testing.T) {
sink := &fakeSandboxFileSink{}
for _, p := range []string{"/workspace", "/workspace/output", "/workspace/input"} {
for _, p := range []string{"/", "/workspace", "/workspace/output", "/workspace/input"} {
result, err := NewWriteSandboxFileTool(sink, 0).Execute(
sandboxFileTestContext(),
mustWriteSandboxArgs(p, "nope"),
@ -145,6 +145,34 @@ func TestWriteSandboxFileRefusesDirectoryPaths(t *testing.T) {
assert.Zero(t, sink.calls)
}
func TestSandboxWriteAppendAndEditTemporaryFiles(t *testing.T) {
sink := &fakeSandboxFileSink{}
writer := NewWriteSandboxFileTool(sink, 0)
for _, tc := range []struct{ mode, content string }{
{"overwrite", "hello"},
{"append", " world"},
} {
args, err := json.Marshal(WriteSandboxFileInput{
Path: "../tmp/task/check.txt", Content: tc.content, Mode: tc.mode,
})
require.NoError(t, err)
result, err := writer.Execute(sandboxFileTestContext(), args)
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.Equal(t, "/tmp/task/check.txt", sink.path)
require.Equal(t, "/", result.Data["root"])
require.Empty(t, result.OutputFiles, "temporary files are not downloadable artifacts")
}
require.Equal(t, "hello world", string(sink.files["/tmp/task/check.txt"]))
editor := &fakeSandboxFileEditor{files: sink.files}
result, err := NewEditSandboxFileTool(editor).Execute(sandboxFileTestContext(),
json.RawMessage(`{"path":"/tmp/task/check.txt","edits":[{"old_string":"world","new_string":"sandbox"}]}`))
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.Equal(t, "hello sandbox", string(editor.files["/tmp/task/check.txt"]))
require.Empty(t, result.OutputFiles)
}
func TestWriteSandboxFileRefusesBinaryAndOversize(t *testing.T) {
sink := &fakeSandboxFileSink{}

View File

@ -130,7 +130,8 @@ var shellExecTool = BaseTool{
name: ToolShellExec,
description: `Execute a command in the current session's isolated sandbox as root.
The sandbox belongs to this session alone; nothing here runs on the host.
- CWD defaults to /workspace on every call; cd does not persist. work_dir selects another directory under /workspace and missing directories are created as the same user.
- CWD defaults to /workspace on every call; cd does not persist.
work_dir selects any directory inside the session sandbox; missing directories are created as the same user.
- Use ls/find to discover files, grep/awk to search, and cat/head/tail/sed to inspect text. Read known paths directly; no mandatory discovery call.
- Use write_sandbox_file for scripts or large text; edit_sandbox_file for precise changes. Commands are limited to 8192 bytes. Execution is synchronous (no nohup or trailing &).
- skill_name selects a listed skill for this call. Installed skills use their Python virtualenv and Node modules;
@ -148,7 +149,7 @@ The sandbox belongs to this session alone; nothing here runs on the host.
Changes live and die with this session.
- Non-zero exit_code is a command result: inspect stderr before deciding whether a corrected call is useful. Transport failures/timeouts are tool failures. Changing tools does not change permissions; do not repeat a denied operation through another tool.
- stdout/stderr have independent byte limits, preserving head and tail when truncated. Full output is not automatically saved; redirect verbose commands to a workspace log when it must be retained. Binary bytes are suppressed.
- Reference collected deliverables as ![description](sandbox:<file name>) using the exact filename.`,
- Use ![description](sandbox:<file name>) with exact links from Output files, never stdout or temporary paths.`,
schema: utils.GenerateSchema[ShellExecInput](),
}
@ -220,8 +221,8 @@ func (e installShellExecutor) ExecShellCommand(
type ShellExecTool struct {
BaseTool
executor SandboxCommandExecutor
// workDirRoots are the directories work_dir may point inside. Ordinary
// sessions get /workspace only; install mode adds the skills image root.
// workDirRoots restrict install-mode working directories. Ordinary
// sessions may work anywhere inside their own sandbox.
workDirRoots []string
// defaultWorkDir is where a call that omits work_dir lands. Empty means
// /workspace, which is right for an ordinary session and wrong for an
@ -263,7 +264,7 @@ func NewShellExecTool(executor SandboxCommandExecutor, envResolver skills.SkillE
BaseTool: shellExecTool,
executor: executor,
envResolver: envResolver,
workDirRoots: []string{defaultShellExecWorkDir},
workDirRoots: []string{"/"},
}
}
@ -692,11 +693,11 @@ func (t *ShellExecTool) effectiveDefaultWorkDir() string {
return t.defaultWorkDir
}
// allowedWorkDirRoots defaults to /workspace so a zero-value tool (or one
// built before install mode existed) keeps the ordinary contract.
// allowedWorkDirRoots allows any sandbox directory for ordinary sessions.
// Install-mode tools provide an explicit scope.
func (t *ShellExecTool) allowedWorkDirRoots() []string {
if len(t.workDirRoots) == 0 {
return []string{defaultShellExecWorkDir}
return []string{"/"}
}
return t.workDirRoots
}

View File

@ -49,18 +49,18 @@ func shellExecTestContext() context.Context {
return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "session-1"})
}
func TestShellExecRejectsWorkDirOutsideWorkspace(t *testing.T) {
func TestShellExecAllowsWorkDirOutsideWorkspace(t *testing.T) {
executor := &fakeShellExecutor{}
tool := NewShellExecTool(executor, nil)
result, err := tool.Execute(shellExecTestContext(), json.RawMessage(
`{"command":"pwd","work_dir":"/etc"}`,
`{"command":"pwd","work_dir":"../tmp/task"}`,
))
require.NoError(t, err)
require.False(t, result.Success)
require.Contains(t, result.Error, `work_dir "/etc" is outside the allowed sandbox roots /workspace`)
assert.Equal(t, time.Duration(0), executor.timeout)
require.True(t, result.Success, result.Error)
require.Equal(t, "/tmp/task", executor.workDir)
require.Equal(t, 1, executor.calls)
}
func TestShellExecTimeoutHonorsAndCapsRequestedValue(t *testing.T) {

View File

@ -1,16 +1,15 @@
// Package tools — read_file.
//
// Read-only tool that lets the LLM read a file under the session's
// inspectable sandbox directories. Known paths can be read directly;
// Read-only tool that lets the LLM read a file inside the session's
// sandbox. Known paths can be read directly;
// directory discovery is optional.
//
// Design notes:
// - 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 /workspace, matching
// what this session may write. Skills that need to peek outside it
// should print via stdout.
// - Absolute paths are sandbox-local; relative paths resolve from /workspace.
// Reading a file does not make it a downloadable artifact.
// - Paginated reads: a page is bounded by a line count, a byte budget, and
// the registry's rune budget, and a partial page ends with the offset to
// continue from. Files over 8 MiB are never downloaded; the model gets
@ -55,7 +54,7 @@ const (
)
// workspaceFileReader is a private source adapter for read_file, not a
// separately registered tool. It owns the workspace cache and path guards.
// separately registered tool. It owns the sandbox file cache and read limits.
type workspaceFileReader struct {
source SandboxFileSource
mu sync.Mutex
@ -131,7 +130,7 @@ func (t *workspaceFileReader) read(ctx context.Context, input ReadFileInput) (*t
if trimmed == "" {
return &types.ToolResult{
Success: false,
Error: "path is required; use a known file path under /workspace",
Error: "path is required; use a known file path inside the session sandbox",
}, nil
}
@ -139,20 +138,17 @@ func (t *workspaceFileReader) read(ctx context.Context, input ReadFileInput) (*t
if sessionID == "" {
return &types.ToolResult{
Success: false,
Error: "no session ID in context; workspace file reads must run inside an agent turn",
Error: "no session ID in context; sandbox file reads must run inside an agent turn",
}, nil
}
// Enforce that the path sits underneath an inspectable root. This
// mirrors list_sandbox_files so the LLM sees a consistent reachable
// surface covering both skill output and staged attachments.
// The source binds reads to the current session's sandbox. Preserve the
// familiar workspace roots in metadata, without restricting readable paths
// to them: temporary files and installed resources may live elsewhere.
clean := sandbox.ResolveWorkspacePath(trimmed)
rootDir, ok := matchingInspectableRoot(clean)
if !ok {
return &types.ToolResult{
Success: false,
Error: inspectablePathError(input.Path),
}, nil
rootDir = "/"
}
stat, err := t.source.StatSessionFile(ctx, sessionID, clean)
@ -176,23 +172,13 @@ func (t *workspaceFileReader) read(ctx context.Context, input ReadFileInput) (*t
Error: fmt.Sprintf("path is a directory, not a file: %s", clean),
}, nil
}
// The directory guard above is a string prefix test, so it cannot tell that
// a symlink under the output directory points somewhere else entirely. The
// backends stat the final component without following it, so this refuses a
// path that names a link.
//
// A link in the MIDDLE of the path is still resolved by the kernel and is
// not caught here. That leaves the artifact-directory convention evadable,
// but not the privilege boundary: the read runs as the sandbox account, so
// it can only return what that account could already have read via
// shell_exec.
// Keep reads limited to regular files. Backends stat the final component
// without following symlinks; other filesystem permissions remain enforced
// by the sandbox backend.
if stat.Type != sandbox.RemoteEntryFile {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf(
"path is not a regular file: %s; only files under %s can be read",
clean, inspectableRootsDescription(),
),
Error: fmt.Sprintf("path is not a regular file: %s", clean),
}, nil
}
if stat.Size > maxReadSandboxDownloadBytes {

View File

@ -15,14 +15,18 @@ import (
)
type fakeSandboxFileSource struct {
stat *sandbox.RemoteStatEntry
statErr error
data []byte
readErr error
entries []sandbox.RemoteDirEntry
statCalls int
readCalls int
listedDir string
stat *sandbox.RemoteStatEntry
statErr error
data []byte
readErr error
entries []sandbox.RemoteDirEntry
statCalls int
readCalls int
listedDir string
statPath string
readPath string
statSession string
readSession string
}
func (f *fakeSandboxFileSource) ListSessionFiles(_ context.Context, _, dir string) ([]sandbox.RemoteDirEntry, error) {
@ -30,13 +34,17 @@ func (f *fakeSandboxFileSource) ListSessionFiles(_ context.Context, _, dir strin
return f.entries, nil
}
func (f *fakeSandboxFileSource) StatSessionFile(context.Context, string, string) (*sandbox.RemoteStatEntry, error) {
func (f *fakeSandboxFileSource) StatSessionFile(
_ context.Context, sessionID, path string,
) (*sandbox.RemoteStatEntry, error) {
f.statCalls++
f.statSession, f.statPath = sessionID, path
return f.stat, f.statErr
}
func (f *fakeSandboxFileSource) ReadSessionFile(context.Context, string, string) ([]byte, error) {
func (f *fakeSandboxFileSource) ReadSessionFile(_ context.Context, sessionID, path string) ([]byte, error) {
f.readCalls++
f.readSession, f.readPath = sessionID, path
return f.data, f.readErr
}
@ -366,8 +374,7 @@ func TestReadFileWorkspaceReturnsSmallTextOnlyInOutput(t *testing.T) {
//
// The path here names the link itself, which is the case this actually covers.
// A link used as an intermediate component is resolved by the kernel and still
// stats as a regular file; see the note in Execute for why that is a convention
// leak rather than a privilege one.
// stats as a regular file. Both cases remain inside the session's sandbox.
func TestReadFileWorkspaceRefusesNonRegularFile(t *testing.T) {
source := &fakeSandboxFileSource{
stat: &sandbox.RemoteStatEntry{
@ -482,27 +489,32 @@ func TestReadFileWorkspaceAllowsWorkspaceScratchFile(t *testing.T) {
assert.Equal(t, sandbox.SessionWorkspaceRoot, result.Data["root"])
}
func TestReadFileWorkspaceRefusesOutsideInspectableRoots(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",
"/home/user/.ssh/id_rsa",
"/opt/weknora/tenant/skills/pdf/SKILL.md",
func TestReadFileAllowsPathsOutsideWorkspaceInCurrentSandbox(t *testing.T) {
for _, tc := range []struct{ input, want string }{
{"/tmp/task/previews/check.txt", "/tmp/task/previews/check.txt"},
{"/etc/os-release", "/etc/os-release"},
{"/home/user/config.txt", "/home/user/config.txt"},
{"/opt/weknora/tenant/skills/pdf/SKILL.md", "/opt/weknora/tenant/skills/pdf/SKILL.md"},
{"../tmp/task/./check.txt", "/tmp/task/check.txt"},
} {
result, err := NewReadFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"`+path+`"}`),
)
require.NoError(t, err, path)
require.False(t, result.Success, path)
assert.Contains(t, result.Error, "outside that scope", path)
t.Run(tc.input, func(t *testing.T) {
source := &fakeSandboxFileSource{
data: []byte("sandbox text"),
stat: &sandbox.RemoteStatEntry{Type: sandbox.RemoteEntryFile, Size: 12},
}
result, err := NewReadFileTool(source).Execute(sandboxFileTestContext(),
json.RawMessage(`{"path":"`+tc.input+`"}`))
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.Equal(t, tc.want, source.statPath)
require.Equal(t, tc.want, source.readPath)
require.Equal(t, "session-1", source.statSession)
require.Equal(t, "session-1", source.readSession)
require.Equal(t, "/", result.Data["root"])
require.Contains(t, result.Output, "sandbox text")
require.Nil(t, result.OutputFiles, "reading a temporary file must not publish it")
})
}
assert.Zero(t, source.readCalls)
assert.Zero(t, source.statCalls)
}
func TestListSandboxFilesDefaultsToOutput(t *testing.T) {
@ -540,45 +552,43 @@ func TestListSandboxFilesAllowsSessionInput(t *testing.T) {
assert.Equal(t, 1, result.Data["count"])
}
func TestListSandboxFilesRefusesOutsideInspectableRoots(t *testing.T) {
func TestListSandboxFilesAllowsOutsideWorkspace(t *testing.T) {
source := &fakeSandboxFileSource{}
result, err := NewListSandboxFilesTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/etc"}`),
json.RawMessage(`{"path":"../tmp/task/previews"}`),
)
require.NoError(t, err)
require.False(t, result.Success)
assert.Contains(t, result.Error, "outside that scope")
assert.Empty(t, source.listedDir)
require.True(t, result.Success, result.Error)
assert.Equal(t, "/tmp/task/previews", source.listedDir)
assert.Equal(t, "/", result.Data["root"])
}
func TestListSandboxFilesRedirectsSkillImagePaths(t *testing.T) {
func TestListSandboxFilesAllowsSandboxSkillImagePaths(t *testing.T) {
source := &fakeSandboxFileSource{}
result, err := NewListSandboxFilesTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/opt/weknora/tenant/skills/ppt-generator"}`),
)
require.NoError(t, err)
require.False(t, result.Success)
assert.Contains(t, result.Error, "outside that scope")
assert.Contains(t, result.Error, `read_file(path="skill://ppt-generator/SKILL.md")`)
assert.Contains(t, result.Error, "Do not ls")
assert.Empty(t, source.listedDir)
require.True(t, result.Success, result.Error)
assert.Equal(t, "/opt/weknora/tenant/skills/ppt-generator", source.listedDir)
}
func TestReadFileWorkspaceRedirectsSkillImagePaths(t *testing.T) {
func TestReadFileOutsideWorkspaceStillRequiresSession(t *testing.T) {
source := &fakeSandboxFileSource{
data: []byte("must not be read"),
stat: &sandbox.RemoteStatEntry{Path: "/opt/weknora/tenant/skills/ppt-generator/scripts/generate_ppt.py", Type: sandbox.RemoteEntryFile, Size: 4},
stat: &sandbox.RemoteStatEntry{Type: sandbox.RemoteEntryFile, Size: 4},
}
result, err := NewReadFileTool(source).Execute(
sandboxFileTestContext(),
json.RawMessage(`{"path":"/opt/weknora/tenant/skills/ppt-generator/scripts/generate_ppt.py"}`),
context.Background(),
json.RawMessage(`{"path":"/tmp/task/check.txt"}`),
)
require.NoError(t, err)
require.False(t, result.Success)
assert.Contains(t, result.Error, "skill://")
assert.Contains(t, result.Error, "no session ID")
assert.Zero(t, source.statCalls)
assert.Zero(t, source.readCalls)
}

View File

@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/require"
)
// stubInstallShellExecutor records the options the privileged executor is
// stubInstallShellExecutor records the options the install executor is
// asked for, so a test can prove the difference between the two shell_exec
// wirings rather than merely that one was registered.
type stubInstallShellExecutor struct {
@ -50,37 +50,36 @@ func TestInstallerAgentGetsTheRootShellWithTheSkillsRoot(t *testing.T) {
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.False(t, ordinary.called,
"the installer must not fall through to the unprivileged executor")
"the installer must not fall through to the ordinary executor")
require.Len(t, privileged.calls, 1)
require.True(t, privileged.calls[0].AsRoot)
require.True(t, privileged.calls[0].AllowSkillsRoot)
require.Equal(t, sandbox.SkillsImageRoot+"/sk-1", privileged.calls[0].WorkDir)
}
func TestOrdinaryAgentKeepsTheUnprivilegedShell(t *testing.T) {
privileged := &stubInstallShellExecutor{}
ordinary := &stubShellExecutor{}
mgr := &capableManager{
typ: sandbox.SandboxTypeE2B,
shell: ordinary,
installShell: privileged,
func TestOrdinaryAgentUsesSessionShellForSandboxPaths(t *testing.T) {
for _, workDir := range []string{"", "/tmp/task/previews", sandbox.SkillsImageRoot + "/sk-1"} {
t.Run(workDir, func(t *testing.T) {
installer := &stubInstallShellExecutor{}
ordinary := &stubShellExecutor{}
mgr := &capableManager{
typ: sandbox.SandboxTypeE2B,
shell: ordinary,
installShell: installer,
}
registry := tools.NewToolRegistry()
(&agentService{}).registerSandboxShellTool(context.Background(), registry, mgr, &types.AgentConfig{})
args, err := json.Marshal(tools.ShellExecInput{Command: "ls", WorkDir: workDir})
require.NoError(t, err)
result, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec, args)
require.NoError(t, err)
require.True(t, result.Success, result.Error)
require.True(t, ordinary.called)
require.Empty(t, installer.calls,
"a sandbox path must not switch ordinary calls to the install executor")
})
}
registry := tools.NewToolRegistry()
(&agentService{}).registerSandboxShellTool(context.Background(), registry, mgr, &types.AgentConfig{})
rejected, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec,
json.RawMessage(`{"command":"pip install x","work_dir":"`+sandbox.SkillsImageRoot+`/sk-1"}`))
require.NoError(t, err)
require.False(t, rejected.Success, "an ordinary agent has no business under /opt")
accepted, err := registry.ExecuteTool(installShellToolContext(), tools.ToolShellExec,
json.RawMessage(`{"command":"ls"}`))
require.NoError(t, err)
require.True(t, accepted.Success)
require.True(t, ordinary.called)
require.Empty(t, privileged.calls,
"nothing an ordinary agent can ask for may reach the root executor")
}
func TestInstallModeIsRefusedToEveryAgentButTheInstaller(t *testing.T) {

View File

@ -310,9 +310,12 @@ func (r *Registry) ModelToolResultForTool(toolName string, result *types.ToolRes
}
func outputFilesPrompt(result *types.ToolResult) string {
if result == nil || len(result.OutputFiles) == 0 {
if result == nil || result.OutputFiles == nil {
return ""
}
if len(result.OutputFiles) == 0 {
return "\nOutput files: none identified by this call."
}
return "\nOutput files: `" + strings.Join(result.OutputFiles, "`, `") + "`"
}

View File

@ -61,6 +61,27 @@ func TestOutputFilesAreRenderedOnlyForLiveModelResults(t *testing.T) {
require.Contains(t, registry.ModelToolResultForTool("shell_exec", result), "sandbox:比赛信息.pptx")
}
func TestEmptyOutputInspectionIsExplicitOnlyInLiveModelResults(t *testing.T) {
for _, registry := range []*Registry{NewRegistry(true), nil} {
result := &types.ToolResult{Success: true, Output: "page-1.png", OutputFiles: []string{}}
modelOutput := registry.ModelToolResultForTool("shell_exec", result)
require.Equal(t, "page-1.png\nOutput files: none identified by this call.", modelOutput)
require.NotContains(t, modelOutput, "sandbox:page-1.png")
encoded, err := json.Marshal(result)
require.NoError(t, err)
var restored types.ToolResult
require.NoError(t, json.Unmarshal(encoded, &restored))
require.Equal(t, "page-1.png", registry.ModelToolResultForTool("shell_exec", &restored))
result.Success = false
result.Error = "command timed out"
modelOutput = registry.ModelToolResultForTool("shell_exec", result)
require.Contains(t, modelOutput, "command timed out")
require.Contains(t, modelOutput, "Output files: none identified by this call.")
result.OutputFiles = nil
require.NotContains(t, registry.ModelToolResultForTool("shell_exec", result), "Output files:")
}
}
func TestRegistryAuditsUnresolvedAndPartiallyResolvedToolHandles(t *testing.T) {
registry := NewRegistry(true)
registry.RegisterKnowledgeBase("kb-real")

View File

@ -62,10 +62,9 @@ type SessionFileStore interface {
// session's remote sandbox, provisioning the sandbox on first call.
WriteSessionInputFile(ctx context.Context, sessionID, filePath string, content []byte) error
// WriteSessionWorkspaceFile writes a model-authored file under
// /workspace. /workspace/input stays read-only (attachments); everything
// else under /workspace is accepted so generated scripts do not have to
// travel through shell_exec heredocs.
// WriteSessionWorkspaceFile writes a model-authored file inside the
// current session sandbox. Relative paths resolve from /workspace;
// /workspace/input stays read-only (attachments).
WriteSessionWorkspaceFile(ctx context.Context, sessionID, filePath string, content []byte) error
// WriteSessionWorkspaceFiles writes many workspace files after preparing
@ -93,11 +92,9 @@ type SessionCapabilityProvider interface {
SessionFileStore() SessionFileStore
}
// SessionInstallShellExecutor runs install/maintenance shell commands, which
// need the skills image root. It is a separate interface from
// SessionShellExecutor so reaching outside /workspace is something a caller
// must ask for by name: ordinary chat sessions keep the /workspace-only
// contract even though they already run as root.
// SessionInstallShellExecutor runs install/maintenance shell commands with
// their own bootstrap and working-directory scope. Ordinary shell execution
// stays inside its session sandbox but is not limited to /workspace.
type SessionInstallShellExecutor interface {
ExecShellCommandWithOptions(
ctx context.Context,

View File

@ -527,7 +527,7 @@ func (m *SessionBoundManager) WriteSessionInputFile(
// WriteSessionWorkspaceFile writes a model-authored file into the session's
// remote sandbox, provisioning the sandbox on first call. Paths must sit
// under /workspace and must not land in /workspace/input.
// inside the session sandbox and must not land in /workspace/input.
func (m *SessionBoundManager) WriteSessionWorkspaceFile(
ctx context.Context, sessionID, filePath string, content []byte,
) error {
@ -709,14 +709,14 @@ type ShellExecOptions struct {
Timeout time.Duration
Env map[string]string
// AllowSkillsRoot lets installer calls work inside the skills image root.
// AllowSkillsRoot selects the installer workspace/skills working-directory scope.
// See cleanSessionWorkDir for why the work_dir allowlist is lexical only.
// Never set this from a model-authored tool such as shell_exec.
AllowSkillsRoot bool
// AsRoot forces root and selects the maintenance bootstrap: only WorkDir
// is prepared, without requiring /workspace/input or /workspace/output.
// The default account is already root, but the bootstrap still differs.
// AllowSkillsRoot separately permits a work_dir under the skills image root;
// AllowSkillsRoot separately selects the installer working-directory scope;
// it is not a filesystem boundary for commands running as root.
AsRoot bool
// SkipWorkspacePrep omits prepareSessionDirs. Desktop maintenance
@ -727,8 +727,7 @@ type ShellExecOptions struct {
}
// ExecShellCommand runs a shell one-liner inside the session's persistent
// sandbox. It preserves the shell_exec tool contract: /workspace-only work_dir
// validation and provider default user.
// sandbox. work_dir may name any absolute directory inside that sandbox.
func (m *SessionBoundManager) ExecShellCommand(
ctx context.Context,
sessionID string,
@ -1334,9 +1333,8 @@ func cleanSessionInputPath(filePath string) (string, error) {
)
}
// cleanSessionWorkspaceWritePath keeps model-authored writes inside the
// session workspace and out of the attachment tree. Validation is lexical
// (path.Clean plus prefix checks), matching cleanSessionWorkDir.
// cleanSessionWorkspaceWritePath normalizes model-authored sandbox writes and
// protects staged attachments. The remote session binding isolates the files.
func cleanSessionWorkspaceWritePath(filePath string) (string, error) {
clean := ResolveWorkspacePath(filePath)
if !path.IsAbs(clean) || clean == "." || clean == "/" {
@ -1345,34 +1343,23 @@ func cleanSessionWorkspaceWritePath(filePath string) (string, error) {
if clean == SessionWorkspaceRoot || clean == SessionOutputRoot || clean == SessionInputRoot {
return "", fmt.Errorf("sandbox: workspace write path %q is a directory, not a file", filePath)
}
if !strings.HasPrefix(clean, SessionWorkspaceRoot+"/") {
return "", fmt.Errorf("sandbox: workspace write path %q is outside %s", filePath, SessionWorkspaceRoot)
}
if strings.HasPrefix(clean, SessionInputRoot+"/") {
return "", fmt.Errorf("sandbox: session input %s is read-only", SessionInputRoot)
}
return clean, nil
}
// cleanSessionWorkDir keeps shell_exec inside directories we are willing to let
// an agent work in. Ordinary sessions get /workspace only.
//
// Validation is lexical (path.Clean plus prefix checks): a symlink under an
// allowed root that resolves elsewhere at execution time is not detected and
// that is intentional. The only caller that passes allowSkillsRoot also passes
// AsRoot and runs arbitrary install shell commands, so a symlink would grant
// nothing those commands cannot already reach via cd or absolute paths. For
// ordinary sessions the allowlist is unchanged and its lexical nature is
// pre-existing. The allowlist stops casual wandering and makes intent
// auditable; the real isolation boundary is the remote sandbox itself.
//
// allowSkillsRoot widens it to the skills image root for install/maintenance
// sessions, so the installer agent can set work_dir to the skill directory and
// run ordinary relative commands instead of composing long absolute paths. It
// is a widening, not a removal: everything outside these two roots is still
// refused.
// cleanSessionWorkDir requires an absolute sandbox-local working directory.
// Ordinary calls may work anywhere; the install/maintenance option retains its
// explicit workspace/skills scope. Neither check changes filesystem privileges.
func cleanSessionWorkDir(workDir string, allowSkillsRoot bool) (string, error) {
clean := path.Clean(strings.TrimSpace(workDir))
if !path.IsAbs(clean) {
return "", fmt.Errorf("sandbox: work dir %q must be absolute", workDir)
}
if !allowSkillsRoot {
return clean, nil
}
if clean == SessionWorkspaceRoot || strings.HasPrefix(clean, SessionWorkspaceRoot+"/") {
return clean, nil
}

View File

@ -178,10 +178,10 @@ func TestSessionBoundManagerShellExecRunsAsSandboxUser(t *testing.T) {
require.Equal(t, DefaultSandboxExecUser, shell[0].User)
}
func TestCleanSessionWorkDirRejectsSkillRootByDefault(t *testing.T) {
func TestCleanSessionWorkDirAcceptsSandboxSkillRoot(t *testing.T) {
skillDir := mustSkillDir(t, "sk-1")
_, err := cleanSessionWorkDir(skillDir, false)
require.Error(t, err, "ordinary sessions must stay inside /workspace")
require.NoError(t, err, "ordinary sessions may use any directory in their sandbox")
got, err := cleanSessionWorkDir(skillDir, true)
require.NoError(t, err, "install sessions need to work inside the skills root")
@ -242,16 +242,16 @@ func TestExecShellCommandSkipWorkspacePrepOmitsBootstrap(t *testing.T) {
require.Equal(t, DefaultSandboxExecUser, execs[0].User)
}
func TestExecShellCommandSkipWorkspacePrepStillRejectsWorkDir(t *testing.T) {
func TestExecShellCommandSkipWorkspacePrepStillRejectsRelativeWorkDir(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
mgr, _ := newSessionManagerExecTestHarness(t)
_, err := mgr.ExecShellCommandWithOptions(ctx, "sess-1", "echo hi", ShellExecOptions{
SkipWorkspacePrep: true,
WorkDir: "/etc",
WorkDir: "relative",
})
require.Error(t, err)
require.Contains(t, err.Error(), "outside allowed roots")
require.Contains(t, err.Error(), "must be absolute")
}
func TestExecShellCommandWithoutSkipStillBootstraps(t *testing.T) {
@ -302,14 +302,13 @@ func TestExecShellCommandEmptyWorkDirUsesWorkspace(t *testing.T) {
require.Equal(t, DefaultSandboxExecUser, last.User)
}
func TestExecShellCommandRejectsInvalidWorkDir(t *testing.T) {
func TestExecShellCommandAllowsTemporaryWorkDir(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
mgr, _ := newSessionManagerExecTestHarness(t)
mgr, client := newSessionManagerExecTestHarness(t)
_, err := mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "/etc", time.Second, nil)
require.Error(t, err)
require.Contains(t, err.Error(), "outside allowed roots")
require.Contains(t, err.Error(), SessionWorkspaceRoot)
_, err := mgr.ExecShellCommand(ctx, "sess-1", "echo hi", "/tmp/task", time.Second, nil)
require.NoError(t, err)
require.Equal(t, "/tmp/task", lastExecRequest(t, client).WorkDir)
}
// The manager is what the skill install flow holds, so the path from "the
@ -387,29 +386,36 @@ func TestCleanSessionWorkspaceWritePathAcceptsWorkspaceAndRefusesInput(t *testin
require.Error(t, err)
_, err = cleanSessionWorkspaceWritePath("/workspace/output")
require.Error(t, err)
_, err = cleanSessionWorkspaceWritePath("/etc/passwd")
got, err = cleanSessionWorkspaceWritePath("/tmp/task/check.txt")
require.NoError(t, err)
require.Equal(t, "/tmp/task/check.txt", got)
_, err = cleanSessionWorkspaceWritePath("/tmp/../workspace/input/report.txt")
require.Error(t, err)
got, err = cleanSessionWorkspaceWritePath("relative.py")
require.NoError(t, err)
require.Equal(t, "/workspace/relative.py", got)
}
func TestWriteSessionWorkspaceFileWritesUnderOutput(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
mgr, client := newSessionManagerExecTestHarness(t)
func TestWriteSessionWorkspaceFileWritesSandboxPaths(t *testing.T) {
for _, filePath := range []string{"/workspace/output/generate_ppt.py", "/tmp/task/generate_ppt.py"} {
t.Run(filePath, func(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))
mgr, client := newSessionManagerExecTestHarness(t)
require.NoError(t, mgr.WriteSessionWorkspaceFile(
ctx, "sess-1", "/workspace/output/generate_ppt.py", []byte("print(1)\n"),
))
require.NoError(t, mgr.WriteSessionWorkspaceFile(
ctx, "sess-1", filePath, []byte("print(1)\n"),
))
client.mu.Lock()
writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
execs := len(client.execRequests)
client.mu.Unlock()
require.Len(t, writes, 1)
require.Equal(t, "/workspace/output/generate_ppt.py", writes[0].path)
require.Equal(t, []byte("print(1)\n"), writes[0].content)
require.Equal(t, 1, execs)
client.mu.Lock()
writes := append([]fakeRemoteWriteFile(nil), client.writeFiles...)
execs := len(client.execRequests)
client.mu.Unlock()
require.Len(t, writes, 1)
require.Equal(t, filePath, writes[0].path)
require.Equal(t, []byte("print(1)\n"), writes[0].content)
require.Equal(t, 1, execs)
})
}
}
func TestWriteSessionWorkspaceFilesPreparesLayoutOnce(t *testing.T) {

View File

@ -91,11 +91,11 @@ func RunnableWorkspaceScript(scriptPath string) (string, bool) {
// 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.
// collector took the host value as-is. Keep this separate from shell working
// directories: access to a sandbox path does not make it a delivery directory.
func ValidatedSessionOutputDir(dir string) (string, bool) {
clean, err := cleanSessionWorkDir(dir, false)
if err != nil {
clean := path.Clean(strings.TrimSpace(dir))
if clean != SessionWorkspaceRoot && !strings.HasPrefix(clean, SessionWorkspaceRoot+"/") {
return "", false
}
return clean, true

View File

@ -351,6 +351,8 @@ type Cleanable interface {
type ToolResult struct {
// OutputFiles holds sandbox references for this live result only. History
// uses the final answer's persistent resource references instead.
// A non-nil empty slice means output inspection found no eligible changes;
// nil means no output inspection result is available.
OutputFiles []string `json:"-"`
Success bool `json:"success"` // Whether the tool executed successfully
Output string `json:"output"` // Human-readable output

View File

@ -131,27 +131,6 @@ check_gofmt_files() {
log_ok "gofmt"
}
collect_go_packages_from_files() {
local -a files=("$@")
local f dir pkg module root_module
local -a pkgs=()
# Nested modules (docs/poc, cli, client) are not testable from the root
# module, so only keep packages that belong to it.
root_module="$(cd "$ROOT" && go list -m 2>/dev/null || true)"
for f in "${files[@]}"; do
[[ "$f" == *.go ]] || continue
dir="$(dirname "$f")"
module="$(cd "$ROOT/$dir" && go list -m 2>/dev/null)" || continue
[[ "$module" == "$root_module" ]] || continue
pkg="$(cd "$ROOT/$dir" && go list . 2>/dev/null)" || continue
pkgs+=("$pkg")
done
if [[ ${#pkgs[@]} -eq 0 ]]; then
return 0
fi
printf '%s\n' "${pkgs[@]}" | sort -u
}
run_golangci_if_available() {
local from_rev="$1"
if ! command -v golangci-lint >/dev/null 2>&1; then
@ -166,43 +145,48 @@ run_golangci_if_available() {
log_ok "golangci-lint"
}
run_full_app_vet() {
# Mirrors .github/workflows/app.yml: vet every app package (excl. docreader).
log_step "go vet (all app packages, like CI)"
run_app_vet_test() {
# Use the same application package set as CI, including callers of changed
# packages. Testing only directly changed packages misses contract regressions.
(
cd "$ROOT"
local package_list
package_list="$(go list ./...)"
local -a pkgs=()
while IFS= read -r line; do
[[ -n "$line" ]] && pkgs+=("$line")
done < <(go list ./... | grep -v '/docreader/' || true)
[[ -z "$line" || "$line" == *"/docreader/"* ]] && continue
pkgs+=("$line")
done <<< "$package_list"
if [[ ${#pkgs[@]} -eq 0 ]]; then
log_fail "no application packages found"
exit 1
fi
log_step "go vet (all app packages, like CI)"
go vet "${pkgs[@]}"
log_ok "go vet"
run_go_test_packages "${pkgs[@]}"
)
log_ok "go vet"
}
run_go_test_packages() {
local -a pkgs=("$@")
if [[ ${#pkgs[@]} -eq 0 ]]; then
log_step "no changed Go packages; skip go test"
log_step "no Go packages; skip go test"
return 0
fi
if [[ "${HOOK_SKIP_TEST:-}" == "1" ]]; then
log_step "HOOK_SKIP_TEST=1; skip go test"
return 0
fi
log_step "go test (${#pkgs[@]} changed package(s))"
log_step "go test (${#pkgs[@]} app package(s), like CI)"
(
cd "$ROOT"
go test -count=1 "${pkgs[@]}"
# Match app.yml: a developer's custom log template must not alter assertions.
LOG_FORMAT="" go test -count=1 "${pkgs[@]}"
)
log_ok "go test"
}
run_app_vet_test() {
run_full_app_vet
run_go_test_packages "$@"
}
run_cli_checks() {
log_step "cli: go vet && go test"
(

View File

@ -66,19 +66,7 @@ while read -r _local_ref local_sha remote_ref remote_sha; do
run_golangci_if_available "$lint_from_rev"
pkgs=()
while IFS= read -r line; do
[[ -n "$line" ]] && pkgs+=("$line")
done < <(collect_go_packages_from_files "${pr_changed_go[@]}")
filtered=()
for pkg in "${pkgs[@]}"; do
[[ "$pkg" == *"/docreader/"* ]] && continue
filtered+=("$pkg")
done
run_full_app_vet
run_go_test_packages "${filtered[@]}"
run_app_vet_test
log_step "go build ./cmd/server"
go build ./cmd/server

View File

@ -27,6 +27,6 @@ git -C "$ROOT" config core.hooksPath scripts/git-hooks
echo "Installed git hooks -> scripts/git-hooks"
echo " pre-commit: whitespace, gofmt (auto-fix), golangci-lint (if installed)"
echo " pre-push: PR gofmt + full go vet/build (like CI); scoped go test"
echo " pre-push: PR gofmt + full app go vet/test/build (like CI)"
echo ""
echo "Optional: SKIP_HOOKS=1 or HOOK_SKIP_TEST=1 — see script header."

View File

@ -0,0 +1,67 @@
#!/usr/bin/env bash
# Verify that app checks cover unchanged callers and propagate failures.
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
fixture="$(mktemp -d)"
trap 'rm -rf "$fixture"' EXIT
mkdir -p "$fixture/scripts/git-hooks" "$fixture/bin"
cp "$repo_root/scripts/git-hooks/common.sh" "$fixture/scripts/git-hooks/"
export HOOK_TEST_LOG="$fixture/go.log"
export LOG_FORMAT="developer-custom-template"
cat > "$fixture/bin/go" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' "$*" >> "$HOOK_TEST_LOG"
case "$1" in
list)
[[ "${HOOK_TEST_FAIL:-}" != list ]] || exit 1
printf '%s\n' example/internal/agent/tools example/internal/application/service example/docreader/proto
;;
vet|test)
if [[ "$1" == test && -n "${LOG_FORMAT:-}" ]]; then
echo "App tests inherited the developer log template" >&2
exit 1
fi
[[ "${HOOK_TEST_FAIL:-}" != "$1" ]] || exit 1
;;
*) echo "Unexpected go invocation: $*" >&2; exit 1 ;;
esac
EOF
chmod +x "$fixture/bin/go"
export PATH="$fixture/bin:$PATH"
unset HOOK_SKIP_TEST HOOK_TEST_FAIL
run_checks() {
bash -c 'source "$1"; run_app_vet_test' bash "$fixture/scripts/git-hooks/common.sh"
}
run_checks
cat > "$fixture/expected.log" <<'EOF'
list ./...
vet example/internal/agent/tools example/internal/application/service
test -count=1 example/internal/agent/tools example/internal/application/service
EOF
diff -u "$fixture/expected.log" "$HOOK_TEST_LOG"
# Keep the explicit local opt-out, but it must not skip vet.
: > "$HOOK_TEST_LOG"
HOOK_SKIP_TEST=1 run_checks
head -n 2 "$fixture/expected.log" > "$fixture/skip.log"
diff -u "$fixture/skip.log" "$HOOK_TEST_LOG"
for phase in list vet test; do
: > "$HOOK_TEST_LOG"
if HOOK_TEST_FAIL="$phase" run_checks > "$fixture/failure.log" 2>&1; then
echo "App checks accepted a failing go $phase" >&2
exit 1
fi
case "$phase" in
list) head -n 1 "$fixture/expected.log" ;;
vet) head -n 2 "$fixture/expected.log" ;;
test) cat "$fixture/expected.log" ;;
esac > "$fixture/failure-expected.log"
diff -u "$fixture/failure-expected.log" "$HOOK_TEST_LOG"
done
echo 'Git hook coverage checks passed'