package runtime import ( "bytes" "context" "errors" "os" "path/filepath" "testing" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/i18n" ) func TestLaunchPolicyUnreadableSelection(t *testing.T) { cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current"} if err := os.WriteFile(filepath.Join(cfg.DataRoot, "reims-go.json"), []byte("{"), 0o600); err != nil { t.Fatal(err) } current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)} for _, enabled := range []bool{false, true} { cfg.QEMUASLR = enabled var warning bytes.Buffer err := checkLaunchASLR(t.Context(), cfg, current.QemuPath(), &warning, func(_, _ string) error { t.Fatal("policy applied without a confirmed selection") return nil }) if err != nil || warning.Len() == 0 { t.Fatalf("ASLR enabled=%t: launch error %v, warning %q", enabled, err, &warning) } } } func TestLaunchPolicyBusy(t *testing.T) { for _, tc := range []struct { name string lock func(context.Context, string) (func(), error) }{ {"pending selection", LockSelection}, {"runtime directory in use", lockRuntimeDirectoriesContext}, } { t.Run(tc.name, func(t *testing.T) { cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "current", QEMUASLR: true} current := Installed{Dir: filepath.Join(cfg.RuntimesDir(), cfg.ActiveRuntime)} writeFakeRuntime(t, current.Dir, Manifest{Commit: cfg.ActiveRuntime}) release, err := tc.lock(t.Context(), cfg.RuntimesDir()) if err != nil { t.Fatal(err) } defer release() var warning bytes.Buffer err = checkLaunchASLR(t.Context(), cfg, current.QemuPath(), &warning, func(_, _ string) error { t.Fatal("policy applied while its lock was in use") return nil }) if err != nil || warning.Len() == 0 { t.Fatalf("busy policy: launch error %v, warning %q", err, &warning) } }) } } func TestLaunchPolicyReturnsCallerCancellation(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) cancel() err := checkLaunchASLR(ctx, config.Config{}, "", nil, nil) if !errors.Is(err, context.Canceled) { t.Fatalf("cancelled launch returned %v", err) } } func TestBusyLaunchPolicyRejectsSupersededRuntime(t *testing.T) { cfg := config.Config{DataRoot: t.TempDir(), ActiveRuntime: "old", QEMUASLR: true} old := Installed{Dir: filepath.Join(cfg.RuntimesDir(), "old")} writeFakeRuntime(t, old.Dir, Manifest{Commit: "old"}) writeFakeRuntime(t, filepath.Join(cfg.RuntimesDir(), "new"), Manifest{Commit: "new"}) published := cfg published.ActiveRuntime = "new" if err := config.Save("", &published); err != nil { t.Fatal(err) } release, err := LockSelection(t.Context(), cfg.RuntimesDir()) if err != nil { t.Fatal(err) } defer release() err = checkLaunchASLR(t.Context(), cfg, old.QemuPath(), nil, func(_, _ string) error { t.Fatal("policy applied to a superseded runtime") return nil }) var coded *i18n.CodedError if !errors.As(err, &coded) || coded.Code != "E_RUNTIME_CHANGED" { t.Fatalf("superseded launch while policy busy: %v", err) } }