From 7f11b7b5b9bb16f6775cfa5ff2301b94c699a406 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Mon, 24 Aug 2026 15:44:45 +0800 Subject: [PATCH] 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. --- .../application/repository/tenant_skill.go | 6 ++-- .../repository/tenant_skill_test.go | 35 +++++++++++++++++- .../service/tenant_sandbox_config_test.go | 26 ++++++++++++++ internal/sandbox/cube_remote_client.go | 12 ++++--- internal/sandbox/e2b_remote_client.go | 12 ++++--- internal/sandbox/remote_client.go | 8 +++++ internal/sandbox/remote_sandbox_test.go | 4 +-- internal/sandbox/remote_snapshot_test.go | 10 ++++++ internal/sandbox/sandbox.go | 5 ++- internal/sandbox/session_manager.go | 3 ++ internal/sandbox/session_manager_test.go | 12 ++++--- internal/sandbox/skill_paths.go | 36 +++++++++++++++---- internal/sandbox/skill_paths_test.go | 32 +++++++++++++++-- internal/types/config_redaction.go | 11 ++++++ .../types/config_redaction_sandbox_test.go | 32 +++++++++++++++++ internal/types/tenant.go | 4 ++- 16 files changed, 216 insertions(+), 32 deletions(-) diff --git a/internal/application/repository/tenant_skill.go b/internal/application/repository/tenant_skill.go index d464f9a7..65bb2e74 100644 --- a/internal/application/repository/tenant_skill.go +++ b/internal/application/repository/tenant_skill.go @@ -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 } diff --git a/internal/application/repository/tenant_skill_test.go b/internal/application/repository/tenant_skill_test.go index ecb0ca38..da320c11 100644 --- a/internal/application/repository/tenant_skill_test.go +++ b/internal/application/repository/tenant_skill_test.go @@ -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) +} diff --git a/internal/application/service/tenant_sandbox_config_test.go b/internal/application/service/tenant_sandbox_config_test.go index ef1fb15e..043395a1 100644 --- a/internal/application/service/tenant_sandbox_config_test.go +++ b/internal/application/service/tenant_sandbox_config_test.go @@ -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) { diff --git a/internal/sandbox/cube_remote_client.go b/internal/sandbox/cube_remote_client.go index ed9a7dbc..984714d8 100644 --- a/internal/sandbox/cube_remote_client.go +++ b/internal/sandbox/cube_remote_client.go @@ -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 } } diff --git a/internal/sandbox/e2b_remote_client.go b/internal/sandbox/e2b_remote_client.go index d16ffd6f..d937cc34 100644 --- a/internal/sandbox/e2b_remote_client.go +++ b/internal/sandbox/e2b_remote_client.go @@ -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 } } diff --git a/internal/sandbox/remote_client.go b/internal/sandbox/remote_client.go index b6ae1885..bc2a7641 100644 --- a/internal/sandbox/remote_client.go +++ b/internal/sandbox/remote_client.go @@ -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 } diff --git a/internal/sandbox/remote_sandbox_test.go b/internal/sandbox/remote_sandbox_test.go index c66d0765..29ec2ee6 100644 --- a/internal/sandbox/remote_sandbox_test.go +++ b/internal/sandbox/remote_sandbox_test.go @@ -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", }) diff --git a/internal/sandbox/remote_snapshot_test.go b/internal/sandbox/remote_snapshot_test.go index 8fabba23..e4bd8d69 100644 --- a/internal/sandbox/remote_snapshot_test.go +++ b/internal/sandbox/remote_snapshot_test.go @@ -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) { diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index ed683aad..70bdeeb4 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -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 } diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.go index 91824635..c87b3e33 100644 --- a/internal/sandbox/session_manager.go +++ b/internal/sandbox/session_manager.go @@ -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 } diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.go index cc011235..351a86c8 100644 --- a/internal/sandbox/session_manager_test.go +++ b/internal/sandbox/session_manager_test.go @@ -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) { diff --git a/internal/sandbox/skill_paths.go b/internal/sandbox/skill_paths.go index f29278a8..b31f30bd 100644 --- a/internal/sandbox/skill_paths.go +++ b/internal/sandbox/skill_paths.go @@ -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} diff --git a/internal/sandbox/skill_paths_test.go b/internal/sandbox/skill_paths_test.go index dcb58b91..c4f92f15 100644 --- a/internal/sandbox/skill_paths_test.go +++ b/internal/sandbox/skill_paths_test.go @@ -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) { diff --git a/internal/types/config_redaction.go b/internal/types/config_redaction.go index 5636961a..ab7c6645 100644 --- a/internal/types/config_redaction.go +++ b/internal/types/config_redaction.go @@ -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 } diff --git a/internal/types/config_redaction_sandbox_test.go b/internal/types/config_redaction_sandbox_test.go index f7022da8..8d1ec098 100644 --- a/internal/types/config_redaction_sandbox_test.go +++ b/internal/types/config_redaction_sandbox_test.go @@ -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{ diff --git a/internal/types/tenant.go b/internal/types/tenant.go index ce0251bf..35349290 100644 --- a/internal/types/tenant.go +++ b/internal/types/tenant.go @@ -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 决定)───