package app import ( "context" "encoding/json" "errors" "os" "path/filepath" "strings" "sync" "sync/atomic" "testing" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/testutil/fakedriver" ) type elevateTestEnv struct { app *App h *fakedriver.Harness plugin string mu sync.Mutex prompts []ElevationPrompt dismissed []string runs atomic.Int32 runArgs []string runErr error runRes host.ElevationResult // onPrompt answers a prompt; nil leaves it pending. onPrompt func(ElevationPrompt) } func newElevateTestEnv(t *testing.T) *elevateTestEnv { t.Helper() h := fakedriver.NewHarness(t) e := &elevateTestEnv{h: h, plugin: "test.fake.elev"} h.Add("hosted", e.plugin, "test.driver.elev") e.app = &App{cfg: &config.Config{DataRoot: h.DataRoot}} e.app.elevateEmit = func(p ElevationPrompt) { e.mu.Lock() e.prompts = append(e.prompts, p) answer := e.onPrompt e.mu.Unlock() if answer != nil { go answer(p) } } e.app.elevateDismiss = func(id string) { e.mu.Lock() e.dismissed = append(e.dismissed, id) e.mu.Unlock() } e.app.elevateRunner = func(_ context.Context, action, targetUser string) (host.ElevationResult, error) { e.runs.Add(1) e.mu.Lock() e.runArgs = []string{action, targetUser} e.mu.Unlock() if e.runErr != nil { return host.ElevationResult{}, e.runErr } return e.runRes, nil } return e } func (e *elevateTestEnv) request(ctx context.Context, pluginID, action string) (any, error) { raw, _ := json.Marshal(map[string]any{"action": action}) return e.app.requestElevation(ctx, e.h.Broker, e.h.Registry, pluginID, raw) } func (e *elevateTestEnv) promptCount() int { e.mu.Lock() defer e.mu.Unlock() return len(e.prompts) } func (e *elevateTestEnv) dismissedIDs() []string { e.mu.Lock() defer e.mu.Unlock() return append([]string(nil), e.dismissed...) } func (e *elevateTestEnv) auditLog(t *testing.T) string { t.Helper() data, err := os.ReadFile(filepath.Join(e.h.DataRoot, "plugins", "logs", e.plugin+".log")) if err != nil && !os.IsNotExist(err) { t.Fatal(err) } return string(data) } func (e *elevateTestEnv) answer(approved bool) { e.onPrompt = func(p ElevationPrompt) { _ = e.app.ResolveElevationRequest(p.ID, approved) } } func TestElevationRejectsAPluginWithoutDriverPermission(t *testing.T) { e := newElevateTestEnv(t) if _, err := e.request(context.Background(), "nobody.plugin", host.ElevateHyperVEnable); err == nil { t.Fatal("an unknown plugin was allowed to request elevation") } if e.promptCount() != 0 || e.runs.Load() != 0 { t.Fatalf("prompts=%d runs=%d, want 0 and 0", e.promptCount(), e.runs.Load()) } } func TestElevationRejectsActionsOutsideTheWhitelist(t *testing.T) { e := newElevateTestEnv(t) for _, action := range []string{"shell.exec", "", "HYPERV.ENABLE"} { if _, err := e.request(context.Background(), e.plugin, action); err == nil { t.Fatalf("action %q was accepted", action) } } if e.promptCount() != 0 || e.runs.Load() != 0 { t.Fatalf("prompts=%d runs=%d, want 0 and 0", e.promptCount(), e.runs.Load()) } } func TestElevationIsRefusedWithoutADesktopWindow(t *testing.T) { e := newElevateTestEnv(t) e.app.elevateEmit = nil _, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable) if err == nil || !strings.Contains(err.Error(), "elevation_unavailable") { t.Fatalf("err = %v, want elevation_unavailable", err) } if e.runs.Load() != 0 { t.Fatal("the elevated runner started without a confirmation window") } if !strings.Contains(e.auditLog(t), "ELEVATE_UNAVAILABLE") { t.Fatalf("audit log lacks ELEVATE_UNAVAILABLE:\n%s", e.auditLog(t)) } } func TestElevationDeclinedInTheDialogRunsNothing(t *testing.T) { e := newElevateTestEnv(t) e.answer(false) _, err := e.request(context.Background(), e.plugin, host.ElevateSandboxEnable) if err == nil || !strings.Contains(err.Error(), "elevation_denied") { t.Fatalf("err = %v, want elevation_denied", err) } if e.runs.Load() != 0 { t.Fatal("the runner started after the user declined") } if log := e.auditLog(t); !strings.Contains(log, "ELEVATE_DENIED") || strings.Contains(log, "ELEVATE_APPROVED") { t.Fatalf("unexpected audit log:\n%s", log) } } func TestElevationApprovedRunsTheActionOnce(t *testing.T) { e := newElevateTestEnv(t) e.answer(true) e.runRes = host.ElevationResult{OK: true, Action: host.ElevateHyperVEnable, RebootRequired: true} res, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable) if err != nil { t.Fatal(err) } got, ok := res.(host.ElevationResult) if !ok || !got.OK || !got.RebootRequired { t.Fatalf("result = %#v", res) } if e.runs.Load() != 1 || e.runArgs[0] != host.ElevateHyperVEnable { t.Fatalf("runs=%d args=%v", e.runs.Load(), e.runArgs) } e.mu.Lock() p := e.prompts[0] e.mu.Unlock() if p.PluginID != e.plugin || p.Action != host.ElevateHyperVEnable || !p.NeedsReboot || p.ID == "" { t.Fatalf("prompt = %+v", p) } log := e.auditLog(t) for _, tag := range []string{"ELEVATE_APPROVED", "ELEVATE_OK"} { if !strings.Contains(log, tag) { t.Fatalf("audit log lacks %s:\n%s", tag, log) } } } func TestElevationForTheAdminGroupNamesTheCurrentAccount(t *testing.T) { e := newElevateTestEnv(t) e.answer(true) e.runRes = host.ElevationResult{OK: true, Action: host.ElevateHyperVAddAdminGroup, LogoffRequired: true} if _, err := e.request(context.Background(), e.plugin, host.ElevateHyperVAddAdminGroup); err != nil { t.Fatal(err) } if e.runArgs[0] != host.ElevateHyperVAddAdminGroup || strings.TrimSpace(e.runArgs[1]) == "" { t.Fatalf("runner args = %v, want the action and a non-empty account", e.runArgs) } } func TestElevationDeclinedAtUACIsADenial(t *testing.T) { e := newElevateTestEnv(t) e.answer(true) e.runErr = host.ErrElevationDeclined _, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable) if err == nil || !strings.Contains(err.Error(), "elevation_denied") { t.Fatalf("err = %v, want elevation_denied", err) } if !strings.Contains(e.auditLog(t), "ELEVATE_UAC_DECLINED") { t.Fatalf("audit log lacks ELEVATE_UAC_DECLINED:\n%s", e.auditLog(t)) } } func TestElevationRunnerFailureIsReported(t *testing.T) { e := newElevateTestEnv(t) e.answer(true) e.runErr = errors.New("dism exited with code 50") _, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable) if err == nil || !strings.Contains(err.Error(), "dism exited") { t.Fatalf("err = %v", err) } if !strings.Contains(e.auditLog(t), "ELEVATE_ERROR") { t.Fatalf("audit log lacks ELEVATE_ERROR:\n%s", e.auditLog(t)) } } func TestConcurrentElevationRequestsShareOneDialogAtATime(t *testing.T) { e := newElevateTestEnv(t) e.runRes = host.ElevationResult{OK: true} var active, peak atomic.Int32 e.onPrompt = func(p ElevationPrompt) { n := active.Add(1) for { old := peak.Load() if n <= old || peak.CompareAndSwap(old, n) { break } } time.Sleep(50 * time.Millisecond) active.Add(-1) _ = e.app.ResolveElevationRequest(p.ID, true) } var wg sync.WaitGroup for _, action := range []string{host.ElevateHyperVEnable, host.ElevateSandboxEnable} { wg.Add(1) go func() { defer wg.Done() if _, err := e.request(context.Background(), e.plugin, action); err != nil { t.Errorf("%s: %v", action, err) } }() } wg.Wait() if e.promptCount() != 2 || e.runs.Load() != 2 { t.Fatalf("prompts=%d runs=%d, want 2 and 2", e.promptCount(), e.runs.Load()) } if peak.Load() != 1 { t.Fatalf("%d dialogs were open at once", peak.Load()) } } func TestCancelPendingElevationsDeniesWaitingRequests(t *testing.T) { e := newElevateTestEnv(t) errc := make(chan error, 1) go func() { _, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable) errc <- err }() waitFor(t, "the prompt to open", func() bool { return e.promptCount() == 1 }) e.app.cancelPendingElevations() select { case err := <-errc: if err == nil || !strings.Contains(err.Error(), "elevation_denied") { t.Fatalf("err = %v, want elevation_denied", err) } case <-time.After(5 * time.Second): t.Fatal("the waiting request was not released") } if e.runs.Load() != 0 { t.Fatal("the runner started after shutdown") } e.mu.Lock() wantID := e.prompts[0].ID e.mu.Unlock() if got := e.dismissedIDs(); len(got) != 1 || got[0] != wantID { t.Fatalf("dismissed = %v, want [%s]", got, wantID) } } func TestElevationTimesOutWithoutAnAnswer(t *testing.T) { prev := elevatePromptTimeout elevatePromptTimeout = 50 * time.Millisecond t.Cleanup(func() { elevatePromptTimeout = prev }) e := newElevateTestEnv(t) _, err := e.request(context.Background(), e.plugin, host.ElevateHyperVEnable) if err == nil || !strings.Contains(err.Error(), "elevation_denied") { t.Fatalf("err = %v, want elevation_denied", err) } if e.runs.Load() != 0 || !strings.Contains(e.auditLog(t), "ELEVATE_TIMEOUT") { t.Fatalf("runs=%d, audit:\n%s", e.runs.Load(), e.auditLog(t)) } e.mu.Lock() wantID := e.prompts[0].ID e.mu.Unlock() if got := e.dismissedIDs(); len(got) != 1 || got[0] != wantID { t.Fatalf("dismissed = %v, want [%s]", got, wantID) } } func TestElevationContextCancelDismissesTheDialog(t *testing.T) { e := newElevateTestEnv(t) ctx, cancel := context.WithCancel(context.Background()) errc := make(chan error, 1) go func() { _, err := e.request(ctx, e.plugin, host.ElevateSandboxEnable) errc <- err }() waitFor(t, "the prompt to open", func() bool { return e.promptCount() == 1 }) cancel() select { case err := <-errc: if err == nil || !strings.Contains(err.Error(), "elevation_denied") { t.Fatalf("err = %v, want elevation_denied", err) } case <-time.After(5 * time.Second): t.Fatal("the canceled request was not released") } if e.runs.Load() != 0 || !strings.Contains(e.auditLog(t), "ELEVATE_CANCELED") { t.Fatalf("runs=%d, audit:\n%s", e.runs.Load(), e.auditLog(t)) } e.mu.Lock() wantID := e.prompts[0].ID e.mu.Unlock() if got := e.dismissedIDs(); len(got) != 1 || got[0] != wantID { t.Fatalf("dismissed = %v, want [%s]", got, wantID) } } func TestResolveElevationRequestIgnoresUnknownIDs(t *testing.T) { e := newElevateTestEnv(t) if err := e.app.ResolveElevationRequest("elevate-999", true); err != nil { t.Fatalf("an expired request must be ignored, got %v", err) } }