fix(sandbox): keep skill image pointer out of sandbox config PUT

The settings form rebuilds the payload without skill_image, so merge
must ignore client values or a save would drop the snapshot (and a
crafted PUT could plant one). Also reject skill names that escape
the image root and require SupportsSnapshots on the snapshot manager.
main
wizardchen 2026-08-24 15:44:45 +08:00 committed by lyingbug
parent 00fe035668
commit 7f11b7b5b9
16 changed files with 216 additions and 32 deletions

View File

@ -31,7 +31,7 @@ type TenantSkillRepository interface {
// CreateSnapshotRow records provider work before creating the billable snapshot.
CreateSnapshotRow(ctx context.Context, e *types.TenantSkillSnapshotEntity) error
// MarkSnapshotState updates ledger state and stores the provider snapshot ID once known.
MarkSnapshotState(ctx context.Context, id, state, snapshotID string) error
MarkSnapshotState(ctx context.Context, tenantID uint64, id, state, snapshotID string) error
// ListSnapshotsByConfig returns the full chain for audit and troubleshooting.
ListSnapshotsByConfig(ctx context.Context, tenantID uint64, configID string) ([]*types.TenantSkillSnapshotEntity, error)
// DeleteSnapshotRowsByConfig removes ledger rows only when an entire sandbox
@ -150,7 +150,7 @@ func (r *tenantSkillRepository) CreateSnapshotRow(
// MarkSnapshotState moves a ledger row and, when the snapshot has just been
// created, records its provider-side ID.
func (r *tenantSkillRepository) MarkSnapshotState(
ctx context.Context, id, state, snapshotID string,
ctx context.Context, tenantID uint64, id, state, snapshotID string,
) error {
updates := map[string]any{"state": state, "updated_at": time.Now()}
if snapshotID != "" {
@ -162,7 +162,7 @@ func (r *tenantSkillRepository) MarkSnapshotState(
}
return r.db.WithContext(ctx).
Model(&types.TenantSkillSnapshotEntity{}).
Where("id = ?", id).
Where("tenant_id = ? AND id = ?", tenantID, id).
Updates(updates).Error
}

View File

@ -81,7 +81,7 @@ func TestSnapshotLedgerRecordsChain(t *testing.T) {
State: types.SkillSnapshotStateBuilding,
}))
require.NoError(t, repo.MarkSnapshotState(ctx, "ins-1", types.SkillSnapshotStateActive, "snap-1"))
require.NoError(t, repo.MarkSnapshotState(ctx, 7, "ins-1", types.SkillSnapshotStateActive, "snap-1"))
rows, err := repo.ListSnapshotsByConfig(ctx, 7, "cfg-1")
require.NoError(t, err)
@ -127,3 +127,36 @@ func TestListStaleInstallingFindsAbandonedRuns(t *testing.T) {
ids := []string{stale[0].ID, stale[1].ID}
require.ElementsMatch(t, []string{"sk-old-install", "sk-old-remove"}, ids)
}
func TestSkillRepoSoftDeleteAllowsNameReuse(t *testing.T) {
repo := newSkillTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-a", "cfg-1", "pdf")))
require.NoError(t, repo.DeleteSkill(ctx, 7, "cfg-1", "sk-a"))
require.NoError(t, repo.CreateSkill(ctx, skillRow("sk-b", "cfg-1", "pdf")),
"a soft-deleted name must be reusable for an in-place reinstall")
got, err := repo.GetSkillByName(ctx, 7, "cfg-1", "pdf")
require.NoError(t, err)
require.Equal(t, "sk-b", got.ID)
}
func TestMarkSnapshotStateIsTenantScoped(t *testing.T) {
repo := newSkillTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.CreateSnapshotRow(ctx, &types.TenantSkillSnapshotEntity{
ID: "ins-1", TenantID: 7, SandboxConfigID: "cfg-1", SkillID: "sk-a",
ParentSnapshotID: "tpl-base", Generation: 1,
Trigger: types.SkillSnapshotTriggerInstall,
State: types.SkillSnapshotStateBuilding,
}))
require.NoError(t, repo.MarkSnapshotState(ctx, 8, "ins-1", types.SkillSnapshotStateActive, "snap-stolen"))
rows, err := repo.ListSnapshotsByConfig(ctx, 7, "cfg-1")
require.NoError(t, err)
require.Len(t, rows, 1)
require.Equal(t, types.SkillSnapshotStateBuilding, rows[0].State,
"a snapshot row must not move when the caller is a different tenant")
require.Empty(t, rows[0].SnapshotID)
}

View File

@ -816,6 +816,32 @@ func TestSanitizeSandboxConfigPreservesRedactedSecret(t *testing.T) {
require.Equal(t, "stored-key", out.E2B.APIKey)
}
func TestSanitizeSandboxConfigPreservesSkillImage(t *testing.T) {
t.Setenv("SYSTEM_AES_KEY", strings.Repeat("k", 32))
existing := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIKey: "stored-key", APIURL: "https://203.0.113.10", TemplateID: "t1",
},
SkillImage: &types.SkillImageConfig{SnapshotID: "snap-1", OwnerFingerprint: "fp-1"},
}
incoming := &types.TenantSandboxConfig{
SandboxType: "e2b",
E2B: &types.E2BSandboxConfig{
APIKey: types.RedactedSecretPlaceholder,
APIURL: "https://203.0.113.10",
TemplateID: "t1",
},
SkillImage: &types.SkillImageConfig{SnapshotID: "forged-snap"},
}
out, err := SanitizeSandboxConfig(incoming, existing)
require.NoError(t, err)
require.Equal(t, "snap-1", out.SkillImage.SnapshotID,
"the sandbox config API must not let a client plant or wipe the skill image")
}
// Nothing is inherited from the deployment, so an incomplete config has to be
// refused when it is saved rather than at the first sandbox allocation.
func TestSanitizeSandboxConfigRejectsIncompleteConfig(t *testing.T) {

View File

@ -706,6 +706,7 @@ func (c *CubeRemoteClient) ListSnapshots(
var (
out []RemoteSnapshotRef
token string
seen = map[string]struct{}{"": {}}
)
for {
page, next, err := c.client.ListSnapshots(ctx, cubesandbox.ListSnapshotsOptions{
@ -722,13 +723,14 @@ func (c *CubeRemoteClient) ListSnapshots(
if next == "" {
return out, nil
}
// A provider/SDK bug that echoes the same non-empty pagination token
// would otherwise spin forever and block skill-image orphan cleanup.
// Fail fast instead of hanging until the context is cancelled.
if next == token {
// A provider/SDK bug that repeats a pagination token (the same one,
// or a cycle A→B→A) would otherwise spin forever and block skill-
// image orphan cleanup. Fail fast instead of hanging until cancel.
if _, dup := seen[next]; dup {
return nil, cubeInvalidRequest("ListSnapshots",
"provider returned the same pagination token", nil)
"provider returned a repeated pagination token", nil)
}
seen[next] = struct{}{}
token = next
}
}

View File

@ -996,6 +996,7 @@ func (c *E2BRemoteClient) ListSnapshots(
var (
out []RemoteSnapshotRef
token string
seen = map[string]struct{}{"": {}}
)
for {
options := append([]e2b.ListSnapshotsOption(nil), baseOptions...)
@ -1021,13 +1022,14 @@ func (c *E2BRemoteClient) ListSnapshots(
if page.NextToken == "" {
return out, nil
}
// A provider/SDK bug that echoes the same non-empty pagination token
// would otherwise spin forever and block skill-image orphan cleanup.
// Fail fast instead of hanging until the context is cancelled.
if page.NextToken == token {
// A provider/SDK bug that repeats a pagination token (the same one,
// or a cycle A→B→A) would otherwise spin forever and block skill-
// image orphan cleanup. Fail fast instead of hanging until cancel.
if _, dup := seen[page.NextToken]; dup {
return nil, e2bInvalidRequest("ListSnapshots",
"provider returned the same pagination token", nil)
"provider returned a repeated pagination token", nil)
}
seen[page.NextToken] = struct{}{}
token = page.NextToken
}
}

View File

@ -446,6 +446,11 @@ type RemoteSnapshotManager interface {
// SnapshotManagerFrom narrows a client to its snapshot capability. It returns
// false for providers that cannot snapshot (docker/local), so callers can fall
// back to the base template instead of failing.
//
// Both signals must agree: the type assertion finds the methods, and
// SupportsSnapshots is the advertised capability. A wrapper that happens to
// embed snapshot methods must not be treated as snapshot-capable when the
// flag is off.
func SnapshotManagerFrom(client RemoteSandboxClient) (RemoteSnapshotManager, bool) {
if client == nil {
return nil, false
@ -454,5 +459,8 @@ func SnapshotManagerFrom(client RemoteSandboxClient) (RemoteSnapshotManager, boo
if !ok {
return nil, false
}
if !client.Capabilities().SupportsSnapshots {
return nil, false
}
return mgr, true
}

View File

@ -14,7 +14,7 @@ func TestExecuteOnHandleRunsRemoteScriptWithoutUploading(t *testing.T) {
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
skillDir := SkillDirFor("sk-1")
skillDir := mustSkillDir(t, "sk-1")
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: skillDir + "/scripts/run.py",
Args: []string{"--flag"},
@ -42,7 +42,7 @@ func TestExecuteOnHandleNestedRemoteScriptUsesSkillRootVenv(t *testing.T) {
handle, err := client.Create(ctx, RemoteCreateRequest{TemplateID: "tpl"})
require.NoError(t, err)
skillDir := SkillDirFor("sk-1")
skillDir := mustSkillDir(t, "sk-1")
_, err = sb.ExecuteOnHandle(ctx, handle, &ExecuteConfig{
RemoteScriptPath: skillDir + "/scripts/tools/run.py",
})

View File

@ -26,6 +26,16 @@ func TestSnapshotManagerFromDetectsCapability(t *testing.T) {
require.False(t, ok)
require.Nil(t, mgr)
})
t.Run("interface without SupportsSnapshots is rejected", func(t *testing.T) {
client := newFakeRemoteClient(SandboxTypeCube)
client.capabilities.SupportsSnapshots = false
mgr, ok := SnapshotManagerFrom(client)
require.False(t, ok, "embedding snapshot methods must not override a false capability flag")
require.Nil(t, mgr)
})
}
func TestFakeSnapshotRoundTrip(t *testing.T) {

View File

@ -182,7 +182,10 @@ type ExecuteConfig struct {
// RemoteScriptPath is an absolute path to a script that already exists
// inside the sandbox image (installed skills). When set, the executor
// skips the upload step and runs it in place.
// skips the upload step and runs it in place. Only paths under a valid
// skill directory in SkillsImageRoot are accepted; script-content
// validation is skipped because the file is already on the image, so
// callers must have vetted the bundle at install time.
RemoteScriptPath string
}

View File

@ -522,9 +522,12 @@ type ShellExecOptions struct {
// AllowSkillsRoot lets installer calls work inside the skills image root.
// 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 is reserved for install/maintenance commands that need to write
// outside /workspace; ordinary sessions must keep the provider default user.
// Never set this from a model-authored tool such as shell_exec: root inside
// the sandbox bypasses file-mode isolation on the image.
AsRoot bool
}

View File

@ -134,12 +134,13 @@ func TestSessionBoundManagerShellExecRunsAsSandboxUser(t *testing.T) {
}
func TestCleanSessionWorkDirRejectsSkillRootByDefault(t *testing.T) {
_, err := cleanSessionWorkDir(SkillDirFor("sk-1"), false)
skillDir := mustSkillDir(t, "sk-1")
_, err := cleanSessionWorkDir(skillDir, false)
require.Error(t, err, "ordinary sessions must stay inside /workspace")
got, err := cleanSessionWorkDir(SkillDirFor("sk-1"), true)
got, err := cleanSessionWorkDir(skillDir, true)
require.NoError(t, err, "install sessions need to work inside the skills root")
require.Equal(t, SkillDirFor("sk-1"), got)
require.Equal(t, skillDir, got)
}
func TestCleanSessionWorkDirStillRejectsArbitraryPathsInInstallMode(t *testing.T) {
@ -157,15 +158,16 @@ func TestExecShellCommandWithOptionsRunsAsRootOnlyWhenAsked(t *testing.T) {
require.Equal(t, DefaultSandboxExecUser, last.User,
"ordinary shell_exec must stay on the non-root sandbox account")
skillDir := mustSkillDir(t, "sk-1")
_, err = mgr.ExecShellCommandWithOptions(ctx, "sess-1", "echo hi", ShellExecOptions{
AsRoot: true,
AllowSkillsRoot: true,
WorkDir: SkillDirFor("sk-1"),
WorkDir: skillDir,
})
require.NoError(t, err)
last = lastExecRequest(t, client)
require.Equal(t, "root", last.User)
require.Equal(t, SkillDirFor("sk-1"), last.WorkDir)
require.Equal(t, skillDir, last.WorkDir)
}
func TestExecShellCommandKeepsOrdinaryRemoteRequest(t *testing.T) {

View File

@ -1,6 +1,7 @@
package sandbox
import (
"errors"
"fmt"
"path"
"strings"
@ -19,12 +20,33 @@ const (
const skillShellArgv0 = "weknora-skill"
// ErrInvalidSkillName is returned when a skill name would escape SkillsImageRoot
// or is not a single path segment.
var ErrInvalidSkillName = errors.New("sandbox: invalid skill name")
// IsValidSkillName reports whether name is a single directory segment under
// SkillsImageRoot. Empty names, "." / "..", and anything containing a path
// separator are rejected so install/exec cannot walk out of the skills root.
func IsValidSkillName(name string) bool {
name = strings.TrimSpace(name)
if name == "" || name == "." || name == ".." {
return false
}
if strings.ContainsAny(name, "/\\\x00") {
return false
}
return path.Base(path.Clean(name)) == name
}
// SkillDirFor returns the image directory of a skill. The key is the skill
// name from SKILL.md: that is what the installer writes, and what the agent
// is told to execute. The database id stays a row key and is not part of
// the path.
func SkillDirFor(skillName string) string {
return path.Join(SkillsImageRoot, skillName)
func SkillDirFor(skillName string) (string, error) {
if !IsValidSkillName(skillName) {
return "", fmt.Errorf("%w %q", ErrInvalidSkillName, skillName)
}
return path.Join(SkillsImageRoot, skillName), nil
}
// SkillDirForImageScript returns the owning skill directory for an image script.
@ -40,7 +62,7 @@ func SkillDirForImageScript(scriptPath string) (string, bool) {
rest := strings.TrimPrefix(cleanScript, prefix)
parts := strings.SplitN(rest, "/", 2)
if len(parts) != 2 || parts[0] == "" {
if len(parts) != 2 || parts[0] == "" || !IsValidSkillName(parts[0]) {
return "", false
}
return path.Join(cleanRoot, parts[0]), true
@ -56,17 +78,17 @@ func SkillDirForImageScript(scriptPath string) (string, bool) {
// sandbox with a shell conditional instead of an extra round trip to stat the
// path, because the extra Exec would double the latency of every skill call.
func SkillInterpreterCommand(skillDir, scriptPath string) (string, []string) {
switch {
case strings.HasSuffix(scriptPath, ".py"):
switch strings.ToLower(path.Ext(scriptPath)) {
case ".py":
venvPython := path.Join(skillDir, ".venv", "bin", "python")
script := shellQuote(scriptPath)
return "/bin/sh", []string{"-c", fmt.Sprintf(
`if [ -x %s ]; then exec %s %s "$@"; else exec python3 %s "$@"; fi`,
shellQuote(venvPython), shellQuote(venvPython), script, script,
), skillShellArgv0}
case strings.HasSuffix(scriptPath, ".js"), strings.HasSuffix(scriptPath, ".mjs"):
case ".js", ".mjs":
return "node", []string{scriptPath}
case strings.HasSuffix(scriptPath, ".sh"):
case ".sh":
return "/bin/sh", []string{scriptPath}
default:
return "/bin/sh", []string{scriptPath}

View File

@ -10,7 +10,16 @@ import (
)
func TestSkillDirFor(t *testing.T) {
require.Equal(t, "/opt/weknora/tenant/skills/sk-1", SkillDirFor("sk-1"))
dir, err := SkillDirFor("sk-1")
require.NoError(t, err)
require.Equal(t, "/opt/weknora/tenant/skills/sk-1", dir)
}
func TestSkillDirForRejectsPathEscape(t *testing.T) {
for _, name := range []string{"", ".", "..", "../x", "foo/bar", `foo\bar`, "foo/../bar"} {
_, err := SkillDirFor(name)
require.ErrorIs(t, err, ErrInvalidSkillName, "name %q must not resolve under the skills root", name)
}
}
func TestSkillDirForImageScript(t *testing.T) {
@ -31,10 +40,16 @@ func TestSkillDirForImageScript(t *testing.T) {
require.False(t, ok)
require.Empty(t, skillDir)
})
t.Run("dot-dot after clean that leaves the skills root is rejected", func(t *testing.T) {
skillDir, ok := SkillDirForImageScript(SkillsImageRoot + "/../workspace/run.py")
require.False(t, ok)
require.Empty(t, skillDir)
})
}
func TestSkillInterpreterCommand(t *testing.T) {
dir := SkillDirFor("sk-1")
dir := mustSkillDir(t, "sk-1")
t.Run("python prefers the skill's own venv", func(t *testing.T) {
cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/run.py")
@ -64,6 +79,19 @@ func TestSkillInterpreterCommand(t *testing.T) {
require.Equal(t, "/bin/sh", cmd)
require.Equal(t, []string{dir + "/scripts/run"}, args)
})
t.Run("uppercase python extension still uses the venv", func(t *testing.T) {
cmd, args := SkillInterpreterCommand(dir, dir+"/scripts/run.PY")
require.Equal(t, "/bin/sh", cmd)
require.Contains(t, args[1], dir+"/.venv/bin/python")
})
}
func mustSkillDir(t *testing.T, name string) string {
t.Helper()
dir, err := SkillDirFor(name)
require.NoError(t, err)
return dir
}
func TestSkillInterpreterCommandPythonForwardsAllCallerArgs(t *testing.T) {

View File

@ -346,5 +346,16 @@ func MergeSandboxConfigForUpdate(incoming, existing *TenantSandboxConfig) *Tenan
out.EnvVars = envVars
}
// SkillImage is owned by the skill install/remove path, not the sandbox
// settings form. The editor rebuilds the payload without this field, and a
// crafted PUT must not plant or wipe a snapshot pointer. Copy from the
// stored row (or clear on create) and ignore whatever the client sent.
if existing != nil && existing.SkillImage != nil {
image := *existing.SkillImage
out.SkillImage = &image
} else {
out.SkillImage = nil
}
return &out
}

View File

@ -79,6 +79,38 @@ func TestMergeSandboxConfigForUpdateNilIncoming(t *testing.T) {
require.Nil(t, MergeSandboxConfigForUpdate(nil, &TenantSandboxConfig{}))
}
func TestMergeSandboxConfigForUpdatePreservesSkillImage(t *testing.T) {
existing := &TenantSandboxConfig{
E2B: &E2BSandboxConfig{APIKey: "old-e2b"},
SkillImage: &SkillImageConfig{SnapshotID: "snap-1", OwnerFingerprint: "fp-1", Generation: 3},
}
incoming := &TenantSandboxConfig{
E2B: &E2BSandboxConfig{APIKey: RedactedSecretPlaceholder},
SkillImage: &SkillImageConfig{SnapshotID: "forged-snap", OwnerFingerprint: "forged-fp"},
}
out := MergeSandboxConfigForUpdate(incoming, existing)
require.Equal(t, "snap-1", out.SkillImage.SnapshotID,
"a settings save must not replace the install-owned snapshot pointer")
require.Equal(t, "fp-1", out.SkillImage.OwnerFingerprint)
require.Equal(t, 3, out.SkillImage.Generation)
out.SkillImage.SnapshotID = "mutated"
require.Equal(t, "snap-1", existing.SkillImage.SnapshotID,
"merge must copy SkillImage so later mutation cannot touch the stored row")
}
func TestMergeSandboxConfigForUpdateIgnoresIncomingSkillImageOnCreate(t *testing.T) {
incoming := &TenantSandboxConfig{
E2B: &E2BSandboxConfig{APIKey: "new-e2b"},
SkillImage: &SkillImageConfig{SnapshotID: "forged-snap"},
}
out := MergeSandboxConfigForUpdate(incoming, nil)
require.Nil(t, out.SkillImage, "create must not accept a client-supplied skill image")
}
func TestMergeSandboxConfigForUpdateDoesNotMutateInputs(t *testing.T) {
existing := &TenantSandboxConfig{E2B: &E2BSandboxConfig{APIKey: "old-e2b"}}
incoming := &TenantSandboxConfig{

View File

@ -655,7 +655,9 @@ type TenantSandboxConfig struct {
VolumeMount *VolumeMountConfig `json:"volume_mount,omitempty"`
// SkillImage points at the snapshot that carries this config's installed
// skills. Empty means "use the base template".
// skills. Empty means "use the base template". Written only by the skill
// install/remove path: MergeSandboxConfigForUpdate ignores client values
// so a settings-form save cannot wipe or plant the pointer.
SkillImage *SkillImageConfig `json:"skill_image,omitempty"`
// ── 后端专属配置(同一时刻只有一个生效,由 SandboxType 决定)───