Files
Reims-Go/internal/plugin/vmjob_test.go
T
NwflowerandClaude Opus 5.5 44e2174fff fix: harden guest driver host APIs
- run elevated actions as fixed System32 tools instead of a hidden subcommand
- require a SHA-256 for plugin downloads
- keep records of secret files that could not be deleted, and never overwrite
  files the host did not create
- stop two concurrent requests from starting the same VM
- drop invalid endpoints instead of failing the whole VM list, and reject ssh
  users and IPv6 zones that could inject command-line text
- accept driver screenshots only at the requested path
- do not treat an unreadable guest phase as normal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:07:46 -07:00

303 lines
11 KiB
Go

package plugin_test
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/plugin"
)
// TestHelperVM acts as a VM executable when invoked through the compiled test
// binary: "sleep" runs until its stop file appears, "launch" starts a child
// that sleeps and exits at once (the way a launcher starts an emulator).
func TestHelperVM(t *testing.T) {
mode := os.Getenv("REIMS_TEST_VM")
if mode == "" {
return
}
stop := os.Getenv("REIMS_TEST_VM_STOP")
switch mode {
case "launch":
child := exec.Command(os.Args[0], "-test.run=^TestHelperVM$")
child.Env = append(os.Environ(), "REIMS_TEST_VM=sleep")
if err := child.Start(); err != nil {
os.Exit(3)
}
os.Exit(0)
case "sleep":
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
if _, err := os.Stat(stop); err == nil {
os.Exit(0)
}
time.Sleep(20 * time.Millisecond)
}
os.Exit(4)
}
}
type brokerFixture struct {
broker *plugin.Broker
exe string
stop string
exited chan string
}
// newBrokerFixture registers one builtin plugin owning the given drivers.
func newBrokerFixture(t *testing.T, pluginID string, drivers ...string) *brokerFixture {
t.Helper()
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
reg := plugin.NewRegistry(nil)
var gds []plugin.GuestDriverContribution
for _, id := range drivers {
gds = append(gds, plugin.GuestDriverContribution{ID: id, Name: plugin.LocalizedText{EnUS: id}, RuntimeKind: "external"})
}
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{
ID: pluginID, Version: "1.0.0", Name: plugin.LocalizedText{EnUS: pluginID},
Permissions: []string{"driver:vm", "process:spawn", "vm:control"},
Contributes: plugin.Contributes{GuestDrivers: gds},
},
Source: plugin.SourceBuiltin, Desired: true,
Activate: func(context.Context, *plugin.Scope) error { return nil },
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
broker := plugin.NewBroker(plugin.NewPluginsLayout(t.TempDir()), reg, nil)
f := &brokerFixture{broker: broker, exe: exe, stop: filepath.Join(t.TempDir(), "stop"), exited: make(chan string, 8)}
broker.SetVMExitHandler(func(driverID, vmName string) { f.exited <- driverID + "/" + vmName })
t.Cleanup(func() { _ = os.WriteFile(f.stop, nil, 0o644) })
return f
}
func (f *brokerFixture) env(mode string) []string {
return []string{"REIMS_TEST_VM=" + mode, "REIMS_TEST_VM_STOP=" + f.stop}
}
func (f *brokerFixture) waitExit(t *testing.T, want string) {
t.Helper()
select {
case got := <-f.exited:
if got != want {
t.Fatalf("exit handler fired for %q, want %q", got, want)
}
case <-time.After(15 * time.Second):
t.Fatalf("timed out waiting for %s to exit", want)
}
}
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
if cond() {
return
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s", what)
}
func TestSpawnWithRefTracksVMAndStopsByRef(t *testing.T) {
f := newBrokerFixture(t, "test.vmjob.plugin", "test.driver.one")
ref := plugin.VMRef{DriverID: "test.driver.one", Name: "dev"}
pid, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin", ref, f.exe,
[]string{"-test.run=^TestHelperVM$"}, "", f.env("sleep"))
if err != nil {
t.Skipf("cannot spawn a detached process in this environment: %v", err)
}
if !f.broker.IsManagedVMRunning(ref.DriverID, ref.Name) || !f.broker.IsManagedVMRunningForPlugin("test.vmjob.plugin", ref) {
t.Fatal("running VM not reported as running")
}
if !f.broker.IsManagedProcessRunningForPlugin("test.vmjob.plugin", pid) {
t.Fatal("PID lookup does not see the VM")
}
if pids := f.broker.ManagedVMPIDs(ref.DriverID, ref.Name); len(pids) == 0 {
t.Fatal("ManagedVMPIDs is empty for a running VM")
}
// Same name under a different driver id is a different VM.
if f.broker.IsManagedVMRunning("test.driver.two", ref.Name) {
t.Fatal("same-name VM of another driver reported running")
}
if _, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin", ref, f.exe,
[]string{"-test.run=^TestHelperVM$"}, "", f.env("sleep")); err == nil {
t.Fatal("a second spawn of the same running VM was accepted")
}
if err := f.broker.StopManagedVMProcessByRef("test.vmjob.plugin", ref); err != nil {
t.Fatalf("StopManagedVMProcessByRef: %v", err)
}
f.waitExit(t, "test.driver.one/dev")
if f.broker.IsManagedVMRunning(ref.DriverID, ref.Name) {
t.Fatal("stopped VM still reported running")
}
}
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"}
for i := 0; i < 5; i++ {
if _, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin", ref, f.exe,
[]string{"-test.run=^TestHelperVM$"}, "", f.env("sleep")); err != nil {
if i == 0 {
t.Skipf("cannot spawn a detached process in this environment: %v", err)
}
t.Fatalf("respawn iteration %d immediately after stop failed: %v", i, err)
}
if err := f.broker.StopManagedVMProcessByRef("test.vmjob.plugin", ref); err != nil {
t.Fatalf("StopManagedVMProcessByRef iteration %d: %v", i, err)
}
if f.broker.IsManagedVMRunning(ref.DriverID, ref.Name) {
t.Fatalf("iteration %d: VM still reported running right after stop returned", i)
}
}
}
func TestSpawnWithRefInfersSingleDriverAndRejectsForeignDriver(t *testing.T) {
f := newBrokerFixture(t, "test.vmjob.plugin", "test.driver.one")
if _, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin",
plugin.VMRef{DriverID: "someone.else.driver", Name: "dev"}, f.exe, nil, "", nil); err == nil || !strings.Contains(err.Error(), "does not declare") {
t.Fatalf("spawn for a foreign driver = %v", err)
}
pid, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin",
plugin.VMRef{Name: "dev"}, f.exe, []string{"-test.run=^TestHelperVM$"}, "", f.env("sleep"))
if err != nil {
t.Skipf("cannot spawn a detached process in this environment: %v", err)
}
if !f.broker.IsManagedVMRunning("test.driver.one", "dev") {
t.Fatal("an empty driver_id did not default to the plugin's only driver")
}
_ = os.WriteFile(f.stop, nil, 0o644)
eventually(t, "VM exit", func() bool { return !f.broker.IsManagedProcessRunning(pid) })
}
func TestSpawnWithRefRequiresDriverWhenSeveralDeclared(t *testing.T) {
f := newBrokerFixture(t, "test.vmjob.plugin", "test.driver.one", "test.driver.two")
if _, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin",
plugin.VMRef{Name: "dev"}, f.exe, nil, "", nil); err == nil || !strings.Contains(err.Error(), "driver_id") {
t.Fatalf("ambiguous driver = %v", err)
}
}
func TestVMJobKeepsRunningUntilLastChildExits(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("process-tree tracking relies on Windows job objects")
}
f := newBrokerFixture(t, "test.vmjob.plugin", "test.driver.one")
ref := plugin.VMRef{DriverID: "test.driver.one", Name: "emu"}
pid, err := f.broker.SpawnManagedVMProcessWithRef(context.Background(), "test.vmjob.plugin", ref, f.exe,
[]string{"-test.run=^TestHelperVM$"}, "", f.env("launch"))
if err != nil {
t.Skipf("cannot spawn a detached process in this environment: %v", err)
}
// The launcher exits right away; its child keeps the VM alive.
eventually(t, "launcher exit and child start", func() bool {
pids := f.broker.ManagedVMPIDs(ref.DriverID, ref.Name)
for _, p := range pids {
if int(p) != pid {
return true
}
}
return false
})
select {
case got := <-f.exited:
t.Fatalf("exit handler fired (%s) while a child process is alive", got)
case <-time.After(300 * time.Millisecond):
}
if !f.broker.IsManagedVMRunning(ref.DriverID, ref.Name) {
t.Fatal("VM reported stopped while its child process is alive")
}
if err := f.broker.SetManagedVMAffinity(ref.DriverID, ref.Name, 1); err != nil {
t.Fatalf("SetManagedVMAffinity: %v", err)
}
if err := f.broker.SetManagedVMAffinity(ref.DriverID, ref.Name, 0); err != nil {
t.Fatalf("lifting the affinity limit: %v", err)
}
_ = os.WriteFile(f.stop, nil, 0o644)
f.waitExit(t, "test.driver.one/emu")
}
func TestReportVMStateAcceptsOwnDriverOnly(t *testing.T) {
f := newBrokerFixture(t, "test.vmjob.plugin", "test.driver.one")
var got []plugin.ReportedVMState
f.broker.SetVMStateHandler(func(pluginID string, rep plugin.ReportedVMState) error {
got = append(got, rep)
return nil
})
ready := true
own := plugin.ReportedVMState{
Ref: plugin.VMRef{DriverID: "test.driver.one", Name: "dev"}, State: "running", Ready: &ready,
Endpoints: []plugin.VMEndpoint{{Kind: "wsl", Distro: "dev", Ready: true}},
}
if err := f.broker.ReportVMState("test.vmjob.plugin", own); err != nil {
t.Fatalf("own driver report rejected: %v", err)
}
// An empty driver ID defaults to the plugin's only driver.
noDriver := own
noDriver.Ref.DriverID = ""
if err := f.broker.ReportVMState("test.vmjob.plugin", noDriver); err != nil {
t.Fatalf("report without driver rejected: %v", err)
}
if len(got) != 2 || got[1].Ref.DriverID != "test.driver.one" {
t.Fatalf("handler saw %+v", got)
}
spoof := own
spoof.Ref.DriverID = "someone.else.driver"
if err := f.broker.ReportVMState("test.vmjob.plugin", spoof); err == nil {
t.Fatal("a report for a foreign driver was accepted")
}
badState := own
badState.State = "exploded"
if err := f.broker.ReportVMState("test.vmjob.plugin", badState); err == nil {
t.Fatal("an unknown state was accepted")
}
noName := own
noName.Ref.Name = " "
if err := f.broker.ReportVMState("test.vmjob.plugin", noName); err == nil {
t.Fatal("a report without a VM name was accepted")
}
if len(got) != 2 {
t.Fatalf("rejected reports reached the handler: %d", len(got))
}
if err := f.broker.ReportVMState("unknown.plugin", own); err == nil {
t.Fatal("an unknown plugin's report was accepted")
}
}