diff --git a/changes/host-guest-prereqs-a1-a2.json b/changes/host-guest-prereqs-a1-a2.json index 4b0204d..9b54b28 100644 --- a/changes/host-guest-prereqs-a1-a2.json +++ b/changes/host-guest-prereqs-a1-a2.json @@ -1,7 +1,7 @@ { "group": "new", "order": 0, - "authors": ["icaruszezen"], - "zh": "完整支持非 macOS 客体驱动宿主前置能力。客体驱动可按托管或进程树方式运行虚拟机,并上报状态、就绪情况、阶段、客体系统与访问入口;宿主新增统一控制台路由(支持 `driver/console.*`)、受 DPAPI 保护的虚拟机密钥物化与自动清理、受来源与重定向约束的后台代下载及关闭确认,以及基于内置隐藏提权子命令与桌面确认弹窗的白名单受控提权。插件契约升级为 `pluginApi 1.2` 和 `uiApi 2.1`,并公开 `pkg/drivertest` 契约测试套件([#74](https://github.com/Nwflower/Reims-Go/issues/74))。", - "en": "Complete host prerequisites for non-macOS guest drivers. Drivers can run VMs as hosted or process-tree instances and report state, readiness, phase, guest OS, and access endpoints; the host adds a unified console router (supporting `driver/console.*`), DPAPI-backed secret materialization with automatic cleanup, origin- and redirect-guarded host downloads with close confirmation, and whitelisted elevation via an embedded subcommand behind a host confirmation dialog and Windows UAC. The plugin contracts move to `pluginApi 1.2` and `uiApi 2.1`, and `pkg/drivertest` is public ([#74](https://github.com/Nwflower/Reims-Go/issues/74))." + "authors": ["icaruszezen", "Nwflower"], + "zh": "支持由插件接入非 macOS 虚拟机,可在客户端查看其状态,并通过 SSH、WSL、远程桌面、Hyper-V 连接或 ADB 打开。插件契约升级为 `pluginApi 1.2` 和 `uiApi 2.1`,并公开 `pkg/drivertest` 契约测试套件([#74](https://github.com/Nwflower/Reims-Go/issues/74))。", + "en": "Let plugins add non-macOS VMs, with their state shown in the app and access through SSH, WSL, Remote Desktop, VMConnect, or ADB. The plugin contracts move to `pluginApi 1.2` and `uiApi 2.1`, and the `pkg/drivertest` contract test suite is public ([#74](https://github.com/Nwflower/Reims-Go/issues/74))." } diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 81311e6..a3e520f 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -84,11 +84,11 @@ Sidecar 可通过宿主接口请求为指定虚拟机拉起进程,宿主以「 客体驱动可在清单中将 `consoleEndpoint` 设为 `driver`,并通过 `driver/console.screenshot`、`driver/console.pointer`、`driver/console.key` 与 `driver/console.type` 提供控制台能力。宿主统一控制台路由按驱动声明和虚拟机能力决定走 QMP 代理或驱动控制台,使缩略图、截屏、键入与代理控制共用同一套入口。 -客体驱动可通过 `host/secret.materialize` 委托宿主把受 Windows DPAPI 保护的敏感设置按模板(支持原样、XML 转义与 Base64 UTF-16LE)写入虚拟机目录内仅当前用户可读的文件。插件本身不接触明文,审计日志只记录设置名与字节长度;宿主持久化记录已物化路径,在插件调用 `host/secret.discard` 或用户删除虚拟机时先覆写清零再删除文件。 +客体驱动可通过 `host/secret.materialize` 委托宿主把受 Windows DPAPI 保护的敏感设置按模板(支持原样、XML 转义与 Base64 UTF-16LE)写入虚拟机目录内的新文件,文件权限沿用该目录。插件本身不接触明文,审计日志只记录设置名与字节长度;宿主持久化记录已物化路径,在插件调用 `host/secret.discard` 或用户删除虚拟机时先覆写清零再删除文件。 -插件可通过 `host/download.start` 与 `host/download.cancel` 委托宿主执行受 `net:` 权限约束的后台下载。宿主只放行已声明来源的 HTTPS 地址(测试用回环地址除外),校验哈希与重定向安全,禁止 HTTPS 降级为明文 HTTP 以及指向本机或私网地址的重定向,并限制落盘目录位于插件私有数据目录或该驱动声明的虚拟机根目录内。下载进度同步到桌面任务栏与 Sidecar 的 `download/progress` 通知;存在进行中的下载时,关闭主窗口会先弹出确认提示。 +插件可通过 `host/download.start` 与 `host/download.cancel` 委托宿主执行受 `net:` 权限约束的后台下载。宿主只放行已声明来源的 HTTPS 地址(测试用回环地址除外),要求提供并校验 SHA-256,检查重定向安全,禁止 HTTPS 降级为明文 HTTP 以及指向本机或私网地址的重定向,并限制落盘目录位于插件私有数据目录或该驱动声明的虚拟机根目录内。下载进度同步到桌面任务栏与 Sidecar 的 `download/progress` 通知;存在进行中的下载时,关闭主窗口会先弹出确认提示。 -客体驱动可通过 `host/elevate.request` 请求白名单内的 Windows 系统功能配置,当前仅支持启用 Hyper-V、将当前账户加入 Hyper-V Administrators 组与启用 Windows Sandbox。宿主先唤起主窗口并展示默认聚焦取消按钮的确认对话框,明确告知请求插件来源、操作内容、权限范围以及后续需要手动重启或重新登录,确认后才通过主程序内置的隐藏提权子命令拉起 Windows UAC。提权操作在无桌面窗口时直接拒绝,且绝不自动重启系统。 +客体驱动可通过 `host/elevate.request` 请求白名单内的 Windows 系统功能配置,当前仅支持启用 Hyper-V、将当前账户加入 Hyper-V Administrators 组与启用 Windows Sandbox。宿主先唤起主窗口并展示默认聚焦取消按钮的确认对话框,明确告知请求插件来源、操作内容、权限范围以及后续需要手动重启或重新登录,确认后才通过 Windows UAC 直接运行对应的系统工具。提权操作在无桌面窗口时直接拒绝,且绝不自动重启系统。 客体系统信息为结构化对象,`family` 取 `macos`、`linux`、`windows` 或 `android`,可附带发行版、版本与架构。界面据此显示客体图标,并在列表项与详情页上写入 `data-guest-family` 属性,供主题按客体类型定制外观。 diff --git a/internal/app/computer_use_host.go b/internal/app/computer_use_host.go index db1ea2d..7a0c461 100644 --- a/internal/app/computer_use_host.go +++ b/internal/app/computer_use_host.go @@ -422,10 +422,15 @@ func (a *App) resolveComputerUseVM(mgr *plugin.Manager, pluginID, ref string) (d if vm.Phase == "" { if pr, ok := a.driverFor(vm).(driver.PhaseReporter); ok { pctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - if phase, err := pr.Phase(pctx, vm.Name); err == nil { - vm.Phase = phase - } + phase, err := pr.Phase(pctx, vm.Name) cancel() + // Only a driver without `driver/phase` has no protected phases; any + // other failure must not pass for the normal phase. + var rpcErr *plugin.RPCError + if err != nil && !(errors.As(err, &rpcErr) && rpcErr.Code == plugin.RPCMethodNotFound) { + return driver.VMInfo{}, consoleRoute{}, fmt.Errorf("read the guest phase of %s: %w", vm.Name, err) + } + vm.Phase = phase } } if phase := computerUseVMPhase(vm); phase != "normal" { diff --git a/internal/app/console_router.go b/internal/app/console_router.go index 6e855fb..3d3f13e 100644 --- a/internal/app/console_router.go +++ b/internal/app/console_router.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "os" - "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/driver" @@ -98,23 +97,9 @@ func (a *App) consoleCaptureWithMode(ctx context.Context, route consoleRoute, ma cleanup() return "", "", nil, err } - if res.Path != "" && !strings.EqualFold(filepath.Clean(res.Path), filepath.Clean(path)) { - // A driver may pick its own frame file. Accept it only as a plain - // file inside the data folder or the system temp folder, and let - // it keep the file: only the host's unused temp file goes away. - a.mu.Lock() - dataRoot := "" - if a.cfg != nil { - dataRoot = a.cfg.DataRoot - } - a.mu.Unlock() - own := res.Path - if !pathInsideAny(own, dataRoot, os.TempDir()) { - cleanup() - return "", "", nil, fmt.Errorf("driver %q wrote its frame outside the folders the host allows", route.vm.DriverID) - } + if res.Path != "" && !samePath(res.Path, path) { cleanup() - path, cleanup = own, func() {} + return "", "", nil, fmt.Errorf("driver %q did not write its frame to the requested path", route.vm.DriverID) } format = strings.ToLower(strings.TrimSpace(res.Format)) switch format { diff --git a/internal/app/console_router_test.go b/internal/app/console_router_test.go index d6b41b9..f6639b5 100644 --- a/internal/app/console_router_test.go +++ b/internal/app/console_router_test.go @@ -184,21 +184,10 @@ func TestConsoleCaptureGuardsTheFramePathADriverReturns(t *testing.T) { } cleanup() - // A frame inside the data folder is accepted and kept by cleanup. + // Any other file is rejected, even one inside the data folder. own := filepath.Join(root, "own-frame.png") - path, _, cleanup, err := a.consoleCapture(ctx, route(&stubConsole{file: own, res: driver.ConsoleScreenshotResult{Path: own}}), 0) - if err != nil || path != own { - t.Fatalf("a frame inside the data folder = %q, %v", path, err) - } - cleanup() - if _, err := os.Stat(own); err != nil { - t.Fatal("cleanup deleted a frame the driver owns") - } - - // A frame outside every allowed folder is rejected. - outside := filepath.Join(filepath.VolumeName(os.TempDir())+string(os.PathSeparator), "reims-outside", "frame.png") - if _, _, _, err := a.consoleCapture(ctx, route(&stubConsole{res: driver.ConsoleScreenshotResult{Path: outside}}), 0); err == nil { - t.Fatal("a frame outside the allowed folders was accepted") + if _, _, _, err := a.consoleCapture(ctx, route(&stubConsole{file: own, res: driver.ConsoleScreenshotResult{Path: own}}), 0); err == nil { + t.Fatal("a frame at a path the driver chose was accepted") } // An unsupported frame format is rejected. @@ -225,14 +214,21 @@ func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *test t.Fatalf("phase %s: err = %v, want confirmation_required", phase, err) } } + // A phase the host cannot read must not pass for the normal one. + if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte("bogus"), 0o644); err != nil { + t.Fatal(err) + } + if _, _, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()); err == nil { + t.Fatal("a VM with an unreadable phase was treated as normal") + } } func TestComputerUsePhasePrefersTheDriverReportedPhase(t *testing.T) { for phase, want := range map[string]string{ - "": "normal", - driver.PhaseNormal: "normal", - driver.PhaseInstaller: "installer", - driver.PhaseRecovery: "recovery", + "": "normal", + driver.PhaseNormal: "normal", + driver.PhaseInstaller: "installer", + driver.PhaseRecovery: "recovery", } { if got := computerUseVMPhase(driver.VMInfo{Phase: phase}); got != want { t.Errorf("phase %q -> %q, want %q", phase, got, want) diff --git a/internal/app/download_host_flow.go b/internal/app/download_host_flow.go index f28abd7..7177bae 100644 --- a/internal/app/download_host_flow.go +++ b/internal/app/download_host_flow.go @@ -210,66 +210,6 @@ func resolveExpectedSum(ctx context.Context, client *http.Client, sumsURL, name return "", fmt.Errorf("the checksum document has no entry for %s", name) } -type progressWriter struct { - w io.Writer - done int64 - total int64 - fn func(done, total int64) -} - -func (p *progressWriter) Write(b []byte) (int, error) { - n, err := p.w.Write(b) - p.done += int64(n) - if p.fn != nil { - p.fn(p.done, p.total) - } - return n, err -} - -// downloadPlain fetches url to dest with no checksum: into dest.part, then renamed. -func downloadPlain(ctx context.Context, client *http.Client, url, dest string, size int64, fn func(done, total int64)) error { - req, err := fetch.NewRequest(ctx, url) - if err != nil { - return err - } - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("download: HTTP %d", resp.StatusCode) - } - total := size - if total <= 0 && resp.ContentLength > 0 { - total = resp.ContentLength - } - if total > downloadMaxBytes { - return fmt.Errorf("download is larger than %d bytes", downloadMaxBytes) - } - part := dest + ".part" - f, err := os.OpenFile(part, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) - if err != nil { - return err - } - n, err := io.Copy(&progressWriter{w: f, total: total, fn: fn}, io.LimitReader(resp.Body, downloadMaxBytes+1)) - closeErr := f.Close() - if err == nil && n > downloadMaxBytes { - err = fmt.Errorf("download is larger than %d bytes", downloadMaxBytes) - } - if err == nil { - err = closeErr - } - if err == nil { - err = ctx.Err() - } - if err != nil { - _ = os.Remove(part) - return err - } - return os.Rename(part, dest) -} - type downloadEvent struct { ID string `json:"id"` Status string `json:"status"` // running | done | failed | canceled @@ -307,6 +247,9 @@ func (a *App) startPluginDownload(broker *plugin.Broker, notify downloadNotifier if want != "" && !isHex64(want) { return nil, errors.New("sha256 must be 64 hex digits") } + if want == "" && strings.TrimSpace(req.SHA256URL) == "" { + return nil, errors.New("sha256 or sha256_url is required") + } if len(roots) == 0 { return nil, errors.New("this plugin has no folder it may download into") } @@ -359,17 +302,12 @@ func (a *App) startPluginDownload(broker *plugin.Broker, notify downloadNotifier } } var err error - if want == "" && strings.TrimSpace(req.SHA256URL) != "" { - name := req.SHA256Name - want, err = resolveExpectedSum(ctx, client, req.SHA256URL, name) + if want == "" { + want, err = resolveExpectedSum(ctx, client, req.SHA256URL, req.SHA256Name) } if err == nil { - if want != "" { - _, err = fetch.ResumeDirect(ctx, client, req.URL, dest, req.Size, want, progress, - fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: downloadStall}) - } else { - err = downloadPlain(ctx, client, req.URL, dest, req.Size, progress) - } + _, err = fetch.ResumeDirect(ctx, client, req.URL, dest, req.Size, want, progress, + fetch.ResumeOptions{MaxBytes: downloadMaxBytes, StallTimeout: downloadStall}) } pluginDownloads.mu.Lock() delete(pluginDownloads.m, id) diff --git a/internal/app/download_host_test.go b/internal/app/download_host_test.go index fed1e60..2db31bd 100644 --- a/internal/app/download_host_test.go +++ b/internal/app/download_host_test.go @@ -1,7 +1,6 @@ package app import ( - "context" "crypto/sha256" "encoding/hex" "encoding/json" @@ -112,7 +111,6 @@ func TestHostDownloadVerifiesAndReportsProgress(t *testing.T) { "explicit hash": {"url": srv.URL + "/file.bin", "sha256": sum(body), "dest": "a/file.bin"}, "sums file": {"url": srv.URL + "/file.bin", "sha256_url": srv.URL + "/SHA256SUMS.txt", "sha256_name": "file.bin", "dest": "b/file.bin"}, "single hash": {"url": srv.URL + "/file.bin", "sha256_url": srv.URL + "/one.sha256", "dest": "c/file.bin"}, - "no checksum": {"url": srv.URL + "/file.bin", "dest": "d/file.bin", "label": "plain"}, } for name, req := range cases { id, err := e.start(t, e.plugin, req) @@ -158,14 +156,15 @@ func TestHostDownloadChecksOriginsAndDestinations(t *testing.T) { outside := filepath.Join(t.TempDir(), "out.bin") bad := map[string]map[string]any{ - "undeclared origin": {"url": denied.URL + "/x", "dest": "a.bin"}, + "undeclared origin": {"url": denied.URL + "/x", "sha256": sum([]byte("ok")), "dest": "a.bin"}, "undeclared checksum": {"url": srv.URL + "/x", "sha256_url": denied.URL + "/sums", "dest": "a.bin"}, - "plain http to a remote": {"url": "http://example.com/x", "dest": "a.bin"}, - "url with user info": {"url": strings.Replace(srv.URL, "http://", "http://user:pw@", 1) + "/x", "dest": "a.bin"}, - "file scheme": {"url": "file:///C:/Windows/win.ini", "dest": "a.bin"}, - "dest above the folder": {"url": srv.URL + "/x", "dest": "../escaped.bin"}, - "dest elsewhere": {"url": srv.URL + "/x", "dest": outside}, - "empty dest": {"url": srv.URL + "/x", "dest": ""}, + "plain http to a remote": {"url": "http://example.com/x", "sha256": sum([]byte("ok")), "dest": "a.bin"}, + "url with user info": {"url": strings.Replace(srv.URL, "http://", "http://user:pw@", 1) + "/x", "sha256": sum([]byte("ok")), "dest": "a.bin"}, + "file scheme": {"url": "file:///C:/Windows/win.ini", "sha256": sum([]byte("ok")), "dest": "a.bin"}, + "dest above the folder": {"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": "../escaped.bin"}, + "dest elsewhere": {"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": outside}, + "empty dest": {"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": ""}, + "no checksum": {"url": srv.URL + "/x", "dest": "a.bin"}, "bad hash": {"url": srv.URL + "/x", "sha256": "zz", "dest": "a.bin"}, } for name, req := range bad { @@ -177,7 +176,7 @@ func TestHostDownloadChecksOriginsAndDestinations(t *testing.T) { t.Fatal("a file was written outside the allowed folders") } // Another plugin without the permission cannot use this origin. - if id, err := e.start(t, e.other, map[string]any{"url": srv.URL + "/x", "dest": "a.bin"}); err == nil { + if id, err := e.start(t, e.other, map[string]any{"url": srv.URL + "/x", "sha256": sum([]byte("ok")), "dest": "a.bin"}); err == nil { t.Fatalf("a plugin without the net permission started download %s", id) } } @@ -196,7 +195,7 @@ func TestHostDownloadCancelIsPerPlugin(t *testing.T) { })) defer srv.Close() e := newDownloadTestEnv(t, srv.URL, "127.0.0.1") - id, err := e.start(t, e.plugin, map[string]any{"url": srv.URL + "/slow", "dest": "slow.bin"}) + id, err := e.start(t, e.plugin, map[string]any{"url": srv.URL + "/slow", "sha256": sum([]byte("x")), "dest": "slow.bin"}) if err != nil { t.Fatal(err) } @@ -232,13 +231,13 @@ func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) { } via := []*http.Request{req("https://downloads.example.com/file")} cases := map[string]string{ - "downgrade to http": "http://8.8.8.8/x", - "loopback": "https://127.0.0.1/x", - "loopback name": "https://localhost/x", - "private range": "https://10.1.2.3/x", - "link local": "https://169.254.169.254/latest", - "scheme change": "ftp://8.8.8.8/x", - "user info": "https://u:p@8.8.8.8/x", + "downgrade to http": "http://8.8.8.8/x", + "loopback": "https://127.0.0.1/x", + "loopback name": "https://localhost/x", + "private range": "https://10.1.2.3/x", + "link local": "https://169.254.169.254/latest", + "scheme change": "ftp://8.8.8.8/x", + "user info": "https://u:p@8.8.8.8/x", } for name, target := range cases { if err := client.CheckRedirect(req(target), via); err == nil { @@ -260,7 +259,6 @@ func TestDownloadRedirectsNeverDowngradeOrReachInternalHosts(t *testing.T) { if err := local.CheckRedirect(req("http://127.0.0.1:1/g"), []*http.Request{req("http://127.0.0.1:1/f")}); err != nil { t.Errorf("a loopback redirect from a loopback origin was refused: %v", err) } - _ = context.Background() } func TestHasRunningDownloadFollowsPluginDownloads(t *testing.T) { diff --git a/internal/app/elevate_flow.go b/internal/app/elevate_flow.go index 2b90023..5e0dc9f 100644 --- a/internal/app/elevate_flow.go +++ b/internal/app/elevate_flow.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "os" "os/user" "strings" "time" @@ -32,7 +31,7 @@ type ElevationPrompt struct { NeedsLogoff bool `json:"needs_logoff,omitempty"` } -type elevationRunner func(ctx context.Context, exePath, action, targetUser string) (host.ElevationResult, error) +type elevationRunner func(ctx context.Context, action, targetUser string) (host.ElevationResult, error) func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler { if mgr == nil || mgr.Broker() == nil { @@ -54,7 +53,7 @@ func (a *App) elevateHostHandlers(mgr *plugin.Manager, pluginID string) map[stri // requestElevation runs one plugin elevation request: check the permission and // the closed action list, ask the person in the desktop window, and only after -// a yes start the elevated helper (which raises the Windows UAC prompt). A no, +// a yes run the action (which raises the Windows UAC prompt). A no, // a timeout or a missing window ends the request before anything runs. func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg *plugin.Registry, pluginID string, raw json.RawMessage) (any, error) { if err := broker.Authorize(pluginID, "driver:vm"); err != nil { @@ -156,7 +155,6 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg * } broker.Audit(pluginID, "ELEVATE_APPROVED", spec.Action) - exePath, _ := os.Executable() targetUser := "" if spec.Action == host.ElevateHyperVAddAdminGroup { cur, err := user.Current() @@ -169,7 +167,7 @@ func (a *App) requestElevation(ctx context.Context, broker *plugin.Broker, reg * if runner == nil { runner = host.RunElevatedAction } - res, err := runner(ctx, exePath, spec.Action, targetUser) + res, err := runner(ctx, spec.Action, targetUser) if err != nil { if errors.Is(err, host.ErrElevationDeclined) { broker.Audit(pluginID, "ELEVATE_UAC_DECLINED", spec.Action) diff --git a/internal/app/elevate_flow_test.go b/internal/app/elevate_flow_test.go index 236f337..c5a4dd5 100644 --- a/internal/app/elevate_flow_test.go +++ b/internal/app/elevate_flow_test.go @@ -52,7 +52,7 @@ func newElevateTestEnv(t *testing.T) *elevateTestEnv { e.dismissed = append(e.dismissed, id) e.mu.Unlock() } - e.app.elevateRunner = func(_ context.Context, exePath, action, targetUser string) (host.ElevationResult, error) { + e.app.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) { e.runs.Add(1) e.mu.Lock() e.runArgs = []string{action, targetUser} diff --git a/internal/app/hosted_driver_test.go b/internal/app/hosted_driver_test.go index 950f4d5..46bc3b2 100644 --- a/internal/app/hosted_driver_test.go +++ b/internal/app/hosted_driver_test.go @@ -24,12 +24,12 @@ func TestHelperFakeDriver(t *testing.T) { fakedriver.MaybeServe() } func TestHelperFakeVM(t *testing.T) { fakedriver.MaybeRunVM() } type twoDriverApp struct { - app *App - hosted, process driver.Driver - hostedRef, processRef driver.VMRef - harness *fakedriver.Harness - svc *lifecycle.Service - hostedDir, processDir string + app *App + hosted, process driver.Driver + hostedRef, processRef driver.VMRef + harness *fakedriver.Harness + svc *lifecycle.Service + hostedDir, processDir string } func newTwoDriverApp(t *testing.T) *twoDriverApp { diff --git a/internal/app/secret_materialize_flow.go b/internal/app/secret_materialize_flow.go index 47a9722..2a35131 100644 --- a/internal/app/secret_materialize_flow.go +++ b/internal/app/secret_materialize_flow.go @@ -97,11 +97,11 @@ func encodeSecret(secret, format string) (string, error) { // result into the VM's folder. The plugin gets back only the path. func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, pluginID string, raw json.RawMessage) (any, error) { var req struct { - Setting string `json:"setting"` - Ref plugin.VMRef `json:"ref"` - Template string `json:"template"` - Dest string `json:"dest"` - Format string `json:"format"` + Setting string `json:"setting"` + Ref plugin.VMRef `json:"ref"` + Template string `json:"template"` + Dest string `json:"dest"` + Format string `json:"format"` } if err := json.Unmarshal(raw, &req); err != nil { return nil, err @@ -156,11 +156,12 @@ func (a *App) materializeSecret(broker *plugin.Broker, source secretSource, plug return nil, err } content := strings.ReplaceAll(req.Template, secretPlaceholder, encoded) - if err := writeSecretFile(dest, []byte(content)); err != nil { + // Record the file first: a crash in between leaves a record without a file, + // never a secret file nobody cleans up. + if err := a.trackMaterializedSecret(materializedSecret{VMKey: vm.Ref().Key(), PluginID: pluginID, Setting: req.Setting, Path: dest}); err != nil { return nil, err } - if err := a.trackMaterializedSecret(materializedSecret{VMKey: vm.Ref().Key(), PluginID: pluginID, Setting: req.Setting, Path: dest}); err != nil { - _ = os.Remove(dest) + if err := writeSecretFile(dest, []byte(content)); err != nil { return nil, err } // The audit line names the setting and its size, never the value. @@ -249,6 +250,8 @@ func saveMaterializedSecrets(path string, doc materializedSecretsFile) error { func samePath(a, b string) bool { return strings.EqualFold(filepath.Clean(a), filepath.Clean(b)) } +// trackMaterializedSecret records entry. It refuses a file that already exists +// without a record of the same VM and plugin: the host would later delete it. func (a *App) trackMaterializedSecret(entry materializedSecret) error { path := a.materializedSecretsPath() if path == "" { @@ -262,27 +265,47 @@ func (a *App) trackMaterializedSecret(entry materializedSecret) error { } for i := range doc.Entries { if samePath(doc.Entries[i].Path, entry.Path) { + if doc.Entries[i].VMKey != entry.VMKey || doc.Entries[i].PluginID != entry.PluginID { + return errors.New("dest holds a secret file of another VM or plugin") + } doc.Entries[i] = entry return saveMaterializedSecrets(path, doc) } } + if _, err := os.Lstat(entry.Path); err == nil { + return errors.New("dest already exists") + } else if !os.IsNotExist(err) { + return err + } doc.Entries = append(doc.Entries, entry) return saveMaterializedSecrets(path, doc) } -// wipeFile overwrites a secret file before it is deleted. -func wipeFile(path string) { - if st, err := os.Lstat(path); err == nil && st.Mode().IsRegular() { - if f, err := os.OpenFile(path, os.O_WRONLY, 0); err == nil { - _, _ = f.Write(make([]byte, st.Size())) - _ = f.Close() +// wipeFile overwrites a secret file and deletes it. A missing file is fine. +func wipeFile(path string) error { + st, err := os.Lstat(path) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return err + } + if st.Mode().IsRegular() { + f, err := os.OpenFile(path, os.O_WRONLY, 0) + if err != nil { + return err + } + _, err = f.Write(make([]byte, st.Size())) + if err := errors.Join(err, f.Close()); err != nil { + return err } } - _ = os.Remove(path) + return os.Remove(path) } // removeMaterialized deletes the tracked files chosen by match and drops -// their records. It returns how many files it handled. +// their records. A file it cannot delete keeps its record for the next try. +// It returns how many files it deleted. func (a *App) removeMaterialized(match func(materializedSecret) bool) (int, error) { path := a.materializedSecretsPath() if path == "" { @@ -296,19 +319,23 @@ func (a *App) removeMaterialized(match func(materializedSecret) bool) (int, erro } kept := doc.Entries[:0:0] removed := 0 + var errs []error for _, e := range doc.Entries { if match(e) { - wipeFile(e.Path) - removed++ - continue + err := wipeFile(e.Path) + if err == nil { + removed++ + continue + } + errs = append(errs, err) } kept = append(kept, e) } - if removed == 0 { - return 0, nil + if removed > 0 { + doc.Entries = kept + errs = append(errs, saveMaterializedSecrets(path, doc)) } - doc.Entries = kept - return removed, saveMaterializedSecrets(path, doc) + return removed, errors.Join(errs...) } // discardSecret deletes the files a plugin materialized for one VM, or just diff --git a/internal/app/secret_materialize_test.go b/internal/app/secret_materialize_test.go index df44e03..5971abc 100644 --- a/internal/app/secret_materialize_test.go +++ b/internal/app/secret_materialize_test.go @@ -20,15 +20,15 @@ import ( const testSecret = `p@ss<&>w0rd"é` type secretTestEnv struct { - app *App - h *fakedriver.Harness - ownerPlugin string - ownerDriver driver.Driver - otherPlugin string - otherDriver driver.Driver - vmDir string - source secretSource - sourceCalls int + app *App + h *fakedriver.Harness + ownerPlugin string + ownerDriver driver.Driver + otherPlugin string + otherDriver driver.Driver + vmDir string + source secretSource + sourceCalls int } func newSecretTestEnv(t *testing.T) *secretTestEnv { @@ -247,3 +247,49 @@ func TestDiscardSecretAndVMDeletionRemoveTheFiles(t *testing.T) { t.Fatal("the tracking file outlived its last entry") } } + +func TestMaterializeSecretKeepsExistingFiles(t *testing.T) { + e := newSecretTestEnv(t) + own := filepath.Join(e.vmDir, "disk.img") + if err := os.WriteFile(own, []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := e.materialize(t, e.ownerPlugin, e.request("disk.img", "")); err == nil { + t.Fatal("a file the host did not create was overwritten") + } + e.app.discardMaterializedSecretsForVM(driver.NewVMRef(e.ownerDriver.ID(), "dev").Key()) + if raw, err := os.ReadFile(own); err != nil || string(raw) != "keep" { + t.Fatalf("existing file = %q, %v", raw, err) + } + for range 2 { // the host may refresh its own file + if _, err := e.materialize(t, e.ownerPlugin, e.request("a.xml", "")); err != nil { + t.Fatal(err) + } + } +} + +func TestDiscardSecretRetriesAFileItCouldNotDelete(t *testing.T) { + e := newSecretTestEnv(t) + res, err := e.materialize(t, e.ownerPlugin, e.request("a.xml", "")) + if err != nil { + t.Fatal(err) + } + path := res.(map[string]any)["path"].(string) + // A non-empty folder in the file's place cannot be removed. + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(path, "x"), 0o755); err != nil { + t.Fatal(err) + } + all := func(materializedSecret) bool { return true } + if n, err := e.app.removeMaterialized(all); err == nil || n != 0 { + t.Fatalf("removed %d, %v; want an error", n, err) + } + if err := os.Remove(filepath.Join(path, "x")); err != nil { + t.Fatal(err) + } + if n, err := e.app.removeMaterialized(all); err != nil || n != 1 { + t.Fatalf("the retry removed %d, %v", n, err) + } +} diff --git a/internal/app/ssh_flow.go b/internal/app/ssh_flow.go index 6f20faf..d099549 100644 --- a/internal/app/ssh_flow.go +++ b/internal/app/ssh_flow.go @@ -89,6 +89,7 @@ func (a *App) SetVMSSHUserWithDriver(driverID, name, user string) error { func (a *App) OpenSSHTerminal(name, user string) error { return a.OpenSSHTerminalWithDriver("", name, user) } + // sshTarget is where a VM's SSH server answers: the ssh endpoint the driver // reports (a hosted VM may sit on its own address), else the forwarded port. func sshTarget(vm driver.VMInfo) (host string, port int, user string, ok bool) { diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 3643ec7..265b4f4 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -45,10 +45,6 @@ func IsCommand(args []string) bool { } func run(args []string) (i18n.Locale, error) { - // The elevated helper must not read or create anything in the data folder. - if len(args) > 0 && args[0] == "__elevate" { - return i18n.Detect(), cmdElevate(args[1:]) - } fs := flag.NewFlagSet("reims-go", flag.ContinueOnError) fs.SetOutput(io.Discard) langFlag := fs.String("lang", "", "UI/CLI language: auto | zh-CN | en-US | | en-XA") diff --git a/internal/cli/elevate.go b/internal/cli/elevate.go deleted file mode 100644 index 9cdfad5..0000000 --- a/internal/cli/elevate.go +++ /dev/null @@ -1,65 +0,0 @@ -package cli - -import ( - "context" - "encoding/json" - "errors" - "flag" - "io" - "os" - - "github.com/Nwflower/reims-go/internal/host" -) - -// elevateExec runs one whitelisted action; tests replace it. -var elevateExec = host.ExecuteElevatedAction - -// cmdElevate is the hidden `__elevate` subcommand the desktop app starts through -// a UAC prompt. It runs before any data folder is opened, so an elevated run -// never creates or changes files in the user's data folder. It is not listed -// in the usage text. -func cmdElevate(args []string) error { - fs := flag.NewFlagSet("__elevate", flag.ContinueOnError) - fs.SetOutput(io.Discard) - action := fs.String("action", "", "whitelisted elevation action") - user := fs.String("user", "", "account the action applies to") - resultFile := fs.String("result-file", "", "file the JSON result is written to") - if err := fs.Parse(args); err != nil { - return writeElevateFailure(*resultFile, *action, err) - } - if _, ok := host.LookupElevationAction(*action); !ok { - return writeElevateFailure(*resultFile, *action, errors.New("unsupported elevation action")) - } - res, err := elevateExec(context.Background(), *action, *user) - if err != nil { - if res.Action == "" { - res.Action = *action - } - if res.Error == "" { - res.Error = err.Error() - } - res.OK = false - } - if werr := writeElevateResult(*resultFile, res); werr != nil && err == nil { - return werr - } - return err -} - -func writeElevateFailure(path, action string, err error) error { - _ = writeElevateResult(path, host.ElevationResult{Action: action, Error: err.Error()}) - return err -} - -// writeElevateResult fills the file in place: the caller created it, and -// replacing it would drop the access the caller holds. -func writeElevateResult(path string, res host.ElevationResult) error { - if path == "" { - return nil - } - data, err := json.Marshal(res) - if err != nil { - return err - } - return os.WriteFile(path, data, 0o600) -} diff --git a/internal/cli/elevate_test.go b/internal/cli/elevate_test.go deleted file mode 100644 index 7149247..0000000 --- a/internal/cli/elevate_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package cli - -import ( - "context" - "encoding/json" - "io" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" -) - -func readElevateResult(t *testing.T, path string) host.ElevationResult { - t.Helper() - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read result: %v", err) - } - var res host.ElevationResult - if err := json.Unmarshal(data, &res); err != nil { - t.Fatalf("decode result %q: %v", data, err) - } - return res -} - -func TestElevateRejectsActionsOutsideTheWhitelist(t *testing.T) { - called := false - prev := elevateExec - elevateExec = func(context.Context, string, string) (host.ElevationResult, error) { - called = true - return host.ElevationResult{OK: true}, nil - } - t.Cleanup(func() { elevateExec = prev }) - - // Point every data-folder lookup at an empty folder: the helper must not touch it. - home := t.TempDir() - t.Setenv("APPDATA", home) - t.Setenv("LOCALAPPDATA", home) - t.Setenv("USERPROFILE", home) - t.Setenv("HOME", home) - - resPath := filepath.Join(t.TempDir(), "result.json") - for _, action := range []string{"rm-rf", ""} { - if _, err := run([]string{"__elevate", "--action", action, "--result-file", resPath}); err == nil { - t.Fatalf("action %q was accepted", action) - } - if res := readElevateResult(t, resPath); res.OK { - t.Fatalf("action %q reported success: %+v", action, res) - } - } - if called { - t.Fatal("an action outside the whitelist reached the executor") - } - entries, err := os.ReadDir(home) - if err != nil { - t.Fatal(err) - } - if len(entries) != 0 { - t.Fatalf("the elevated helper wrote into the data folder candidates: %v", entries) - } -} - -func TestElevateRunsAWhitelistedActionAndWritesTheResult(t *testing.T) { - prev := elevateExec - var gotAction, gotUser string - elevateExec = func(_ context.Context, action, user string) (host.ElevationResult, error) { - gotAction, gotUser = action, user - return host.ElevationResult{OK: true, Action: action, RebootRequired: true}, nil - } - t.Cleanup(func() { elevateExec = prev }) - - resPath := filepath.Join(t.TempDir(), "result.json") - if _, err := run([]string{"__elevate", "--action", "hyperv.enable", "--user", `PC\alice`, "--result-file", resPath}); err != nil { - t.Fatalf("run: %v", err) - } - if gotAction != "hyperv.enable" || gotUser != `PC\alice` { - t.Fatalf("executor got %q, %q", gotAction, gotUser) - } - res := readElevateResult(t, resPath) - if !res.OK || res.Action != "hyperv.enable" || !res.RebootRequired { - t.Fatalf("result = %+v", res) - } -} - -func TestElevateReportsExecutorFailures(t *testing.T) { - prev := elevateExec - elevateExec = func(_ context.Context, action, _ string) (host.ElevationResult, error) { - return host.ElevationResult{Action: action, ExitCode: 5}, io.ErrUnexpectedEOF - } - t.Cleanup(func() { elevateExec = prev }) - - resPath := filepath.Join(t.TempDir(), "result.json") - if _, err := run([]string{"__elevate", "--action", "sandbox.enable", "--result-file", resPath}); err == nil { - t.Fatal("a failed action returned no error") - } - res := readElevateResult(t, resPath) - if res.OK || res.Error == "" || res.ExitCode != 5 { - t.Fatalf("result = %+v", res) - } -} - -func TestElevateIsHiddenFromUsage(t *testing.T) { - if !IsCommand([]string{"__elevate", "--action", "hyperv.enable"}) { - t.Fatal("__elevate must run as a command, not open the window") - } - old := os.Stdout - r, w, err := os.Pipe() - if err != nil { - t.Fatal(err) - } - os.Stdout = w - printUsage(i18n.EffectiveLocale(i18n.EnUS)) - os.Stdout = old - _ = w.Close() - out, err := io.ReadAll(r) - if err != nil { - t.Fatal(err) - } - if strings.Contains(string(out), "__elevate") { - t.Fatalf("usage mentions the hidden subcommand:\n%s", out) - } -} diff --git a/internal/driver/console.go b/internal/driver/console.go index 2125c4e..8084179 100644 --- a/internal/driver/console.go +++ b/internal/driver/console.go @@ -33,7 +33,7 @@ type ConsoleScreenshotRequest struct { // ConsoleScreenshotResult describes the frame the driver wrote to the // requested path. type ConsoleScreenshotResult struct { - Path string `json:"path,omitempty"` // empty or equal to the requested path + Path string `json:"path,omitempty"` // empty or equal to the requested path Format string `json:"format,omitempty"` // "png" (default) or "ppm" Width int `json:"width,omitempty"` Height int `json:"height,omitempty"` diff --git a/internal/driver/driver.go b/internal/driver/driver.go index e661564..51d637c 100644 --- a/internal/driver/driver.go +++ b/internal/driver/driver.go @@ -108,16 +108,16 @@ type ValidationIssue struct { // VMListItem is the poll-facing process and state summary shared with the UI. type VMListItem struct { - Name string `json:"name"` - DriverID string `json:"driver_id,omitempty"` - Dir string `json:"dir"` - PID *int `json:"pid"` - State string `json:"state"` - Capabilities []string `json:"capabilities,omitempty"` - GuestOS *GuestOSInfo `json:"guest_os,omitempty"` - Phase string `json:"phase,omitempty"` - Ready *bool `json:"ready,omitempty"` - Endpoints []VMEndpoint `json:"endpoints,omitempty"` + Name string `json:"name"` + DriverID string `json:"driver_id,omitempty"` + Dir string `json:"dir"` + PID *int `json:"pid"` + State string `json:"state"` + Capabilities []string `json:"capabilities,omitempty"` + GuestOS *GuestOSInfo `json:"guest_os,omitempty"` + Phase string `json:"phase,omitempty"` + Ready *bool `json:"ready,omitempty"` + Endpoints []VMEndpoint `json:"endpoints,omitempty"` } // VMInfo is the generic cross-driver VM model (§5.3). diff --git a/internal/driver/endpoints.go b/internal/driver/endpoints.go index 2bd5e19..bd937ec 100644 --- a/internal/driver/endpoints.go +++ b/internal/driver/endpoints.go @@ -35,7 +35,7 @@ type VMEndpoint struct { var ( reEndpointHost = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$`) - reEndpointUser = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) + reEndpointUser = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]*$`) reEndpointDistro = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) reEndpointSerial = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$`) ) @@ -46,8 +46,8 @@ func validEndpointHost(host string) bool { if host == "" { return false } - if _, err := netip.ParseAddr(host); err == nil { - return true + if addr, err := netip.ParseAddr(host); err == nil { + return addr.Zone() == "" // a zone may hold any character } return reEndpointHost.MatchString(host) } diff --git a/internal/driver/endpoints_test.go b/internal/driver/endpoints_test.go index 2292d9e..c89378c 100644 --- a/internal/driver/endpoints_test.go +++ b/internal/driver/endpoints_test.go @@ -25,31 +25,33 @@ func TestValidateEndpoint(t *testing.T) { } } bad := map[string]VMEndpoint{ - "unknown kind": {Kind: "telnet", Host: "127.0.0.1", Port: 23}, - "empty kind": {}, - "ssh port zero": {Kind: EndpointSSH}, - "ssh port high": {Kind: EndpointSSH, Port: 70000}, - "ssh host flag": {Kind: EndpointSSH, Host: "-oProxyCommand=calc", Port: 22}, - "ssh host space": {Kind: EndpointSSH, Host: "a b", Port: 22}, - "ssh user injection": {Kind: EndpointSSH, Port: 22, User: "dev; calc"}, - "wsl distro flag": {Kind: EndpointWSL, Distro: "-u"}, - "wsl distro space": {Kind: EndpointWSL, Distro: "a b"}, - "wsl distro empty": {Kind: EndpointWSL}, - "rdp host empty": {Kind: EndpointRDP}, - "rdp host injection": {Kind: EndpointRDP, Host: "h /admin"}, - "rdp port negative": {Kind: EndpointRDP, Host: "h", Port: -1}, - "vmconnect empty": {Kind: EndpointVMConnect}, - "vmconnect switch": {Kind: EndpointVMConnect, VM: "/edit"}, - "vmconnect dash": {Kind: EndpointVMConnect, VM: "-x"}, - "vmconnect quote": {Kind: EndpointVMConnect, VM: `a"b`}, - "vmconnect ampersand": {Kind: EndpointVMConnect, VM: "a&calc"}, - "vmconnect percent": {Kind: EndpointVMConnect, VM: "%PATH%"}, - "vmconnect control": {Kind: EndpointVMConnect, VM: "a\nb"}, - "vmconnect padded": {Kind: EndpointVMConnect, VM: " a"}, - "vmconnect too long": {Kind: EndpointVMConnect, VM: strings.Repeat("a", 129)}, - "adb serial flag": {Kind: EndpointADB, Serial: "-s"}, - "adb serial injection": {Kind: EndpointADB, Serial: "x;calc"}, - "adb serial empty": {Kind: EndpointADB}, + "unknown kind": {Kind: "telnet", Host: "127.0.0.1", Port: 23}, + "empty kind": {}, + "ssh port zero": {Kind: EndpointSSH}, + "ssh port high": {Kind: EndpointSSH, Port: 70000}, + "ssh host flag": {Kind: EndpointSSH, Host: "-oProxyCommand=calc", Port: 22}, + "ssh host space": {Kind: EndpointSSH, Host: "a b", Port: 22}, + "ssh user injection": {Kind: EndpointSSH, Port: 22, User: "dev; calc"}, + "ssh user flag": {Kind: EndpointSSH, Port: 22, User: "-oProxyCommand"}, + "rdp host zone": {Kind: EndpointRDP, Host: "fe80::1%x & calc"}, + "wsl distro flag": {Kind: EndpointWSL, Distro: "-u"}, + "wsl distro space": {Kind: EndpointWSL, Distro: "a b"}, + "wsl distro empty": {Kind: EndpointWSL}, + "rdp host empty": {Kind: EndpointRDP}, + "rdp host injection": {Kind: EndpointRDP, Host: "h /admin"}, + "rdp port negative": {Kind: EndpointRDP, Host: "h", Port: -1}, + "vmconnect empty": {Kind: EndpointVMConnect}, + "vmconnect switch": {Kind: EndpointVMConnect, VM: "/edit"}, + "vmconnect dash": {Kind: EndpointVMConnect, VM: "-x"}, + "vmconnect quote": {Kind: EndpointVMConnect, VM: `a"b`}, + "vmconnect ampersand": {Kind: EndpointVMConnect, VM: "a&calc"}, + "vmconnect percent": {Kind: EndpointVMConnect, VM: "%PATH%"}, + "vmconnect control": {Kind: EndpointVMConnect, VM: "a\nb"}, + "vmconnect padded": {Kind: EndpointVMConnect, VM: " a"}, + "vmconnect too long": {Kind: EndpointVMConnect, VM: strings.Repeat("a", 129)}, + "adb serial flag": {Kind: EndpointADB, Serial: "-s"}, + "adb serial injection": {Kind: EndpointADB, Serial: "x;calc"}, + "adb serial empty": {Kind: EndpointADB}, } for name, ep := range bad { if err := ValidateEndpoint(ep); err == nil { diff --git a/internal/driver/sidecar_driver.go b/internal/driver/sidecar_driver.go index 80bf675..9b1eda3 100644 --- a/internal/driver/sidecar_driver.go +++ b/internal/driver/sidecar_driver.go @@ -6,6 +6,7 @@ import ( "io" "os" "path/filepath" + "slices" "strings" "github.com/Nwflower/reims-go/internal/plugin" @@ -98,22 +99,22 @@ func (d *SidecarDriver) PasteCombo() string { return d.contrib.PasteCombo } func (d *SidecarDriver) Keymap() string { return d.contrib.Keymap } var ( - _ Driver = (*SidecarDriver)(nil) - _ ActionDriver = (*SidecarDriver)(nil) - _ LogDriver = (*SidecarDriver)(nil) - _ PhaseReporter = (*SidecarDriver)(nil) - _ DriverMetadata = (*SidecarDriver)(nil) - _ SnapshotDriver = (*sidecarSnapshots)(nil) - _ CloneDriver = (*sidecarClones)(nil) - _ DiskDriver = (*sidecarDisks)(nil) + _ Driver = (*SidecarDriver)(nil) + _ ActionDriver = (*SidecarDriver)(nil) + _ LogDriver = (*SidecarDriver)(nil) + _ PhaseReporter = (*SidecarDriver)(nil) + _ DriverMetadata = (*SidecarDriver)(nil) + _ SnapshotDriver = (*sidecarSnapshots)(nil) + _ CloneDriver = (*sidecarClones)(nil) + _ DiskDriver = (*sidecarDisks)(nil) ) func (d *SidecarDriver) ref(name string) VMRef { return VMRef{DriverID: d.contrib.ID, Name: name} } // normalize pins a VM the Sidecar returned to this driver: its capabilities -// can only narrow the manifest's, its endpoints must be valid, and the ssh +// can only narrow the manifest's, invalid endpoints are dropped, and the ssh // endpoint and SSH port agree. -func (d *SidecarDriver) normalize(vm *VMInfo) error { +func (d *SidecarDriver) normalize(vm *VMInfo) { vm.DriverID = d.contrib.ID if len(vm.Capabilities) == 0 { vm.Capabilities = d.Capabilities() @@ -126,11 +127,8 @@ func (d *SidecarDriver) normalize(vm *VMInfo) error { } vm.Capabilities = kept } - if err := ValidateEndpoints(vm.Endpoints); err != nil { - return fmt.Errorf("VM %q of driver %q reports an invalid endpoint: %w", vm.Name, d.contrib.ID, err) - } + vm.Endpoints = slices.DeleteFunc(vm.Endpoints, func(ep VMEndpoint) bool { return ValidateEndpoint(ep) != nil }) SyncSSHEndpoint(vm) - return nil } func (d *SidecarDriver) List(ctx context.Context) ([]VMInfo, error) { @@ -141,9 +139,7 @@ func (d *SidecarDriver) List(ctx context.Context) ([]VMInfo, error) { return nil, err } for i := range resp.VMs { - if err := d.normalize(&resp.VMs[i]); err != nil { - return nil, err - } + d.normalize(&resp.VMs[i]) } return resp.VMs, nil } @@ -153,9 +149,7 @@ func (d *SidecarDriver) Show(ctx context.Context, name string) (VMInfo, error) { if err := d.sup.Call(ctx, "driver/show", map[string]any{"name": name, "ref": d.ref(name)}, &info); err != nil { return VMInfo{}, err } - if err := d.normalize(&info); err != nil { - return VMInfo{}, err - } + d.normalize(&info) return info, nil } diff --git a/internal/host/elevate.go b/internal/host/elevate.go index ec9f6de..8118d5f 100644 --- a/internal/host/elevate.go +++ b/internal/host/elevate.go @@ -30,7 +30,6 @@ type ElevationResult struct { ExitCode int `json:"exit_code,omitempty"` RebootRequired bool `json:"reboot_required,omitempty"` LogoffRequired bool `json:"logoff_required,omitempty"` - Error string `json:"error,omitempty"` } var elevationActions = map[string]ElevationActionSpec{ @@ -68,10 +67,3 @@ func ValidateElevationTargetUser(user string) error { } return nil } - -// isNetAlreadyMemberOutput reports whether `net localgroup /add` failed only -// because the account already belongs to the group (system error 1378, which -// every Windows display language prints with the same number). -func isNetAlreadyMemberOutput(output string) bool { - return strings.Contains(output, "1378") -} diff --git a/internal/host/elevate_other.go b/internal/host/elevate_other.go index 9785b8a..434486c 100644 --- a/internal/host/elevate_other.go +++ b/internal/host/elevate_other.go @@ -8,22 +8,10 @@ import ( "runtime" ) -func unsupportedElevation(action string) (ElevationResult, error) { +// RunElevatedAction is only available on Windows. +func RunElevatedAction(_ context.Context, action, _ string) (ElevationResult, error) { + if _, ok := LookupElevationAction(action); !ok { + return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) + } return ElevationResult{Action: action}, fmt.Errorf("elevated actions are a Windows feature (current OS: %s)", runtime.GOOS) } - -// ExecuteElevatedAction runs a whitelisted action in the current process. -func ExecuteElevatedAction(_ context.Context, action, _ string) (ElevationResult, error) { - if _, ok := LookupElevationAction(action); !ok { - return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) - } - return unsupportedElevation(action) -} - -// RunElevatedAction starts the elevated helper and waits for its result. -func RunElevatedAction(_ context.Context, _, action, _ string) (ElevationResult, error) { - if _, ok := LookupElevationAction(action); !ok { - return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) - } - return unsupportedElevation(action) -} diff --git a/internal/host/elevate_test.go b/internal/host/elevate_test.go index 22b4f33..37e29c9 100644 --- a/internal/host/elevate_test.go +++ b/internal/host/elevate_test.go @@ -37,26 +37,10 @@ func TestValidateElevationTargetUser(t *testing.T) { } } -func TestIsNetAlreadyMemberOutput(t *testing.T) { - for _, out := range []string{"System error 1378 has occurred.", "发生系统错误 1378。"} { - if !isNetAlreadyMemberOutput(out) { - t.Errorf("%q should count as already a member", out) - } - } - for _, out := range []string{"System error 5 has occurred.", ""} { - if isNetAlreadyMemberOutput(out) { - t.Errorf("%q should not count as already a member", out) +func TestRunElevatedActionRejectsUnknownActions(t *testing.T) { + for _, action := range []string{"shell.exec", ""} { + if res, err := RunElevatedAction(t.Context(), action, ""); err == nil || res.OK { + t.Fatalf("action %q outside the whitelist ran: %+v, %v", action, res, err) } } } - -func TestExecuteElevatedActionRejectsUnknownActions(t *testing.T) { - res, err := ExecuteElevatedAction(t.Context(), "shell.exec", "") - if err == nil || res.OK { - t.Fatalf("an action outside the whitelist ran: %+v, %v", res, err) - } - res, err = RunElevatedAction(t.Context(), "reims-go.exe", "", "") - if err == nil || res.OK { - t.Fatalf("an empty action ran: %+v, %v", res, err) - } -} diff --git a/internal/host/elevate_windows.go b/internal/host/elevate_windows.go index 28d200a..178ec7a 100644 --- a/internal/host/elevate_windows.go +++ b/internal/host/elevate_windows.go @@ -4,87 +4,28 @@ package host import ( "context" - "encoding/json" - "errors" "fmt" - "os" - "os/exec" + "os/user" "path/filepath" + "slices" "strings" "syscall" - "unsafe" "golang.org/x/sys/windows" ) -const ( - seeMaskNoCloseProcess = 0x00000040 - seeMaskNoAsync = 0x00000100 - seeMaskFlagNoUI = 0x00000400 - // dism.exe exits with ERROR_SUCCESS_REBOOT_REQUIRED when the change worked - // and needs a restart. - dismExitRebootRequired = 3010 - hyperVAdminsSID = "S-1-5-32-578" - // How long one wait on the elevated process lasts before the context is checked. - elevateWaitSliceMS = 200 +const hyperVAdminsSID = "S-1-5-32-578" + +// Tests replace these, so no test raises a UAC prompt. +var ( + elevatedRun = runElevatedWait + inHyperVAdminGroup = accountInHyperVAdmins ) -var procShellExecuteExW = shell32.NewProc("ShellExecuteExW") - -// shellExecuteInfoW mirrors SHELLEXECUTEINFOW. -type shellExecuteInfoW struct { - cbSize uint32 - fMask uint32 - hwnd uintptr - lpVerb *uint16 - lpFile *uint16 - lpParameters *uint16 - lpDirectory *uint16 - nShow int32 - hInstApp uintptr - lpIDList uintptr - lpClass *uint16 - hkeyClass uintptr - dwHotKey uint32 - hIcon windows.Handle - hProcess windows.Handle -} - -// systemExe resolves a Windows tool inside System32, so an elevated run never -// follows PATH. -func systemExe(name string) string { - if root := os.Getenv("SystemRoot"); root != "" { - return filepath.Join(root, "System32", name) - } - return name -} - -func runElevatedTool(ctx context.Context, exe string, args ...string) (int, string, error) { - cmd := exec.CommandContext(ctx, exe, args...) - cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} - out, err := cmd.CombinedOutput() - text := strings.TrimSpace(string(out)) - if err == nil { - return 0, text, nil - } - var exitErr *exec.ExitError - if errors.As(err, &exitErr) { - return exitErr.ExitCode(), text, nil - } - return -1, text, err -} - -func enableOptionalFeature(ctx context.Context, spec ElevationActionSpec, feature string) (ElevationResult, error) { - code, out, err := runElevatedTool(ctx, systemExe("dism.exe"), - "/Online", "/Enable-Feature", "/FeatureName:"+feature, "/All", "/NoRestart") - if err != nil { - return ElevationResult{Action: spec.Action, ExitCode: code, Error: err.Error()}, err - } - if code == 0 || code == dismExitRebootRequired { - return ElevationResult{OK: true, Action: spec.Action, ExitCode: code, RebootRequired: spec.NeedsReboot}, nil - } - res := ElevationResult{Action: spec.Action, ExitCode: code, Error: out} - return res, fmt.Errorf("dism exited with code %d: %s", code, out) +// optionalFeatures names the Windows feature each action turns on. +var optionalFeatures = map[string]string{ + ElevateHyperVEnable: "Microsoft-Hyper-V-All", + ElevateSandboxEnable: "Containers-DisposableClientVM", } // hyperVAdminsGroupName returns the local name of the Hyper-V Administrators @@ -95,135 +36,64 @@ func hyperVAdminsGroupName() (string, error) { return "", err } name, _, _, err := sid.LookupAccount("") + return name, err +} + +// accountInHyperVAdmins reads the group's current members, not the signed-in +// token, so it also sees a membership that takes effect at the next sign-in. +func accountInHyperVAdmins(account string) bool { + u, err := user.Lookup(account) if err != nil { - return "", err + return false } - return name, nil + ids, err := u.GroupIds() + return err == nil && slices.Contains(ids, hyperVAdminsSID) } -// ExecuteElevatedAction runs a whitelisted action in the current process. The -// process must already be elevated. It never restarts Windows. -func ExecuteElevatedAction(ctx context.Context, action, targetUser string) (ElevationResult, error) { +// RunElevatedAction runs the fixed Windows tool behind a whitelisted action +// through a UAC prompt and waits for it. It never restarts Windows. +func RunElevatedAction(ctx context.Context, action, targetUser string) (ElevationResult, error) { spec, ok := LookupElevationAction(action) if !ok { return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) } - switch spec.Action { - case ElevateHyperVEnable: - return enableOptionalFeature(ctx, spec, "Microsoft-Hyper-V-All") - case ElevateSandboxEnable: - return enableOptionalFeature(ctx, spec, "Containers-DisposableClientVM") - case ElevateHyperVAddAdminGroup: - if err := ValidateElevationTargetUser(targetUser); err != nil { - return ElevationResult{Action: action, Error: err.Error()}, err - } - group, err := hyperVAdminsGroupName() - if err != nil { - return ElevationResult{Action: action, Error: err.Error()}, fmt.Errorf("find the Hyper-V Administrators group: %w", err) - } - code, out, err := runElevatedTool(ctx, systemExe("net.exe"), "localgroup", group, strings.TrimSpace(targetUser), "/add") - if err != nil { - return ElevationResult{Action: action, ExitCode: code, Error: err.Error()}, err - } - if code == 0 || isNetAlreadyMemberOutput(out) { - return ElevationResult{OK: true, Action: action, LogoffRequired: spec.NeedsLogoff}, nil - } - return ElevationResult{Action: action, ExitCode: code, Error: out}, fmt.Errorf("net localgroup exited with code %d: %s", code, out) + sysDir, err := windows.GetSystemDirectory() + if err != nil { + return ElevationResult{Action: action}, fmt.Errorf("resolve Windows System32 directory: %w", err) } - return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) -} + done := ElevationResult{OK: true, Action: action, RebootRequired: spec.NeedsReboot, LogoffRequired: spec.NeedsLogoff} -// RunElevatedAction starts exePath with the hidden __elevate subcommand through -// a UAC prompt and waits for it. The result file is created by the caller -// first and filled in place by the elevated process, so the caller can always -// read and remove it. -func RunElevatedAction(ctx context.Context, exePath, action, targetUser string) (ElevationResult, error) { - spec, ok := LookupElevationAction(action) - if !ok { - return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) - } - if spec.Action == ElevateHyperVAddAdminGroup { - if err := ValidateElevationTargetUser(targetUser); err != nil { + if feature, ok := optionalFeatures[action]; ok { + code, err := elevatedRun(ctx, filepath.Join(sysDir, "dism.exe"), + "/Online /Enable-Feature /FeatureName:"+feature+" /All /Quiet /NoRestart") + if err != nil { return ElevationResult{Action: action}, err } + if code != 0 && code != errorSuccessRebootRequired { + return ElevationResult{Action: action, ExitCode: int(code)}, fmt.Errorf("dism exited with code %d", code) + } + done.ExitCode = int(code) + return done, nil } - if strings.TrimSpace(exePath) == "" { - return ElevationResult{Action: action}, errors.New("the host executable path is unknown") - } - f, err := os.CreateTemp("", "reims-elevate-*.json") - if err != nil { - return ElevationResult{Action: action}, err - } - resultPath := f.Name() - _ = f.Close() - defer os.Remove(resultPath) - args := []string{"__elevate", "--action", spec.Action, "--result-file", resultPath} - if strings.TrimSpace(targetUser) != "" { - args = append(args, "--user", strings.TrimSpace(targetUser)) + targetUser = strings.TrimSpace(targetUser) + if err := ValidateElevationTargetUser(targetUser); err != nil { + return ElevationResult{Action: action}, err } - escaped := make([]string, len(args)) - for i, a := range args { - escaped[i] = syscall.EscapeArg(a) + if inHyperVAdminGroup(targetUser) { + return done, nil } - verb, _ := syscall.UTF16PtrFromString("runas") - file, err := syscall.UTF16PtrFromString(exePath) + group, err := hyperVAdminsGroupName() + if err != nil { + return ElevationResult{Action: action}, fmt.Errorf("find the Hyper-V Administrators group: %w", err) + } + code, err := elevatedRun(ctx, filepath.Join(sysDir, "net.exe"), + "localgroup "+syscall.EscapeArg(group)+" "+syscall.EscapeArg(targetUser)+" /add") if err != nil { return ElevationResult{Action: action}, err } - params, err := syscall.UTF16PtrFromString(strings.Join(escaped, " ")) - if err != nil { - return ElevationResult{Action: action}, err + if code != 0 && !inHyperVAdminGroup(targetUser) { + return ElevationResult{Action: action, ExitCode: int(code)}, fmt.Errorf("net localgroup exited with code %d", code) } - sei := shellExecuteInfoW{ - fMask: seeMaskNoCloseProcess | seeMaskNoAsync | seeMaskFlagNoUI, - lpVerb: verb, - lpFile: file, - lpParameters: params, - nShow: windows.SW_HIDE, - } - sei.cbSize = uint32(unsafe.Sizeof(sei)) - r, _, callErr := procShellExecuteExW.Call(uintptr(unsafe.Pointer(&sei))) - if r == 0 { - if errors.Is(callErr, windows.ERROR_CANCELLED) { - return ElevationResult{Action: action}, ErrElevationDeclined - } - return ElevationResult{Action: action}, fmt.Errorf("ShellExecuteExW runas failed: %w", callErr) - } - var exitCode uint32 - if sei.hProcess != 0 { - defer windows.CloseHandle(sei.hProcess) - for { - if ctx.Err() != nil { - return ElevationResult{Action: action}, ctx.Err() - } - ev, werr := windows.WaitForSingleObject(sei.hProcess, elevateWaitSliceMS) - if werr != nil || ev == windows.WAIT_OBJECT_0 { - break - } - } - if err := windows.GetExitCodeProcess(sei.hProcess, &exitCode); err != nil { - return ElevationResult{Action: action}, fmt.Errorf("read the elevated exit code: %w", err) - } - } - if data, rerr := os.ReadFile(resultPath); rerr == nil && len(strings.TrimSpace(string(data))) > 0 { - var res ElevationResult - if jerr := json.Unmarshal(data, &res); jerr == nil { - if res.Action == "" { - res.Action = spec.Action - } - if res.OK { - return res, nil - } - msg := res.Error - if msg == "" { - msg = fmt.Sprintf("the elevated action failed (exit code %d)", exitCode) - } - return res, errors.New(msg) - } - } - if exitCode == 0 { - return ElevationResult{OK: true, Action: spec.Action, RebootRequired: spec.NeedsReboot, LogoffRequired: spec.NeedsLogoff}, nil - } - return ElevationResult{Action: spec.Action, ExitCode: int(exitCode)}, fmt.Errorf("the elevated action exited with code %d", exitCode) + return done, nil } diff --git a/internal/host/elevate_windows_test.go b/internal/host/elevate_windows_test.go index e0daa1d..7523073 100644 --- a/internal/host/elevate_windows_test.go +++ b/internal/host/elevate_windows_test.go @@ -3,33 +3,99 @@ package host import ( - "runtime" + "context" + "errors" + "path/filepath" + "strings" "testing" - "unsafe" + + "golang.org/x/sys/windows" ) -func TestShellExecuteInfoLayoutMatchesWin32(t *testing.T) { - if runtime.GOARCH != "amd64" { - t.Skip("layout size is asserted for amd64") +// stubElevation records elevated runs instead of raising a UAC prompt. +func stubElevation(t *testing.T, code uint32, runErr error, members ...bool) *[]string { + t.Helper() + prevRun, prevMember := elevatedRun, inHyperVAdminGroup + t.Cleanup(func() { elevatedRun, inHyperVAdminGroup = prevRun, prevMember }) + runs := &[]string{} + elevatedRun = func(_ context.Context, exe, params string) (uint32, error) { + *runs = append(*runs, exe+" "+params) + return code, runErr } - if got := unsafe.Sizeof(shellExecuteInfoW{}); got != 112 { - t.Fatalf("SHELLEXECUTEINFOW is %d bytes, want 112", got) + inHyperVAdminGroup = func(string) bool { + if len(members) == 0 { + return false + } + m := members[0] + members = members[1:] + return m + } + return runs +} + +func TestRunElevatedActionEnablesFeaturesThroughSystem32(t *testing.T) { + sysDir, err := windows.GetSystemDirectory() + if err != nil { + t.Fatal(err) + } + for action, feature := range map[string]string{ + ElevateHyperVEnable: "Microsoft-Hyper-V-All", + ElevateSandboxEnable: "Containers-DisposableClientVM", + } { + runs := stubElevation(t, errorSuccessRebootRequired, nil) + res, err := RunElevatedAction(t.Context(), action, "") + if err != nil || !res.OK || !res.RebootRequired { + t.Fatalf("%s: %+v, %v", action, res, err) + } + want := filepath.Join(sysDir, "dism.exe") + " /Online /Enable-Feature /FeatureName:" + feature + " /All /Quiet /NoRestart" + if len(*runs) != 1 || (*runs)[0] != want { + t.Fatalf("%s ran %q, want %q", action, *runs, want) + } } } -func TestHyperVAdminsGroupResolvesFromTheWellKnownSID(t *testing.T) { - name, err := hyperVAdminsGroupName() - if err != nil { +func TestRunElevatedActionReportsFailures(t *testing.T) { + stubElevation(t, 50, nil) + if res, err := RunElevatedAction(t.Context(), ElevateHyperVEnable, ""); err == nil || res.OK || res.ExitCode != 50 { + t.Fatalf("a failed dism run = %+v, %v", res, err) + } + stubElevation(t, 0, ErrElevationDeclined) + if _, err := RunElevatedAction(t.Context(), ElevateHyperVEnable, ""); !errors.Is(err, ErrElevationDeclined) { + t.Fatalf("err = %v, want ErrElevationDeclined", err) + } +} + +func TestRunElevatedActionAddsTheAccountToTheHyperVGroup(t *testing.T) { + if _, err := hyperVAdminsGroupName(); err != nil { t.Skipf("this Windows has no Hyper-V Administrators group: %v", err) } - if name == "" { - t.Fatal("the group name is empty") - } -} + const account = `DESKTOP-1\Alice Smith` -func TestExecuteElevatedActionValidatesTheAccountBeforeRunning(t *testing.T) { - res, err := ExecuteElevatedAction(t.Context(), ElevateHyperVAddAdminGroup, "alice & calc") - if err == nil || res.OK { - t.Fatalf("an unsafe account name ran: %+v, %v", res, err) + runs := stubElevation(t, 0, nil) + res, err := RunElevatedAction(t.Context(), ElevateHyperVAddAdminGroup, account) + if err != nil || !res.OK || !res.LogoffRequired { + t.Fatalf("result = %+v, %v", res, err) + } + if len(*runs) != 1 || !strings.Contains((*runs)[0], `"`+account+`" /add`) { + t.Fatalf("runs = %q", *runs) + } + + runs = stubElevation(t, 0, nil, true) + if res, err := RunElevatedAction(t.Context(), ElevateHyperVAddAdminGroup, account); err != nil || !res.OK || len(*runs) != 0 { + t.Fatalf("an existing member still raised UAC: %+v, %v, %q", res, err, *runs) + } + + stubElevation(t, 2, nil, false, true) + if res, err := RunElevatedAction(t.Context(), ElevateHyperVAddAdminGroup, account); err != nil || !res.OK { + t.Fatalf("an account added meanwhile = %+v, %v", res, err) + } + stubElevation(t, 2, nil) + if res, err := RunElevatedAction(t.Context(), ElevateHyperVAddAdminGroup, account); err == nil || res.OK { + t.Fatalf("a failed net run = %+v, %v", res, err) + } + + runs = stubElevation(t, 0, nil) + if res, err := RunElevatedAction(t.Context(), ElevateHyperVAddAdminGroup, "alice & calc"); err == nil || res.OK || len(*runs) != 0 { + t.Fatalf("an unsafe account name ran: %+v, %v, %q", res, err, *runs) } } diff --git a/internal/plugin/broker.go b/internal/plugin/broker.go index 9fdab27..0ccb9fc 100644 --- a/internal/plugin/broker.go +++ b/internal/plugin/broker.go @@ -43,6 +43,8 @@ type Broker struct { // Managed VM processes spawned on behalf of drivers (decoupled from Sidecar Job Object). procs map[int]*ManagedProcess procsByRef map[string]*ManagedProcess + // VMs being spawned right now, so two requests cannot both start one. + spawning map[string]bool onNotify func(pluginID, title, body string) onVMExit func(driverID, vmName string) onVMState func(pluginID string, rep ReportedVMState) error @@ -423,15 +425,29 @@ func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID stri refKey := vmRefMapKey(driverID, vmName) if driverID != "" && vmName != "" { b.mu.Lock() - cur := b.procsByRef[refKey] - b.mu.Unlock() - if cur != nil { + busy := b.spawning[refKey] + if cur := b.procsByRef[refKey]; cur != nil && !busy { select { case <-cur.done: default: - return 0, fmt.Errorf("VM %q of driver %q is already running", vmName, driverID) + busy = true } } + if !busy { + if b.spawning == nil { + b.spawning = map[string]bool{} + } + b.spawning[refKey] = true + } + b.mu.Unlock() + if busy { + return 0, fmt.Errorf("VM %q of driver %q is already running", vmName, driverID) + } + defer func() { + b.mu.Lock() + delete(b.spawning, refKey) + b.mu.Unlock() + }() } build := func(breakaway bool) *exec.Cmd { cmd := exec.Command(exePath, args...) diff --git a/internal/plugin/rpc.go b/internal/plugin/rpc.go index 5effc59..aa9c4b8 100644 --- a/internal/plugin/rpc.go +++ b/internal/plugin/rpc.go @@ -15,6 +15,9 @@ import ( const maxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8) +// RPCMethodNotFound is the code a peer answers for a method it does not serve. +const RPCMethodNotFound = -32601 + // RPCError is a JSON-RPC 2.0 error object. type RPCError struct { Code int `json:"code"` @@ -246,7 +249,7 @@ func (c *RPCConn) dispatchInbound(env rpcEnvelope) { if h == nil { if len(env.ID) > 0 { - c.sendResponse(env.ID, nil, &RPCError{Code: -32601, Message: "method not found: " + env.Method}) + c.sendResponse(env.ID, nil, &RPCError{Code: RPCMethodNotFound, Message: "method not found: " + env.Method}) } return } diff --git a/internal/plugin/vmjob_test.go b/internal/plugin/vmjob_test.go index 958697d..f7865a1 100644 --- a/internal/plugin/vmjob_test.go +++ b/internal/plugin/vmjob_test.go @@ -142,6 +142,33 @@ func TestSpawnWithRefTracksVMAndStopsByRef(t *testing.T) { } } +func TestConcurrentSpawnsStartOneVM(t *testing.T) { + f := newBrokerFixture(t, "test.vmjob.plugin", "test.driver.one") + ref := plugin.VMRef{DriverID: "test.driver.one", Name: "race"} + errs := make(chan error, 4) + for range cap(errs) { + go func() { + _, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin", ref, f.exe, + []string{"-test.run=^TestHelperVM$"}, "", f.env("sleep")) + errs <- err + }() + } + started := 0 + for range cap(errs) { + if err := <-errs; err == nil { + started++ + } else if !strings.Contains(err.Error(), "already running") { + t.Skipf("cannot spawn a detached process in this environment: %v", err) + } + } + if started != 1 { + t.Fatalf("%d processes started for one VM", started) + } + if err := f.broker.StopManagedVMProcessByRef("test.vmjob.plugin", ref); err != nil { + t.Fatal(err) + } +} + func TestStopManagedVMProcessAllowsImmediateRespawn(t *testing.T) { f := newBrokerFixture(t, "test.vmjob.plugin", "test.driver.one") ref := plugin.VMRef{DriverID: "test.driver.one", Name: "fast-restart"} diff --git a/internal/testutil/fakedriver/fakedriver.go b/internal/testutil/fakedriver/fakedriver.go index 8011196..ef0ef1b 100644 --- a/internal/testutil/fakedriver/fakedriver.go +++ b/internal/testutil/fakedriver/fakedriver.go @@ -25,12 +25,12 @@ import ( // Environment variables that configure the Sidecar process. const ( - EnvMode = "REIMS_FAKE_DRIVER_MODE" // "hosted" or "process" - EnvDriverID = "REIMS_FAKE_DRIVER_ID" // default "test.driver." - EnvRoot = "REIMS_FAKE_DRIVER_ROOT" // when set, each VM gets / - EnvVMTest = "REIMS_FAKE_DRIVER_VMTEST" // test function the VM process runs - EnvVMRun = "REIMS_FAKE_DRIVER_VMRUN" // set in the VM process - EnvVMStop = "REIMS_FAKE_DRIVER_VMSTOP" // stop file the VM process watches + EnvMode = "REIMS_FAKE_DRIVER_MODE" // "hosted" or "process" + EnvDriverID = "REIMS_FAKE_DRIVER_ID" // default "test.driver." + EnvRoot = "REIMS_FAKE_DRIVER_ROOT" // when set, each VM gets / + EnvVMTest = "REIMS_FAKE_DRIVER_VMTEST" // test function the VM process runs + EnvVMRun = "REIMS_FAKE_DRIVER_VMRUN" // set in the VM process + EnvVMStop = "REIMS_FAKE_DRIVER_VMSTOP" // stop file the VM process watches ) type vm struct { diff --git a/pkg/drivertest/drivertest.go b/pkg/drivertest/drivertest.go index 94f08a4..69fc012 100644 --- a/pkg/drivertest/drivertest.go +++ b/pkg/drivertest/drivertest.go @@ -175,7 +175,7 @@ type Config struct { } var ( - validStates = map[string]bool{"stopped": true, "starting": true, "running": true, "stopping": true, "suspended": true, "broken": true} + validStates = map[string]bool{"stopped": true, "starting": true, "running": true, "stopping": true, "suspended": true, "broken": true} endpointKinds = map[string]bool{"ssh": true, "wsl": true, "rdp": true, "vmconnect": true, "adb": true} ) diff --git a/pkg/pluginsdk/sdk.go b/pkg/pluginsdk/sdk.go index 2940a3a..7263828 100644 --- a/pkg/pluginsdk/sdk.go +++ b/pkg/pluginsdk/sdk.go @@ -452,8 +452,9 @@ func (s *Server) MaterializeSecret(ctx context.Context, req MaterializeSecretReq // DownloadRequest asks the host to download URL to Dest. The plugin must // declare a `net:` permission for the URL's origin (HTTPS, or HTTP for // loopback). Dest is relative to the plugin's data folder, or an absolute path -// inside it or inside a VM root the plugin's driver declared. SHA256 (or -// SHA256URL with SHA256Name selecting a line) makes the host verify the file. +// inside it or inside a VM root the plugin's driver declared. The host verifies +// every file, so SHA256 or SHA256URL (with SHA256Name selecting a line) is +// required. type DownloadRequest struct { URL string `json:"url"` SHA256 string `json:"sha256,omitempty"` @@ -500,7 +501,6 @@ type ElevationResult struct { ExitCode int `json:"exit_code,omitempty"` RebootRequired bool `json:"reboot_required,omitempty"` LogoffRequired bool `json:"logoff_required,omitempty"` - Error string `json:"error,omitempty"` } // RequestElevation asks the host to run one whitelisted Windows elevation