package app import ( "context" "errors" "os" "path/filepath" "testing" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/dataroot" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" ) func osMkdirAllForTest(p string) error { return os.MkdirAll(p, 0o755) } func fileExistsForTest(p string) bool { _, err := os.Stat(p) return err == nil } func datarootStatusBusyForTest(dir string) dataroot.Status { return dataroot.Status{Dir: dir, ReadOnly: true, Reason: dataroot.ReasonBusy} } func TestHypervisorSwitchGateAndBootGuards(t *testing.T) { origInspect := inspectHostForHypervisor origSet := setHypervisorBootElevatedFn origRecord := recordPendingHypervisorBootFn t.Cleanup(func() { inspectHostForHypervisor = origInspect setHypervisorBootElevatedFn = origSet recordPendingHypervisorBootFn = origRecord }) dir := t.TempDir() cfg := config.Default() cfg.DataRoot = dir cfg.Locale = i18n.ZhCN a := &App{ cfg: cfg, transitions: make(map[string]string), pendingChanges: make(map[string][]PendingChange), } var elevatedCalls int var lastEnable bool var mockSetErr error liveWHPX := host.WHPXReady var recordedPending string inspectHostForHypervisor = func(dataRoot string) host.Report { return host.Report{DataRoot: dataRoot, WHPX: liveWHPX} } setHypervisorBootElevatedFn = func(_ context.Context, enable bool) error { elevatedCalls++ lastEnable = enable return mockSetErr } recordPendingHypervisorBootFn = func(_ string, st host.WHPXState, enable bool) string { recordedPending = host.ResolvePendingHypervisorTarget(st, enable) return recordedPending } // 1. Default off; toggling the UI gate persists locally without invoking UAC. if a.cfg.EnableHypervisorSwitch { t.Fatal("EnableHypervisorSwitch must default to false") } if err := a.SetEnableHypervisorSwitch(true); err != nil { t.Fatalf("SetEnableHypervisorSwitch(true): %v", err) } if elevatedCalls != 0 { t.Fatalf("SetEnableHypervisorSwitch must never run elevated commands, got %d calls", elevatedCalls) } saved, err := config.Load(filepath.Join(dir, "reims-go.json")) if err != nil || !saved.EnableHypervisorSwitch { t.Fatalf("persisted config EnableHypervisorSwitch=%v err=%v", saved != nil && saved.EnableHypervisorSwitch, err) } // 2. Running VM blocks disabling Hyper-V before UAC is even requested. a.lastVMs = []driver.VMListItem{{Name: "mac", State: "running"}} a.lastVMsAt = time.Now() if changed, err := a.SetHypervisorBoot(false); err == nil || changed { t.Fatalf("expected busy VM error, got changed=%v err=%v", changed, err) } else { var coded *i18n.CodedError if !errors.As(err, &coded) || coded.Code != "E_HOST_HYPERVISOR_BUSY_VMS" { t.Fatalf("unexpected coded error: %#v (%v)", coded, err) } } if elevatedCalls != 0 { t.Fatalf("busy VM must block before UAC, got %d calls", elevatedCalls) } // 3. Stopped VM + active vm-create task also blocks disabling Hyper-V. a.lastVMs = []driver.VMListItem{{Name: "mac", State: "stopped"}} taskID := tasks.start("vm-create", "new-mac", "new-mac", func() {}) if changed, err := a.SetHypervisorBoot(false); err == nil || changed { tasks.finish(taskID, "", context.Canceled) t.Fatalf("expected busy task error, got changed=%v err=%v", changed, err) } else { var coded *i18n.CodedError if !errors.As(err, &coded) || coded.Code != "E_HOST_HYPERVISOR_BUSY_TASKS" { tasks.finish(taskID, "", context.Canceled) t.Fatalf("unexpected task coded error: %#v (%v)", coded, err) } } tasks.finish(taskID, "", context.Canceled) tasks.dismiss(taskID) // 4. Declining UAC returns (false, nil) and leaves pending state untouched. mockSetErr = host.ErrElevationDeclined if changed, err := a.SetHypervisorBoot(false); err != nil || changed { t.Fatalf("UAC decline should return (false, nil), got (%v, %v)", changed, err) } if _, err := a.SetHypervisorBoot(true); err != nil { t.Fatalf("SetHypervisorBoot(true) on UAC decline should return nil, got %v", err) } if recordedPending != "" { t.Fatalf("UAC decline must not record pending boot, got %q", recordedPending) } // 5. Command failure returns structured E_HOST_HYPERVISOR_SET_FAILED. mockSetErr = &host.HypervisorExecError{Command: "bcdedit", ExitCode: 1} if changed, err := a.SetHypervisorBoot(false); err == nil || changed { t.Fatalf("expected exec failure error, got (%v, %v)", changed, err) } else { var coded *i18n.CodedError if !errors.As(err, &coded) || coded.Code != "E_HOST_HYPERVISOR_SET_FAILED" { t.Fatalf("unexpected exec coded error: %#v (%v)", coded, err) } } // 6. Successful disable while WHPXReady sets pending="off", and undo clears it. mockSetErr = nil if changed, err := a.SetHypervisorBoot(false); err != nil || !changed { t.Fatalf("SetHypervisorBoot(false) = (%v, %v), want (true, nil)", changed, err) } if lastEnable != false || recordedPending != host.HypervisorBootOff { t.Fatalf("after disable: lastEnable=%v pending=%q", lastEnable, recordedPending) } if changed, err := a.SetHypervisorBoot(true); err != nil || !changed { t.Fatalf("undo SetHypervisorBoot(true) = (%v, %v), want (true, nil)", changed, err) } if lastEnable != true || recordedPending != "" { t.Fatalf("after undo: lastEnable=%v pending=%q", lastEnable, recordedPending) } // 7. SetHypervisorBoot(true) when hypervisor_off sets pending="auto". liveWHPX = host.WHPXHypervisorOff if _, err := a.SetHypervisorBoot(true); err != nil { t.Fatalf("SetHypervisorBoot(true) from hypervisor_off: %v", err) } if lastEnable != true || recordedPending != host.HypervisorBootAuto { t.Fatalf("after SetHypervisorBoot(true): lastEnable=%v pending=%q", lastEnable, recordedPending) } } func TestHypervisorReadOnlyAndFirstRunIsolation(t *testing.T) { origInspect := inspectHostForHypervisor origSet := setHypervisorBootElevatedFn t.Cleanup(func() { inspectHostForHypervisor = origInspect setHypervisorBootElevatedFn = origSet }) dir := t.TempDir() // Pre-create /tmp to prove neither read-only mode nor unconfirmed first-run // writes hypervisor-boot-pending.json into it. if err := config.Default().EnsureDirs(); false { t.Fatal(err) } tmpSub := filepath.Join(dir, "tmp") if err := osMkdirAllForTest(tmpSub); err != nil { t.Fatal(err) } var elevatedCalls int inspectHostForHypervisor = func(dataRoot string) host.Report { return host.Report{DataRoot: dataRoot, WHPX: host.WHPXMissing} } setHypervisorBootElevatedFn = func(_ context.Context, _ bool) error { elevatedCalls++ return nil } // Case A: Read-only data root must roll back in-memory EnableHypervisorSwitch // on save failure and block SetHypervisorBoot before UAC or disk writes. roCfg := config.Default() roCfg.DataRoot = dir roCfg.Locale = i18n.EnUS roApp := &App{ cfg: roCfg, transitions: make(map[string]string), pendingChanges: make(map[string][]PendingChange), root: datarootStatusBusyForTest(dir), } if err := roApp.SetEnableHypervisorSwitch(true); err == nil { t.Fatal("expected SetEnableHypervisorSwitch to fail in read-only mode") } if roApp.cfg.EnableHypervisorSwitch { t.Fatal("in-memory EnableHypervisorSwitch leaked to true after failed read-only save") } if changed, err := roApp.SetHypervisorBoot(false); err == nil || changed { t.Fatalf("expected SetHypervisorBoot(false) to fail in read-only mode, got (%v, %v)", changed, err) } if elevatedCalls != 0 { t.Fatalf("read-only mode must block before UAC, got %d elevated calls", elevatedCalls) } if fileExistsForTest(filepath.Join(tmpSub, "hypervisor-boot-pending.json")) { t.Fatal("read-only mode must never write hypervisor-boot-pending.json") } // Case B: First-run setup (needsSetup=true) allows SetHypervisorBoot(true) in memory, // but must never write to the unconfirmed default candidate folder on disk. firstCfg := config.Default() firstCfg.DataRoot = dir firstCfg.Locale = i18n.ZhCN firstApp := &App{ cfg: firstCfg, needsSetup: true, transitions: make(map[string]string), pendingChanges: make(map[string][]PendingChange), } if _, err := firstApp.SetHypervisorBoot(true); err != nil { t.Fatalf("SetHypervisorBoot(true) during first-run setup: %v", err) } if elevatedCalls != 1 { t.Fatalf("expected 1 elevated call during first-run SetHypervisorBoot(true), got %d", elevatedCalls) } if fileExistsForTest(filepath.Join(tmpSub, "hypervisor-boot-pending.json")) { t.Fatal("first-run SetHypervisorBoot(true) must not write to unconfirmed candidate dataRoot/tmp") } // Clean up in-memory pending state. _ = host.RecordPendingHypervisorBoot("", host.WHPXReady, true) }