Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(sandbox): 共享沙箱短会话目录 + 移除工具层目录限制 (#4533)

nullptr-error6ccc7d12e26d
diff --git a/internal/agent/prompts.go b/internal/agent/prompts.go
index e04d0a243..4ac33c5f0 100644
--- a/internal/agent/prompts.go
+++ b/internal/agent/prompts.go
@@ -396,13 +396,18 @@ func formatToolGuidanceForMode(names []string, skillInstallMode bool, layout san
input := sandbox.PromptSafePath(layout.InputDir)
output := sandbox.PromptSafePath(layout.OutputDir)
if root != "" && input != "" && output != "" {
- b.WriteString("Session workspace: " + root + ". Preserve uploaded originals in " + input + ". ")
- b.WriteString(output + " is the only directory collected for download, " +
- "so it takes finished deliverables only; " +
- "keep drafts and intermediate files in another directory under " +
- root + ". Commands start from " + root + " unless work_dir names a subdirectory. " +
- "Your other conversations share this machine under /workspace/sessions; " +
- "do not read, modify or delete them. Installed packages are shared with those conversations.\n")
+ b.WriteString("Session workspace: ")
+ b.WriteString(root)
+ b.WriteString(". Preserve uploaded originals in ")
+ b.WriteString(input)
+ b.WriteString(". ")
+ b.WriteString(output)
+ b.WriteString(" is the only directory collected for download, so it takes finished " +
+ "deliverables only; keep drafts and intermediate files in another directory under ")
+ b.WriteString(root)
+ b.WriteString(". Commands start from ")
+ b.WriteString(root)
+ b.WriteString(" unless work_dir names a subdirectory.\n")
b.WriteString(sandboxArtifactReferenceGuidance())
}
} else {
diff --git a/internal/agent/prompts_shell_test.go b/internal/agent/prompts_shell_test.go
index a649ba57a..940c8a027 100644
--- a/internal/agent/prompts_shell_test.go
+++ b/internal/agent/prompts_shell_test.go
@@ -86,6 +86,7 @@ func TestSharedLayoutPromptNamesTheSessionDirectory(t *testing.T) {
require.Contains(t, text, "Session workspace: "+l.Root)
require.Contains(t, text, l.InputDir)
require.Contains(t, text, l.OutputDir)
- require.Contains(t, text, "share this machine")
+ require.NotContains(t, text, "share this machine")
+ require.NotContains(t, text, "other conversations")
require.NotContains(t, text, "Session workspace: /workspace.")
}
diff --git a/internal/agent/tools/shell_exec.go b/internal/agent/tools/shell_exec.go
index 3f81b4d60..6e01c7059 100644
--- a/internal/agent/tools/shell_exec.go
+++ b/internal/agent/tools/shell_exec.go
@@ -127,16 +127,23 @@ var shellExecBlacklist = []struct {
var shellExecTool = BaseTool{
name: ToolShellExec,
- description: legacyShellExecDescription,
+ description: shellExecDescription(sandbox.RemoteWorkspaceLayout()),
schema: utils.GenerateSchema[ShellExecInput](),
}
-// legacyShellExecDescription is the remote /workspace prompt text. Host
-// layouts rewrite the same copy through shellExecDescription.
-const legacyShellExecDescription = `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.
+// The shell_exec copy is written against /workspace; the scope claim and the
+// lifetime line differ between a machine one session owns and a machine
+// several sessions share; everything else is the same words for both.
+const (
+ shellExecScopeOwned = `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.`
+ shellExecScopeShared = `Execute a command in this session's directory as root.`
+ shellExecLifetimeOwned = ` Changes live and die with this session.`
+ shellExecLifetimeShared = ` Deleting this session removes its directory, not the machine.`
+
+ shellExecBodyTemplate = `%s
- 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.
+ work_dir selects any directory on the machine; 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;
@@ -151,67 +158,24 @@ The sandbox belongs to this session alone; nothing here runs on the host.
` + "`" + skillNodePackageInstallCommand + "`" + `.
If .venv is absent, create it with python3 -m venv --without-pip "${WEKNORA_SKILL_DIR:?}/.venv".
Without uv, run the venv Python with -m ensurepip --upgrade before -m pip install.
- Changes live and die with this session.
+%s
- 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.
- Use ![description](sandbox:<file name>) with exact links from Output files, never stdout or temporary paths.`
+)
func shellExecDescription(l sandbox.WorkspaceLayout) string {
if l.IsHost() {
root := layoutRootOrGeneric(l)
return fmt.Sprintf(hostShellExecDescription, root, root, root)
}
+ scope, lifetime := shellExecScopeOwned, shellExecLifetimeOwned
if l.IsSharedRemote() {
- return sharedShellExecDescription(l)
- }
- return rewriteRemoteWorkspaceCopy(legacyShellExecDescription, l)
-}
-
-// sharedShellExecDescription is the shell_exec copy for a machine several
-// sessions share. The session directory is private; /tmp and the skills
-// image are not, and the machine outlives the session.
-func sharedShellExecDescription(l sandbox.WorkspaceLayout) string {
- root := layoutRootOrGeneric(l)
- input := sandbox.PromptSafePath(l.InputDir)
- if input == "" {
- input = "the attachment directory"
- }
- output := sandbox.PromptSafePath(l.OutputDir)
- if output == "" {
- output = "the output directory"
+ scope, lifetime = shellExecScopeShared, shellExecLifetimeShared
}
- return fmt.Sprintf(sharedShellExecDescriptionTemplate, root, root, input, output, root)
+ return rewriteRemoteWorkspaceCopy(fmt.Sprintf(shellExecBodyTemplate, scope, lifetime), l)
}
-const sharedShellExecDescriptionTemplate = `Execute a command in this session's directory on a shared machine as root.
-This machine is shared with the owner's other sessions; this session's files are only under %s.
-- CWD defaults to %s on every call; cd does not persist.
- work_dir must be that directory, /tmp, or the skills root (` + sandbox.SkillsImageRoot + `); other paths are rejected.
-- 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;
- host resources are staged automatically and use the system runtime until a local .venv is created.
- Scoped credentials apply to both. Example: skill_name="pdf", command="python3 report.py".
- Run bundled scripts via "$WEKNORA_SKILL_DIR/scripts/...". Omit skill_name for system commands.
-- %s contains user attachments: preserve originals. %s is the only directory collected
- for download, so it takes finished deliverables only; keep scratch and intermediate files elsewhere under %s.
- apt-get is available when the sandbox network policy allows it; permanent dependencies belong in the skill installer.
-- Install extras with skill_name set and the default work_dir:
- ` + "`" + skillPythonPackageInstallCommand + "`" + ` (no pip needed), or
- ` + "`" + skillNodePackageInstallCommand + "`" + `.
- If .venv is absent, create it with python3 -m venv --without-pip "${WEKNORA_SKILL_DIR:?}/.venv".
- Without uv, run the venv Python with -m ensurepip --upgrade before -m pip install.
- Deleting this session removes its directory, not the machine.
-- 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.
-- Use ![description](sandbox:<file name>) with exact links from Output files, never stdout or temporary paths.`
-
const hostShellExecDescription = "Execute a command in %s. The process is OS-sandboxed on this machine.\n" +
"- CWD defaults to %s on every call; cd does not persist. " +
"work_dir must be that folder or a subdirectory.\n" +
@@ -857,10 +821,9 @@ func (t *ShellExecTool) effectiveDefaultWorkDir() string {
//
// A remote sandbox is a disposable container the session owns outright, so any
// directory in it stays allowed; clamping those to /workspace would break
-// skills that legitimately build in /tmp or /opt. A shared machine clamps
-// work_dir to this session's roots. A host workspace is the user's own disk,
-// so there work_dir is clamped to the layout's writable roots. Install mode
-// keeps the skill-image roots and ignores session layouts.
+// skills that legitimately build in /tmp or /opt. A host workspace is the
+// user's own disk, so there work_dir is clamped to the layout's writable
+// roots. Install mode keeps the skill-image roots and ignores session layouts.
func (t *ShellExecTool) workDirRootsFor(layout sandbox.WorkspaceLayout) []string {
if t.isInstallMode() {
if len(t.workDirRoots) == 0 {
@@ -868,10 +831,6 @@ func (t *ShellExecTool) workDirRootsFor(layout sandbox.WorkspaceLayout) []string
}
return t.workDirRoots
}
- if layout.IsSharedRemote() {
- // Several sessions share this machine; work_dir stays in this one.
- return layout.WorkDirRoots
- }
if !layout.IsHost() {
return []string{"/"}
}
diff --git a/internal/agent/tools/workspace_layout.go b/internal/agent/tools/workspace_layout.go
index fb0e4f4fa..2e47f09bc 100644
--- a/internal/agent/tools/workspace_layout.go
+++ b/internal/agent/tools/workspace_layout.go
@@ -122,7 +122,7 @@ func resolveIn(l sandbox.WorkspaceLayout, p string) string {
// and must not sit under the read-only attachment directory. When several
// roots match, the most specific one is reported.
func writableRootIn(l sandbox.WorkspaceLayout, clean string) (string, bool) {
- if l.InputDir != "" && isUnderRoot(clean, l.InputDir) {
+ if l.ReadOnlyInputRoot(clean) != "" {
return "", false
}
best := ""
@@ -153,18 +153,23 @@ func inspectableRootIn(l sandbox.WorkspaceLayout, clean string) (string, bool) {
// inspectRoot reports the metadata root for a read/list. A session-owned
// remote sandbox labels misses as "/" and still inspects (tmp, installed
-// skills). Host layouts and shared remote machines allow ReadRoots only.
+// skills). Host layouts allow ReadRoots only.
func inspectRoot(l sandbox.WorkspaceLayout, clean string) (string, bool) {
if root, ok := inspectableRootIn(l, clean); ok {
return root, true
}
- if l.IsHost() || l.IsSharedRemote() {
+ if l.IsHost() {
return "", false
}
return "/", true
}
func writeScopeErrorIn(l sandbox.WorkspaceLayout, requested string) string {
+ if l.IsSharedRemote() {
+ if input := l.ReadOnlyInputRoot(resolveIn(l, requested)); input != "" {
+ return fmt.Sprintf("session input %s is read-only; write a copy outside attachment directories", input)
+ }
+ }
scope := layoutScopeName(l)
if strings.TrimSpace(l.InputDir) == "" {
return fmt.Sprintf(
diff --git a/internal/agent/tools/workspace_layout_test.go b/internal/agent/tools/workspace_layout_test.go
index 31074f464..511dc4858 100644
--- a/internal/agent/tools/workspace_layout_test.go
+++ b/internal/agent/tools/workspace_layout_test.go
@@ -208,7 +208,8 @@ func TestShellExecInstallModeIgnoresWorkspaceLayout(t *testing.T) {
// The remote description must not drift: it is prompt text a lot of behaviour
// was tuned against.
func TestShellExecDescriptionRemoteIsUnchanged(t *testing.T) {
- require.Equal(t, legacyShellExecDescription,
+ require.Equal(t,
+ fmt.Sprintf(shellExecBodyTemplate, shellExecScopeOwned, shellExecLifetimeOwned),
shellExecDescription(sandbox.RemoteWorkspaceLayout()))
}
@@ -559,20 +560,69 @@ func TestListSandboxFilesScopeErrorNamesResolvedDefaultDir(t *testing.T) {
require.NotContains(t, result.Error, `path ""`)
}
-func TestSharedLayoutClampsInspectAndWorkDir(t *testing.T) {
+func TestSharedLayoutAllowsInspectingTheWholeMachine(t *testing.T) {
l, err := sandbox.UserWorkspaceLayout("0f8fad5b-d9cb-469f-a165-70867728950e")
require.NoError(t, err)
- _, ok := inspectRoot(l, "/workspace/sessions/7c9e6679-7425-40de-944b-e07fc1f90ae7/a.md")
- require.False(t, ok, "a shared machine must not read a sibling session through the tools")
- root, ok := inspectRoot(l, sandbox.SkillsImageRoot+"/pdf/SKILL.md")
+ root, ok := inspectRoot(l, "/workspace/sessions/7c9e6679-7425-40de-944b-e07fc1f90ae7/a.md")
+ require.True(t, ok, "a sibling session's directory is not refused any more")
+ require.Equal(t, "/", root)
+ root, ok = inspectRoot(l, sandbox.SkillsImageRoot+"/pdf/SKILL.md")
require.True(t, ok)
require.Equal(t, sandbox.SkillsImageRoot, root)
tool := &ShellExecTool{}
- require.Equal(t, l.WorkDirRoots, tool.workDirRootsFor(l))
+ require.Equal(t, []string{"/"}, tool.workDirRootsFor(l),
+ "a shared machine allows work_dir anywhere, like a session-owned one")
require.Equal(t, []string{"/"}, tool.workDirRootsFor(sandbox.RemoteWorkspaceLayout()))
}
+func TestSharedFileToolsProtectSiblingAttachments(t *testing.T) {
+ l, err := sandbox.UserWorkspaceLayout("0f8fad5b-d9cb-469f-a165-70867728950e")
+ require.NoError(t, err)
+ sibling, err := sandbox.UserWorkspaceLayout("7c9e6679-7425-40de-944b-e07fc1f90ae7")
+ require.NoError(t, err)
+ for _, file := range []string{
+ sibling.InputDir + "/original.txt",
+ sibling.Root + "/output/../input/original.txt",
+ } {
+ t.Run(file, func(t *testing.T) {
+ target := sibling.InputDir + "/original.txt"
+ sink := &layoutFileSink{layout: l}
+ sink.files = map[string][]byte{target: []byte("original")}
+ writer := NewWriteSandboxFileTool(sink, 0)
+ editor := NewEditSandboxFileTool(sink)
+ for _, mode := range []string{"overwrite", "append"} {
+ args, err := json.Marshal(WriteSandboxFileInput{Path: file, Content: "modified", Mode: mode})
+ require.NoError(t, err)
+ result, err := writer.Execute(sandboxFileTestContext(), args)
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Contains(t, result.Error, sibling.InputDir+" is read-only")
+ }
+ result, err := editor.Execute(
+ sandboxFileTestContext(), mustEditSandboxArgs(file, "original", "modified", false),
+ )
+ require.NoError(t, err)
+ require.False(t, result.Success)
+ require.Contains(t, result.Error, sibling.InputDir+" is read-only")
+ require.Zero(t, sink.calls)
+ require.Equal(t, "original", string(sink.files[target]))
+
+ // Ordinary sibling files remain writable with both tools.
+ work := sibling.OutputDir + "/report.txt"
+ result, err = writer.Execute(sandboxFileTestContext(), mustWriteSandboxArgs(work, "original"))
+ require.NoError(t, err)
+ require.True(t, result.Success, result.Error)
+ result, err = editor.Execute(
+ sandboxFileTestContext(), mustEditSandboxArgs(work, "original", "modified", false),
+ )
+ require.NoError(t, err)
+ require.True(t, result.Success, result.Error)
+ require.Equal(t, "modified", string(sink.files[work]))
+ })
+ }
+}
+
func TestSharedLayoutToolCopyKeepsSessionPathsIntact(t *testing.T) {
l, err := sandbox.UserWorkspaceLayout("0f8fad5b-d9cb-469f-a165-70867728950e")
require.NoError(t, err)
@@ -584,20 +634,18 @@ func TestSharedLayoutToolCopyKeepsSessionPathsIntact(t *testing.T) {
"substituting /workspace must not rewrite a path that already names the session")
}
-func TestSharedLayoutShellDescriptionStatesTheWorkDirRestriction(t *testing.T) {
+func TestSharedLayoutShellDescriptionNamesTheSessionDirectory(t *testing.T) {
l, err := sandbox.UserWorkspaceLayout("0f8fad5b-d9cb-469f-a165-70867728950e")
require.NoError(t, err)
text := shellExecDescription(l)
- require.Contains(t, text, "shared with the owner's other sessions")
- require.Contains(t, text, "this session's files are only under "+l.Root)
- require.Contains(t, text, "work_dir must be that directory, /tmp, or the skills root ("+sandbox.SkillsImageRoot+")")
- require.Contains(t, text, "other paths are rejected")
+ require.Contains(t, text, "CWD defaults to "+l.Root)
require.Contains(t, text, "Deleting this session removes its directory, not the machine")
require.Contains(t, text, "skill_name")
require.Contains(t, text, l.InputDir)
require.Contains(t, text, l.OutputDir)
require.Contains(t, text, "no nohup")
+ require.NotContains(t, text, "shared")
+ require.NotContains(t, text, "other sessions")
require.NotContains(t, text, "belongs to this session alone")
- require.NotContains(t, text, "any directory")
require.Contains(t, shellExecDescription(sandbox.RemoteWorkspaceLayout()), "belongs to this session alone")
}
diff --git a/internal/sandbox/allocation/allocation_test.go b/internal/sandbox/allocation/allocation_test.go
index 5f942d03f..de41a0322 100644
--- a/internal/sandbox/allocation/allocation_test.go
+++ b/internal/sandbox/allocation/allocation_test.go
@@ -141,7 +141,7 @@ func TestAssignmentLayout(t *testing.T) {
require.Equal(t, ModeUser, u.Mode())
l, err = u.Layout()
require.NoError(t, err)
- require.Equal(t, "/workspace/sessions/"+sid, l.Root)
+ require.Equal(t, "/workspace/sessions/c812e1edb644", l.Root)
m, ok := u.UserMachine()
require.True(t, ok)
require.Equal(t, want, m)
diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go
index 34cbf4112..5408c23bb 100644
--- a/internal/sandbox/session_manager.go
+++ b/internal/sandbox/session_manager.go
@@ -626,9 +626,6 @@ func (m *SessionBoundManager) EnsureSessionDir(ctx context.Context, sessionID, d
if err != nil {
return err
}
- if !sc.allowsPath(dir) {
- return fmt.Errorf("sandbox: path %q is outside the session workspace %s", dir, sc.layout.Root)
- }
ctx, release, err := m.admitUser(ctx, sc, "file")
if err != nil {
return err
@@ -826,9 +823,6 @@ func (m *SessionBoundManager) ListSessionFiles(
if err != nil {
return nil, err
}
- if !sc.allowsPath(dir) {
- return nil, fmt.Errorf("sandbox: path %q is outside the session workspace %s", dir, sc.layout.Root)
- }
ctx, release, err := m.admitUser(ctx, sc, "file")
if err != nil {
return nil, err
@@ -858,9 +852,6 @@ func (m *SessionBoundManager) StatSessionFile(
if err != nil {
return nil, err
}
- if !sc.allowsPath(filePath) {
- return nil, fmt.Errorf("sandbox: path %q is outside the session workspace %s", filePath, sc.layout.Root)
- }
ctx, release, err := m.admitUser(ctx, sc, "file")
if err != nil {
return nil, err
@@ -891,9 +882,6 @@ func (m *SessionBoundManager) ReadSessionFile(
if err != nil {
return nil, err
}
- if !sc.allowsPath(filePath) {
- return nil, fmt.Errorf("sandbox: path %q is outside the session workspace %s", filePath, sc.layout.Root)
- }
ctx, release, err := m.admitUser(ctx, sc, "file")
if err != nil {
return nil, err
@@ -2294,7 +2282,10 @@ func (m *SessionBoundManager) DeleteSessionWorkspaces(
}
var targets []string
for _, id := range ready {
- l, _ := UserWorkspaceLayout(id)
+ l, err := UserWorkspaceLayout(id)
+ if err != nil {
+ return nil, err
+ }
targets = append(targets, ShellQuote(l.Root), ShellQuote(l.GitDir))
}
// Refuse a symlinked parent instead of following it: an agent on this
@@ -2357,21 +2348,6 @@ func withSessionEnv(env map[string]string, layout WorkspaceLayout) map[string]st
return out
}
-// allowsPath reports whether a shared-machine file access stays in the
-// session's scope (its read roots, /tmp, the skills image).
-func (s sessionScope) allowsPath(p string) bool {
- if !s.user {
- return true
- }
- clean := path.Clean(strings.TrimSpace(p))
- for _, root := range append(append([]string{}, s.layout.ReadRoots...), s.layout.WorkDirRoots...) {
- if workspace.IsUnder(clean, root) {
- return true
- }
- }
- return false
-}
-
// userScriptDir is where an uploaded skill script lands on a shared machine.
func userScriptDir(layout WorkspaceLayout) string {
return path.Join(layout.Root, ".weknora", "scripts")
diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.go
index 858f5dd8e..9a6367f70 100644
--- a/internal/sandbox/session_manager_test.go
+++ b/internal/sandbox/session_manager_test.go
@@ -1173,10 +1173,10 @@ func TestUserSessionsShareOneMachineWithSeparateDirectories(t *testing.T) {
creates, _, _, _, _ := h.client.counts()
require.Equal(t, 1, creates)
- require.Equal(t, "/workspace/sessions/"+userSessionA, reqA.WorkDir)
- require.Equal(t, "/workspace/sessions/"+userSessionB, reqB.WorkDir)
- require.Equal(t, "/workspace/sessions/"+userSessionB+"/output", reqB.Env["WEKNORA_SKILL_OUTPUT_DIR"])
- require.Equal(t, "/workspace/sessions/"+userSessionB+"/input", reqB.Env["WEKNORA_SESSION_INPUT_DIR"])
+ require.Equal(t, userSessionRoot(userSessionA), reqA.WorkDir)
+ require.Equal(t, userSessionRoot(userSessionB), reqB.WorkDir)
+ require.Equal(t, userSessionRoot(userSessionB)+"/output", reqB.Env["WEKNORA_SKILL_OUTPUT_DIR"])
+ require.Equal(t, userSessionRoot(userSessionB)+"/input", reqB.Env["WEKNORA_SESSION_INPUT_DIR"])
idA, ok := h.mgr.BoundSandboxID(ctx, userSessionA)
require.True(t, ok)
@@ -1192,17 +1192,36 @@ func TestUserSessionsShareOneMachineWithSeparateDirectories(t *testing.T) {
require.Zero(t, n, "every operation released its leases")
}
-func TestUserSessionCannotLeaveItsWorkspace(t *testing.T) {
+func TestUserSessionMayUseTheWholeMachine(t *testing.T) {
h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
ctx := ownerCtx()
_, err := h.mgr.ExecShellCommand(ctx, userSessionA, "true", "/workspace", time.Second, nil)
- require.ErrorContains(t, err, "outside allowed roots")
- err = h.mgr.WriteSessionWorkspaceFile(ctx, userSessionA, "/workspace/sessions/"+userSessionB+"/x", []byte("x"))
- require.ErrorContains(t, err, "outside the session workspace")
+ require.NoError(t, err, "work_dir is not clamped to the session directory")
+ err = h.mgr.WriteSessionWorkspaceFile(ctx, userSessionA, userSessionRoot(userSessionB)+"/x", []byte("x"))
+ require.NoError(t, err, "a sibling session's directory is not refused any more")
err = h.mgr.WriteSessionInputFile(ctx, userSessionA, "/workspace/input/a.pdf", []byte("x"))
- require.Error(t, err)
- _, err = h.mgr.ReadSessionFile(ctx, userSessionA, "/workspace/sessions/"+userSessionB+"/x")
- require.ErrorContains(t, err, "outside the session workspace")
+ require.Error(t, err, "the legacy attachment root stays reserved")
+ _, err = h.mgr.ReadSessionFile(ctx, userSessionA, userSessionRoot(userSessionB)+"/x")
+ require.NoError(t, err, "reads of a sibling's tree go through to the provider")
+}
+
+func TestUserSessionWorkspaceWritesPreserveSiblingInputs(t *testing.T) {
+ h := newUserManagerHarness(t, userAssignmentFor(userSessionA), userAssignmentFor(userSessionB))
+ ctx := ownerCtx()
+ input := userSessionRoot(userSessionB) + "/input/original.txt"
+ require.NoError(t, h.mgr.WriteSessionInputFile(ctx, userSessionB, input, []byte("original")),
+ "application attachment staging remains allowed")
+ writesBefore := len(h.client.writeFiles)
+ err := h.mgr.WriteSessionWorkspaceFile(ctx, userSessionA, input, []byte("modified"))
+ require.ErrorContains(t, err, "read-only")
+ err = h.mgr.WriteSessionWorkspaceFiles(ctx, userSessionA, []SessionWorkspaceFile{
+ {Path: userSessionRoot(userSessionB) + "/output/report.txt", Content: []byte("report")},
+ {Path: userSessionRoot(userSessionB) + "/output/../input/original.txt", Content: []byte("modified")},
+ })
+ require.ErrorContains(t, err, "read-only")
+ require.Len(t, h.client.writeFiles, writesBefore, "reject the entire batch before writing any files")
+ _, err = h.mgr.ReadSessionFile(ctx, userSessionA, input)
+ require.NoError(t, err, "sibling inputs remain readable")
}
func TestValidityIsReadFreshNotCached(t *testing.T) {
@@ -1214,7 +1233,7 @@ func TestValidityIsReadFreshNotCached(t *testing.T) {
h.allocs.release(userSessionA) // deleted by another replica after this manager cached the address
_, err = h.mgr.ExecShellCommand(ctx, userSessionA, "true", "", time.Second, nil)
require.ErrorIs(t, err, ErrSandboxSessionDeleted)
- _, err = h.mgr.ListSessionFiles(ctx, userSessionA, "/workspace/sessions/"+userSessionA+"/output")
+ _, err = h.mgr.ListSessionFiles(ctx, userSessionA, userSessionRoot(userSessionA)+"/output")
require.ErrorIs(t, err, ErrSandboxSessionDeleted, "lookup-only reads are admitted the same way")
}
@@ -1464,6 +1483,14 @@ func TestLockRewindSessionOnAPerSessionSandboxKeepsTheContext(t *testing.T) {
require.Equal(t, 1, got.Value(struct{ k string }{"marker"}))
}
+func userSessionRoot(id string) string {
+ l, err := UserWorkspaceLayout(id)
+ if err != nil {
+ panic(err)
+ }
+ return l.Root
+}
+
func TestUploadedScriptsStayInTheSessionDirectory(t *testing.T) {
h := newUserManagerHarness(t, userAssignmentFor(userSessionA))
script := filepath.Join(t.TempDir(), "run.py")
@@ -1473,7 +1500,7 @@ func TestUploadedScriptsStayInTheSessionDirectory(t *testing.T) {
h.client.mu.Lock()
defer h.client.mu.Unlock()
require.NotEmpty(t, h.client.writeFiles)
- require.Equal(t, "/workspace/sessions/"+userSessionA+"/.weknora/scripts/run.py",
+ require.Equal(t, userSessionRoot(userSessionA)+"/.weknora/scripts/run.py",
h.client.writeFiles[len(h.client.writeFiles)-1].path)
}
@@ -1526,8 +1553,10 @@ func TestDeleteSessionWorkspacesWaitsForTheSessionAndRemovesOnlyIt(t *testing.T)
require.Greater(t, connectsAfter, connectsBefore, "deleting a session connects (and resumes) the machine")
require.Zero(t, deletes, "the shared machine itself stays")
cmd := lastExecRequest(t, h.client).Command
- require.Contains(t, cmd, "/workspace/sessions/"+userSessionA)
- require.Contains(t, cmd, "/var/lib/weknora/sessions/"+userSessionA+".git")
+ layout, err := h.mgr.SessionWorkspaceLayout(context.Background(), userSessionA)
+ require.NoError(t, err)
+ require.Contains(t, cmd, layout.Root)
+ require.Contains(t, cmd, layout.GitDir)
require.NotContains(t, cmd, userSessionB)
require.Contains(t, cmd, "-L", "symlinked parents are refused, not followed")
}
@@ -1557,7 +1586,7 @@ func TestDeleteSessionWorkspacesReadoptsAMachineWhoseBindingWasLost(t *testing.T
deleted, err := h.mgr.DeleteSessionWorkspaces(ctx, m, []string{userSessionA})
require.NoError(t, err)
require.Equal(t, []string{userSessionA}, deleted)
- require.Contains(t, lastExecRequest(t, h.client).Command, "/workspace/sessions/"+userSessionA,
+ require.Contains(t, lastExecRequest(t, h.client).Command, userSessionRoot(userSessionA),
"the files are really deleted on the machine B will keep using")
rebound, _ := h.mgr.BoundSandboxID(ctx, userSessionB)
require.Equal(t, sandboxID, rebound, "re-adopted, not recreated")
@@ -1633,8 +1662,8 @@ func TestWorkspaceForkHoldsLeasesAndCopiesWithOneGuardedScript(t *testing.T) {
require.Equal(t, map[string]bool{sha: true, older: true}, reachable)
req := lastExecRequest(t, h.client)
require.Equal(t, "root", req.User)
- require.Contains(t, req.Command, "/var/lib/weknora/sessions/"+userSessionA+".git")
- require.Contains(t, req.Command, "/workspace/sessions/"+userSessionB)
+ require.Contains(t, req.Command, "/var/lib/weknora/sessions/c812e1edb644.git")
+ require.Contains(t, req.Command, userSessionRoot(userSessionB))
require.Contains(t, req.Command, "core.hooksPath=/dev/null")
require.Contains(t, req.Command, `"160000"`, "gitlinks are refused")
require.Contains(t, req.Command, "merge-base --is-ancestor")
@@ -1645,7 +1674,7 @@ func TestWorkspaceForkHoldsLeasesAndCopiesWithOneGuardedScript(t *testing.T) {
require.Error(t, err)
require.NoError(t, fork.Remove(userSessionB))
- require.Contains(t, lastExecRequest(t, h.client).Command, "/workspace/sessions/"+userSessionB)
+ require.Contains(t, lastExecRequest(t, h.client).Command, userSessionRoot(userSessionB))
fork.Release()
active, _ = h.admission.ActiveExcept(ctx, admission.MachineScope(machine.Digest("weknora")))
require.Zero(t, active)
@@ -1687,8 +1716,8 @@ func TestUserModeTerminalCreatesTheSessionDirectoryFirst(t *testing.T) {
cmd := lastExecRequest(t, h.client).Command
require.Contains(t, cmd, "mkdir -p")
- require.Contains(t, cmd, "/workspace/sessions/"+userSessionB)
- require.Equal(t, "/workspace/sessions/"+userSessionB, h.client.lastTerminalOptions().Cwd)
+ require.Contains(t, cmd, userSessionRoot(userSessionB))
+ require.Equal(t, userSessionRoot(userSessionB), h.client.lastTerminalOptions().Cwd)
}
func TestUserModeTerminalNeverReattachesAClientPID(t *testing.T) {
@@ -1701,7 +1730,7 @@ func TestUserModeTerminalNeverReattachesAClientPID(t *testing.T) {
defer func() { _ = term.Close() }()
opts := h.client.lastTerminalOptions()
require.Zero(t, opts.AttachPID, "a PID on a shared machine may belong to another session")
- require.Equal(t, "/workspace/sessions/"+userSessionA, opts.Cwd)
+ require.Equal(t, userSessionRoot(userSessionA), opts.Cwd)
}
func TestMultiReplicaRealRedisFirstAllocationCreatesOneMachine(t *testing.T) {
diff --git a/internal/sandbox/workspace/layout.go b/internal/sandbox/workspace/layout.go
index 7ff2a167c..46d8240b0 100644
--- a/internal/sandbox/workspace/layout.go
+++ b/internal/sandbox/workspace/layout.go
@@ -6,6 +6,8 @@
package workspace
import (
+ "crypto/sha256"
+ "encoding/hex"
"fmt"
"path"
"strings"
@@ -120,27 +122,43 @@ func Remote() Layout {
// UserSession is the layout of sessionID on a machine its owner's sessions
// share. Only canonical lower-case UUIDs are accepted, so the id can never
-// carry a path segment of its own.
+// carry a path segment of its own. The directory name is SessionDirName, not
+// the full UUID: the model sees this path on every turn. The session root
+// anchors commands and artifact collection; it is not a tool-layer access
+// boundary — tools treat the machine like a session-owned one.
func UserSession(sessionID string) (Layout, error) {
- if !IsCanonicalUUID(sessionID) {
- return Layout{}, fmt.Errorf("workspace: session id %q is not a canonical UUID", sessionID)
+ name, err := SessionDirName(sessionID)
+ if err != nil {
+ return Layout{}, err
}
- root := path.Join(UserSessionsRoot, sessionID)
+ root := path.Join(UserSessionsRoot, name)
input := path.Join(root, "input")
output := path.Join(root, "output")
return Layout{
- Origin: OriginRemoteShared,
- Root: root,
- WriteRoots: []string{root, output},
- ReadRoots: []string{output, input, root, SkillsImageRoot},
- InputDir: input,
- OutputDir: output,
- Hint: root,
- GitDir: path.Join(UserGitRoot, sessionID+".git"),
- WorkDirRoots: []string{root, TmpRoot, SkillsImageRoot},
+ Origin: OriginRemoteShared,
+ Root: root,
+ WriteRoots: []string{Root, OutputDir},
+ ReadRoots: []string{output, input, root, SkillsImageRoot},
+ InputDir: input,
+ OutputDir: output,
+ Hint: root,
+ GitDir: path.Join(UserGitRoot, name+".git"),
}, nil
}
+// SessionDirName is the on-disk directory for a canonical session UUID: the
+// first 12 hex characters of the id's SHA-256. The hash uses every bit of the
+// UUID, so a collision needs roughly a million sessions on one machine, and
+// the name is deterministic: no mapping is stored anywhere. The full id stays
+// the session's identity everywhere else.
+func SessionDirName(sessionID string) (string, error) {
+ if !IsCanonicalUUID(sessionID) {
+ return "", fmt.Errorf("workspace: session id %q is not a canonical UUID", sessionID)
+ }
+ sum := sha256.Sum256([]byte(sessionID))
+ return hex.EncodeToString(sum[:])[:12], nil
+}
+
// FailedHost is what tools and prompts use when a layout provider exists but
// errors: do not fall back to /workspace.
func FailedHost() Layout { return Layout{Origin: OriginHost} }
diff --git a/internal/sandbox/workspace/layout_test.go b/internal/sandbox/workspace/layout_test.go
index 799b86fa7..8aa116246 100644
--- a/internal/sandbox/workspace/layout_test.go
+++ b/internal/sandbox/workspace/layout_test.go
@@ -22,20 +22,24 @@ func TestRemoteLayoutKeepsTheHistoricalContract(t *testing.T) {
require.False(t, l.IsSharedRemote())
}
-func TestUserSessionLayoutScopesEveryPathToTheSession(t *testing.T) {
+func TestUserSessionLayoutUsesMachineWideWriteRoots(t *testing.T) {
l, err := UserSession(testSessionID)
require.NoError(t, err)
- root := "/workspace/sessions/" + testSessionID
+ name, err := SessionDirName(testSessionID)
+ require.NoError(t, err)
+ require.Equal(t, "c812e1edb644", name, "the first 12 hex chars of the id's SHA-256")
+ root := "/workspace/sessions/" + name
require.Equal(t, OriginRemoteShared, l.Origin)
require.True(t, l.IsSharedRemote())
require.False(t, l.IsHost())
require.Equal(t, root, l.Root)
require.Equal(t, root+"/input", l.InputDir)
require.Equal(t, root+"/output", l.OutputDir)
- require.Equal(t, []string{root, root + "/output"}, l.WriteRoots)
+ require.Equal(t, []string{Root, OutputDir}, l.WriteRoots,
+ "tools treat the machine like a session-owned one: the whole /workspace is writable")
require.Equal(t, []string{root + "/output", root + "/input", root, SkillsImageRoot}, l.ReadRoots)
- require.Equal(t, []string{root, TmpRoot, SkillsImageRoot}, l.WorkDirRoots)
- require.Equal(t, "/var/lib/weknora/sessions/"+testSessionID+".git", l.GitDir)
+ require.Empty(t, l.WorkDirRoots, "no work_dir whitelist: any absolute directory is allowed")
+ require.Equal(t, "/var/lib/weknora/sessions/"+name+".git", l.GitDir)
require.Equal(t, root, l.Hint)
}
diff --git a/internal/sandbox/workspace/paths.go b/internal/sandbox/workspace/paths.go
index fbcbe39bd..ab55b0c6f 100644
--- a/internal/sandbox/workspace/paths.go
+++ b/internal/sandbox/workspace/paths.go
@@ -36,10 +36,38 @@ func underAny(p string, roots []string) bool {
return false
}
+// ReadOnlyInputRoot returns the attachment root containing a clean absolute
+// path. Shared machines reserve every session's input tree, not only the
+// caller's: widening file access must not make another session's originals
+// writable. This is a lexical tool rule, not an OS permission boundary.
+func (l Layout) ReadOnlyInputRoot(clean string) string {
+ if l.InputDir != "" && IsUnder(clean, l.InputDir) {
+ return l.InputDir
+ }
+ if !l.IsSharedRemote() {
+ return ""
+ }
+ if IsUnder(clean, InputDir) {
+ return InputDir
+ }
+ relative, ok := strings.CutPrefix(clean, UserSessionsRoot+"/")
+ if !ok {
+ return ""
+ }
+ name, _, ok := strings.Cut(relative, "/")
+ if !ok || name == "" {
+ return ""
+ }
+ input := path.Join(UserSessionsRoot, name, "input")
+ if IsUnder(clean, input) {
+ return input
+ }
+ return ""
+}
+
// CleanWriteFileIn normalizes a model-authored sandbox write and protects the
-// attachment tree. A session-owned machine keeps today's rule (tools enforce
-// WriteRoots); a shared machine additionally refuses anything outside the
-// session's WriteRoots, so one session cannot write into a sibling's tree.
+// attachment tree. The rule is the same on a session-owned and a shared
+// machine: tools enforce WriteRoots at the tool layer.
func CleanWriteFileIn(l Layout, filePath string) (string, error) {
clean := ResolvePathIn(l, filePath)
if !path.IsAbs(clean) || clean == "." || clean == "/" {
@@ -48,11 +76,8 @@ func CleanWriteFileIn(l Layout, filePath string) (string, error) {
if clean == l.Root || clean == l.OutputDir || clean == l.InputDir {
return "", fmt.Errorf("sandbox: workspace write path %q is a directory, not a file", filePath)
}
- if l.InputDir != "" && strings.HasPrefix(clean, l.InputDir+"/") {
- return "", fmt.Errorf("sandbox: session input %s is read-only", l.InputDir)
- }
- if l.IsSharedRemote() && !underAny(clean, l.WriteRoots) {
- return "", fmt.Errorf("sandbox: workspace write path %q is outside the session workspace %s", filePath, l.Root)
+ if input := l.ReadOnlyInputRoot(clean); input != "" {
+ return "", fmt.Errorf("sandbox: session input %s is read-only", input)
}
return clean, nil
}
@@ -67,27 +92,22 @@ func CleanInputPathIn(l Layout, filePath string) (string, error) {
}
// CleanWorkDirIn requires an absolute working directory. Install calls keep
-// the workspace/skills scope; a shared machine limits ordinary calls to
-// WorkDirRoots; a session-owned machine allows any directory. None of these
-// checks changes filesystem privileges.
+// the workspace/skills scope; every other layout allows any directory on the
+// machine. None of these checks changes filesystem privileges.
func CleanWorkDirIn(l Layout, 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)
}
- var allowed []string
- switch {
- case allowSkillsRoot:
- allowed = []string{l.Root, SkillsImageRoot}
- case l.IsSharedRemote():
- allowed = l.WorkDirRoots
- default:
- return clean, nil
- }
- if underAny(clean, allowed) {
- return clean, nil
+ if allowSkillsRoot {
+ allowed := []string{l.Root, SkillsImageRoot}
+ if underAny(clean, allowed) {
+ return clean, nil
+ }
+ return "", fmt.Errorf("sandbox: work dir %q is outside allowed roots (%s)",
+ workDir, strings.Join(allowed, ", "))
}
- return "", fmt.Errorf("sandbox: work dir %q is outside allowed roots (%s)", workDir, strings.Join(allowed, ", "))
+ return clean, nil
}
// ValidOutputDirIn reports whether dir may be used as the artifact directory.
diff --git a/internal/sandbox/workspace/paths_test.go b/internal/sandbox/workspace/paths_test.go
index 249fbd3a6..d469ee850 100644
--- a/internal/sandbox/workspace/paths_test.go
+++ b/internal/sandbox/workspace/paths_test.go
@@ -1,6 +1,7 @@
package workspace
import (
+ "path"
"testing"
"github.com/stretchr/testify/require"
@@ -31,20 +32,51 @@ func TestCleanWriteFileInRemoteMatchesHistoricalErrors(t *testing.T) {
require.EqualError(t, err, `sandbox: workspace write path "/" must be an absolute file path`)
}
-func TestCleanWriteFileInSharedStaysInsideTheSession(t *testing.T) {
+func TestCleanWriteFileInSharedAllowsTheWholeMachine(t *testing.T) {
l := userLayout(t)
got, err := CleanWriteFileIn(l, "report.md")
require.NoError(t, err)
require.Equal(t, l.Root+"/report.md", got)
- _, err = CleanWriteFileIn(l, "/workspace/sessions/11111111-2222-4333-8444-555555555555/a.md")
- require.ErrorContains(t, err, "outside the session workspace")
- _, err = CleanWriteFileIn(l, "../11111111-2222-4333-8444-555555555555/a.md")
- require.ErrorContains(t, err, "outside the session workspace")
+ got, err = CleanWriteFileIn(l, "/workspace/sessions/11111111-2222-4333-8444-555555555555/a.md")
+ require.NoError(t, err, "a sibling session's directory is not refused any more")
+ require.Equal(t, "/workspace/sessions/11111111-2222-4333-8444-555555555555/a.md", got)
_, err = CleanWriteFileIn(l, l.InputDir+"/x")
require.ErrorContains(t, err, "read-only")
}
+func TestSharedWritesProtectEverySessionInput(t *testing.T) {
+ l := userLayout(t)
+ sibling, err := UserSession("7c9e6679-7425-40de-944b-e07fc1f90ae7")
+ require.NoError(t, err)
+ for _, p := range []string{
+ l.InputDir + "/original.txt",
+ sibling.InputDir,
+ sibling.InputDir + "/original.txt",
+ sibling.InputDir + "/nested/original.txt",
+ sibling.Root + "/output/../input/original.txt",
+ "../" + path.Base(sibling.Root) + "/input/original.txt",
+ InputDir + "/original.txt",
+ } {
+ _, err := CleanWriteFileIn(l, p)
+ require.ErrorContains(t, err, "read-only", p)
+ }
+ for _, p := range []string{
+ sibling.Root + "/notes.txt",
+ sibling.OutputDir + "/report.txt",
+ sibling.Root + "/input-copy/original.txt",
+ sibling.Root + "/project/input/data.txt",
+ } {
+ got, err := CleanWriteFileIn(l, p)
+ require.NoError(t, err, p)
+ require.Equal(t, p, got)
+ }
+ // A host project may legitimately contain a sessions/name/input tree.
+ host := Layout{Origin: OriginHost, Root: Root}
+ require.Empty(t, host.ReadOnlyInputRoot(sibling.InputDir+"/data.txt"))
+ require.Empty(t, Remote().ReadOnlyInputRoot(sibling.InputDir+"/data.txt"))
+}
+
func TestCleanWorkDirIn(t *testing.T) {
remote := Remote()
got, err := CleanWorkDirIn(remote, "/opt/build", false)
@@ -57,14 +89,13 @@ func TestCleanWorkDirIn(t *testing.T) {
require.EqualError(t, err, `sandbox: work dir "rel" must be absolute`)
shared := userLayout(t)
- for _, ok := range []string{shared.Root, shared.Root + "/src", "/tmp", "/tmp/x", SkillsImageRoot + "/pdf"} {
+ for _, ok := range []string{shared.Root, "/workspace", "/workspace/sessions", "/tmp", "/opt", "/"} {
_, err := CleanWorkDirIn(shared, ok, false)
require.NoError(t, err, ok)
}
- for _, bad := range []string{"/workspace", "/workspace/sessions", "/opt", "/"} {
- _, err := CleanWorkDirIn(shared, bad, false)
- require.Error(t, err, bad)
- }
+ _, err = CleanWorkDirIn(shared, "/opt/build", true)
+ require.EqualError(t, err,
+ `sandbox: work dir "/opt/build" is outside allowed roots (`+shared.Root+`, /opt/weknora/tenant/skills)`)
}
func TestCleanInputPathIn(t *testing.T) {
diff --git a/website-docs/03-features/22-skills-sandbox.md b/website-docs/03-features/22-skills-sandbox.md
index b6d4a5bb8..287acb20f 100644
--- a/website-docs/03-features/22-skills-sandbox.md
+++ b/website-docs/03-features/22-skills-sandbox.md
@@ -152,7 +152,7 @@ macOS 桌面版可在「工具箱 → 技能管理」将技能安装到「本机
| 方式 | 何时使用 | 会话看到什么 |
| --- | --- | --- |
| 每会话一台(默认) | 配置保持会话模式,或下面任一条件不满足 | 该会话独占一台沙箱,工作目录仍是 `/workspace` |
-| 同一用户共用一台 | 环境变量已开启,配置选了共用,且会话属于可共用的身份 | 同一位所有者、同一份配置上的会话共用一台沙箱。每个会话的目录是 `/workspace/sessions/<会话 ID>`,检查点仓库在 `/var/lib/weknora/sessions/<会话 ID>.git` |
+| 同一用户共用一台 | 环境变量已开启,配置选了共用,且会话属于可共用的身份 | 同一位所有者、同一份配置上的会话共用一台沙箱。每个会话的目录是 `/workspace/sessions/<12 位短名>`(会话 ID 的 SHA-256 前 12 位,例如 `c812e1edb644`),检查点仓库在 `/var/lib/weknora/sessions/<同一段>.git`。 |
切换只影响还没有用过沙箱的会话。已经钉住沙箱配置、已经有检查点,或分叉后还没完成首次准备的会话,继续用自己原来的那一台。
@@ -160,9 +160,8 @@ macOS 桌面版可在「工具箱 → 技能管理」将技能安装到「本机
共用一台时,设计上的风险(设计文档 §5.2.1)是:
-- 沙箱里的命令以 root 运行,同一台机器上的会话之间没有操作系统级的隔离。
-- 磁盘是共享的。工具会把读写限制在本会话目录里,但 root 命令不受这层限制。
-- 进程互相可见。
+- 沙箱里的命令以 root 运行,同一台机器上的会话之间没有操作系统级的隔离,工具也不会把读写限制在本会话目录里:本会话的 agent 可以访问这台机器上的其他目录,包括其他会话的目录。
+- 磁盘是共享的,进程互相可见。
- 一台机器上没有会话数量上限。
空置保留天数写在沙箱配置上。`0` 表示用默认的 7 天,也可以填 1 到 90。它从「这台机器上已经没有存活会话」开始算,到点后回收任务可以删掉这台机器。它不是机器的最短寿命,也不是会话至少保留这么久:还有会话在用时不会按这个天数拆机,未到天数也不会因为空置就提前删。