From 33e28520b78f2ff647a8710990eec980d47be9da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Fri, 4 Dec 2026 06:02:10 -0700 Subject: [PATCH] fix(mcp): read clone secrets and SSH user from the source VM A temporary clone made by session_create keeps no vm settings of its own, so vm_unlock on a clone always failed with "secret setting is empty" even though the source VM had a saved login password and AI access enabled. The SSH user was empty for the same reason: the clone has no settings and no copied .reims-go-ssh-user file, while access is granted through the owns-clone path. Record the source VM key in the temporary VM ownership marker and fall back to it when a clone has no value of its own. The fallback reads the single stored secret instead of copying it, so the password never multiplies across clones, nothing is left behind when a clone is disposed, and revoking AI access on the source removes the fallback immediately. Surface a clear localized error when no VM has a saved password. model: deepseek/deepseek-v4.1-flash agent: lead (DeepSeek Harness) --- .../clone-unlock-uses-source-settings.json | 7 + .../app/computer_use_clone_settings_test.go | 173 ++++++++++++++++++ internal/app/computer_use_host.go | 120 ++++++++++-- internal/i18n/catalog_gen.go | 2 + internal/plugin/manager.go | 2 +- internal/plugin/secret.go | 5 + locales/en-US/native.json | 1 + locales/zh-CN/native.json | 1 + 8 files changed, 294 insertions(+), 17 deletions(-) create mode 100644 changes/clone-unlock-uses-source-settings.json create mode 100644 internal/app/computer_use_clone_settings_test.go diff --git a/changes/clone-unlock-uses-source-settings.json b/changes/clone-unlock-uses-source-settings.json new file mode 100644 index 0000000..d088cf3 --- /dev/null +++ b/changes/clone-unlock-uses-source-settings.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Nwflower"], + "zh": "修复 MCP 临时克隆无法自动输入登录密码、SSH 用户名常为空的问题。克隆不保存自己的虚拟机设置,现在它读取 `login_password` 和 `username` 时会回退到来源虚拟机,且仅在来源虚拟机仍开启「允许 AI 访问」时生效;撤销来源的授权后克隆立即失去回退。密码不会复制进克隆,克隆销毁后不留存副本。虚拟机未保存登录密码时,解锁会提示去 MCP 服务设置里填写,而不是返回内部错误。", + "en": "Fix MCP temporary clones failing to type the login password and often reporting an empty SSH username. A clone keeps no VM settings of its own, so reads of `login_password` and `username` now fall back to the source VM, and only while the source still allows AI access; revoking access on the source removes the fallback immediately. The password is never copied into the clone, so disposing it leaves no copy behind. When a VM has no saved login password, unlock now asks you to set it in the MCP Service settings instead of returning an internal error." +} diff --git a/internal/app/computer_use_clone_settings_test.go b/internal/app/computer_use_clone_settings_test.go new file mode 100644 index 0000000..4292731 --- /dev/null +++ b/internal/app/computer_use_clone_settings_test.go @@ -0,0 +1,173 @@ +package app + +import ( + "context" + "errors" + "io" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/lifecycle" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/testutil/fakedriver" +) + +const cloneSourceSettingPlugin = "test.clone.agent" + +// newCloneSettingsEnv builds a host whose MCP clone reads its settings from a +// source VM. The plugin declares the same login_password/username/ +// allow_ai_access schema as reims.agent, scoped to the VM. +func newCloneSettingsEnv(t *testing.T) (*App, *plugin.Manager, driver.Driver) { + t.Helper() + cfg := config.Default() + cfg.DataRoot = t.TempDir() + mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: cfg.DataRoot, HostVersion: "0.0.0"}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(mgr.Close) + if err := mgr.Registry().Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ + ID: cloneSourceSettingPlugin, + Version: "1.0.0", + Name: plugin.LocalizedText{EnUS: cloneSourceSettingPlugin}, + Settings: &plugin.SettingsSchema{ + Scope: "vm", + Properties: map[string]plugin.SettingProperty{ + "allow_ai_access": {Type: "boolean"}, + "username": {Type: "string"}, + "login_password": {Type: "string", Secret: true}, + }, + }, + }, + Source: plugin.SourceBuiltin, + Desired: true, + Activate: func(_ context.Context, _ *plugin.Scope) error { + return nil + }, + }); err != nil { + t.Fatal(err) + } + mgr.Registry().Reconcile(context.Background()) + + h := fakedriver.NewHarness(t) + drv := h.Add("hosted", "test.clone.driver", "test.driver.clone") + + app := &App{ + cfg: cfg, + pluginMgr: mgr, + transitions: map[string]string{}, + pendingChanges: map[string][]PendingChange{}, + pollWake: make(chan struct{}, 1), + diskPaths: map[string]cachedDiskPath{}, + procSamples: map[string]host.ProcessSample{}, + driverRouter: h.Router, + vmStateTable: h.States, + lifecycleSvc: lifecycle.New(h.Registry, h.Router, nil), + } + return app, mgr, drv +} + +func createVMs(t *testing.T, drv driver.Driver, names ...string) { + t.Helper() + for _, name := range names { + if err := drv.Create(context.Background(), driver.CreateRequest{DriverID: drv.ID(), Name: name}, io.Discard, io.Discard); err != nil { + t.Fatal(err) + } + } +} + +func TestCloneSecretFallsBackToAuthorizedSource(t *testing.T) { + app, mgr, drv := newCloneSettingsEnv(t) + createVMs(t, drv, "source", "__agent-clone") + sourceKey := driver.NewVMRef(drv.ID(), "source").Key() + cloneKey := driver.NewVMRef(drv.ID(), "__agent-clone").Key() + + if err := mgr.SetSettings(cloneSourceSettingPlugin, sourceKey, map[string]any{ + "allow_ai_access": true, + "username": "macuser", + "login_password": "secret-from-source", + }); err != nil { + t.Fatal(err) + } + + cloneVM, err := app.resolveVMInfo(drv.ID(), "__agent-clone") + if err != nil { + t.Fatal(err) + } + if err := writeComputerUseOwnership(cloneVM.Directory, cloneSourceSettingPlugin, cloneKey, sourceKey); err != nil { + t.Fatal(err) + } + + got, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password") + if err != nil { + t.Fatalf("clone should borrow the source password: %v", err) + } + if got != "secret-from-source" { + t.Fatalf("clone secret = %q, want the source value", got) + } + if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "macuser" { + t.Fatalf("clone SSH user = %q, want the source user", user) + } + + // The clone's own value wins over the source. + if err := mgr.SetSettings(cloneSourceSettingPlugin, cloneKey, map[string]any{ + "allow_ai_access": true, + "username": "cloneuser", + "login_password": "clone-own-password", + }); err != nil { + t.Fatal(err) + } + got, err = app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password") + if err != nil || got != "clone-own-password" { + t.Fatalf("clone own secret = %q (%v), want its own value", got, err) + } + if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "cloneuser" { + t.Fatalf("clone SSH user = %q, want its own value", user) + } + + // Clearing the clone's own password and revoking access on the source + // removes the fallback again. + if err := mgr.SetSettings(cloneSourceSettingPlugin, cloneKey, map[string]any{"login_password": ""}); err != nil { + t.Fatal(err) + } + if err := mgr.SetSettings(cloneSourceSettingPlugin, sourceKey, map[string]any{"allow_ai_access": false}); err != nil { + t.Fatal(err) + } + if _, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password"); !errors.Is(err, plugin.ErrSecretEmpty) { + t.Fatalf("revoked source should leave no fallback, got %v", err) + } + if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "cloneuser" { + t.Fatalf("clone keeps its own SSH user after source revoke, got %q", user) + } +} + +func TestCloneSecretWithoutSourceStaysEmpty(t *testing.T) { + app, mgr, drv := newCloneSettingsEnv(t) + createVMs(t, drv, "__agent-orphan") + cloneVM, err := app.resolveVMInfo(drv.ID(), "__agent-orphan") + if err != nil { + t.Fatal(err) + } + // A marker with no source (the lost-marker repair path) has no fallback. + if err := writeComputerUseOwnership(cloneVM.Directory, cloneSourceSettingPlugin, cloneVM.Ref().Key(), ""); err != nil { + t.Fatal(err) + } + if _, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password"); !errors.Is(err, plugin.ErrSecretEmpty) { + t.Fatalf("clone without a source should have no fallback, got %v", err) + } +} + +func TestSecretMissingMessageLocalized(t *testing.T) { + const key = "err.computer_use.secret_missing" + for _, loc := range []i18n.Locale{i18n.ZhCN, i18n.EnUS} { + msg := strings.TrimSpace(i18n.M(loc, key, nil)) + if msg == "" || msg == key { + t.Fatalf("%s %q did not resolve", loc, key) + } + } +} diff --git a/internal/app/computer_use_host.go b/internal/app/computer_use_host.go index d04940b..f10c02f 100644 --- a/internal/app/computer_use_host.go +++ b/internal/app/computer_use_host.go @@ -35,6 +35,11 @@ type computerUseOwnership struct { Version int `json:"version"` PluginID string `json:"plugin_id"` VMKey string `json:"vm_key"` + // SourceVM is the driver-qualified key of the VM the clone was taken from. + // A clone has no vm settings of its own (login password, SSH user), so + // secret and username lookups fall back to the source while it is still + // authorized. Older markers omit it and simply have no fallback. + SourceVM string `json:"source_vm,omitempty"` } func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler { @@ -94,8 +99,11 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa if mgr == nil { return nil, errors.New("plugin manager is unavailable") } - secret, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), req.Setting) + secret, err := a.computerUseSecretSetting(mgr, pluginID, vm, req.Setting) if err != nil { + if errors.Is(err, plugin.ErrSecretEmpty) { + return nil, a.computerUseHostError("secret_missing", "err.computer_use.secret_missing", i18n.Vars{"name": vm.Name}) + } return nil, err } defer func() { secret = "" }() @@ -175,14 +183,7 @@ func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID view["capabilities"] = append([]string(nil), vm.Capabilities...) } if accessEnabled { - username := a.GetVMSSHUser(vm.DriverID, vm.Name) - if mgr != nil { - settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false) - if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" { - username = strings.TrimSpace(configured) - } - } - if username != "" { + if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" { view["ssh_username"] = username } } @@ -278,7 +279,7 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage, return nil, err } cloneRef := cloned.Ref() - err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key()) + err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key(), vm.Ref().Key()) if err != nil { if cleanupErr := a.DeleteVM(vm.DriverID, cloneName, false); cleanupErr != nil { return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr)) @@ -513,14 +514,15 @@ func (a *App) forgetComputerUseOwnedVM(vmKey string) { } } -func writeComputerUseOwnership(vmDir, pluginID, vmKey string) error { +func writeComputerUseOwnership(vmDir, pluginID, vmKey, sourceVM string) error { vmDir = strings.TrimSpace(vmDir) pluginID = strings.TrimSpace(pluginID) vmKey = strings.TrimSpace(vmKey) + sourceVM = strings.TrimSpace(sourceVM) if vmDir == "" || pluginID == "" || vmKey == "" { return errors.New("temporary VM ownership metadata is incomplete") } - data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey}) + data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey, SourceVM: sourceVM}) if err != nil { return err } @@ -612,15 +614,15 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error { return errors.Join(cleanupErrors...) } -func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey string) error { +func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey, sourceVM string) error { if vm.Directory == "" { return errors.New("temporary clone directory is unavailable") } - if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey); err != nil { + if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey, sourceVM); err != nil { return err } marker, ok := readComputerUseOwnership(vm) - if !ok || marker.PluginID != pluginID { + if !ok || marker.PluginID != pluginID || marker.SourceVM != strings.TrimSpace(sourceVM) { return errors.New("temporary VM ownership marker could not be verified") } return nil @@ -647,7 +649,9 @@ func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) { } a.mu.Unlock() for _, pluginID := range pluginIDs { - if err := writeComputerUseOwnership(vm.Directory, pluginID, key); err == nil { + // The source VM is no longer known on this repair path (the marker + // was lost), so write an empty source: no fallback, same as before. + if err := writeComputerUseOwnership(vm.Directory, pluginID, key, ""); err == nil { break } } @@ -685,6 +689,90 @@ func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) boo return mgr.SavedBoolSetting(pluginID, vmKey, computerUseAccessSetting) } +// computerUseSourceVM returns the driver-qualified key of the VM a temporary +// clone was taken from, or "" when the clone records no usable source. Only +// MCP-owned clones carry an ownership marker, so any other VM has no fallback. +func (a *App) computerUseSourceVM(vm driver.VMInfo) string { + marker, ok := readComputerUseOwnership(vm) + if !ok { + return "" + } + source := strings.TrimSpace(marker.SourceVM) + if source == "" || source == vm.Ref().Key() { + return "" + } + normalized, ok := driver.ParseVMRef(source) + if !ok { + return "" + } + return normalized.Key() +} + +// computerUseSecretSetting reads one secret for a VM. A temporary clone owns no +// vm settings, so a value it does not have falls back to the source VM's copy +// while that source still allows MCP access. The fallback reads the single +// stored secret instead of copying it, so revoking access to the source also +// revokes it for its clones and no secret is left behind when a clone is +// disposed. A source that no longer exists resolves to nothing. +func (a *App) computerUseSecretSetting(mgr *plugin.Manager, pluginID string, vm driver.VMInfo, key string) (string, error) { + value, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), key) + if err == nil { + return value, nil + } + if !errors.Is(err, plugin.ErrSecretEmpty) { + return "", err + } + sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm) + if !ok { + return "", err + } + return mgr.SecretSetting(pluginID, sourceVM.Ref().Key(), key) +} + +// computerUseAuthorizedSource resolves a clone's source VM and confirms the +// source still grants MCP access. It reports false when the clone has no +// recorded source, the source is gone, or access to the source was revoked. +func (a *App) computerUseAuthorizedSource(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) (driver.VMInfo, bool) { + source := a.computerUseSourceVM(vm) + if source == "" || !computerUseVMAccessEnabled(mgr, pluginID, source) { + return driver.VMInfo{}, false + } + ref, ok := driver.ParseVMRef(source) + if !ok { + return driver.VMInfo{}, false + } + sourceVM, err := a.resolveVMInfo(ref.DriverID, ref.Name) + if err != nil { + return driver.VMInfo{}, false + } + return sourceVM, true +} + +// computerUseSSHUser resolves the SSH login name for a VM. A temporary clone +// has neither its own settings nor a copied .reims-go-ssh-user file, so it +// borrows the source's user while the source still allows MCP access. +func (a *App) computerUseSSHUser(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string { + if username := a.sshUserForVM(mgr, pluginID, vm); username != "" { + return username + } + sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm) + if !ok { + return "" + } + return a.sshUserForVM(mgr, pluginID, sourceVM) +} + +func (a *App) sshUserForVM(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string { + username := a.GetVMSSHUser(vm.DriverID, vm.Name) + if mgr != nil { + settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false) + if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" { + username = strings.TrimSpace(configured) + } + } + return strings.TrimSpace(username) +} + // resolveComputerUseVMInfo accepts the bare VM name used by the UI and the // canonical driverID:name reference returned by the VM list and resource APIs. func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) { diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index c52e91a..8090cb9 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -162,6 +162,7 @@ var catalog = map[Locale]map[string]string{ "err.computer_use.phase.recovery": "恢复模式", "err.computer_use.phase_confirmation": "虚拟机 {name} 处于 {phase} 阶段,操作需要先在 Reims-Go 中确认", "err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照", + "err.computer_use.secret_missing": "该虚拟机未保存登录密码,无法自动输入。请在 Reims-Go 的 MCP 服务设置中填写 macOS 登录密码后重试。", "err.computer_use.unavailable": "虚拟机交互服务当前不可用", "err.computer_use.unsupported_driver": "当前虚拟机驱动不支持虚拟机交互", "err.computer_use.vm_not_running": "虚拟机 {name} 未运行", @@ -864,6 +865,7 @@ var catalog = map[Locale]map[string]string{ "err.computer_use.phase.recovery": "Recovery mode", "err.computer_use.phase_confirmation": "VM {name} is in the {phase} phase and requires confirmation in Reims-Go", "err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}", + "err.computer_use.secret_missing": "This VM has no saved login password, so it cannot be typed automatically. Set the macOS login password in the Reims-Go MCP Service settings and try again.", "err.computer_use.unavailable": "The virtual machine interaction service is currently unavailable", "err.computer_use.unsupported_driver": "The selected VM driver does not support computer use", "err.computer_use.vm_not_running": "VM {name} is not running", diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index da64815..6c08679 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -1153,7 +1153,7 @@ func (m *Manager) SecretSetting(pluginID, vmName, key string) (string, error) { text, _ := values[key].(string) m.mu.RUnlock() if text == "" { - return "", errors.New("secret setting is empty") + return "", ErrSecretEmpty } if strings.HasPrefix(text, protectedSecretPrefix) { return unprotectSettingSecret(text) diff --git a/internal/plugin/secret.go b/internal/plugin/secret.go index 04013b0..6cd60e2 100644 --- a/internal/plugin/secret.go +++ b/internal/plugin/secret.go @@ -10,6 +10,11 @@ const protectedSecretPrefix = "dpapi:v1:" var ErrSecretNotProtected = errors.New("stored secret is not protected") +// ErrSecretEmpty marks a secret setting that was never saved for the requested +// scope. Callers that may fall back to another VM (a temporary clone reading +// its source) match it with errors.Is instead of comparing text. +var ErrSecretEmpty = errors.New("secret setting is empty") + func protectSettingSecret(value string) (string, error) { if value == "" || strings.HasPrefix(value, protectedSecretPrefix) { return value, nil diff --git a/locales/en-US/native.json b/locales/en-US/native.json index e68fced..fd0438e 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -309,6 +309,7 @@ "err.computer_use.phase.recovery": "Recovery mode", "err.computer_use.access_disabled": "MCP access to VM {name} is disabled in plugin settings", "err.computer_use.not_owned": "VM {name} is not an MCP-created temporary clone", + "err.computer_use.secret_missing": "This VM has no saved login password, so it cannot be typed automatically. Set the macOS login password in the Reims-Go MCP Service settings and try again.", "err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}", "err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen", "err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index 5b6240e..fd8026b 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -309,6 +309,7 @@ "err.computer_use.phase.recovery": "恢复模式", "err.computer_use.access_disabled": "MCP 插件在设置中无权访问虚拟机 {name}", "err.computer_use.not_owned": "虚拟机 {name} 不是 MCP 创建的临时克隆", + "err.computer_use.secret_missing": "该虚拟机未保存登录密码,无法自动输入。请在 Reims-Go 的 MCP 服务设置中填写 macOS 登录密码后重试。", "err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照", "err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏", "err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机",