package app import ( "context" "encoding/json" "errors" "strings" "testing" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/pkg/pluginproto" ) const hostContractPlugin = "test.host.contract" // newHostContractEnv builds a plugin manager with one plugin whose manifest a // test can vary, plus an App that serves the host API through it. func newHostContractEnv(t *testing.T, manifest plugin.Manifest) (*App, *plugin.Manager) { t.Helper() cfg := config.Default() cfg.DataRoot = t.TempDir() mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: cfg.DataRoot, HostVersion: "0.0.0"}) if err != nil { t.Fatal(err) } t.Cleanup(mgr.Close) manifest.ID = hostContractPlugin manifest.Version = "1.0.0" manifest.Name = plugin.LocalizedText{EnUS: hostContractPlugin} if err := mgr.Registry().Register(plugin.PluginDef{ Manifest: manifest, Source: plugin.SourceBuiltin, Desired: true, Activate: func(context.Context, *plugin.Scope) error { return nil }, }); err != nil { t.Fatal(err) } mgr.Registry().Reconcile(context.Background()) return &App{cfg: cfg, pluginMgr: mgr}, mgr } // TestEveryStableHostMethodIsServed is the gate that keeps the host and the // contract catalog from drifting: every stable method must be implemented // somewhere, and nothing may be served that the catalog does not list. func TestEveryStableHostMethodIsServed(t *testing.T) { app, mgr := newHostContractEnv(t, plugin.Manifest{}) served := map[string]bool{} for _, method := range plugin.ReverseHostAPIMethods() { served[method] = true } for method := range app.hostAPISvc().Handlers(mgr, hostContractPlugin) { if _, ok := pluginproto.Lookup(method); !ok { t.Errorf("%s is served but not in the contract catalog", method) } served[method] = true } for _, method := range pluginproto.Methods() { spec, _ := pluginproto.Lookup(method) if spec.Status != pluginproto.StatusStable { continue } if !served[method] { t.Errorf("%s is stable in the catalog but nothing serves it", method) } } } // TestCataloguedPermissionsAreReal checks that every permission a method // declares is one the permission classifier knows, so a typo cannot silently // turn a method into an always-denied or always-allowed one. func TestCataloguedPermissionsAreReal(t *testing.T) { for _, method := range pluginproto.Methods() { spec, _ := pluginproto.Lookup(method) for _, perm := range spec.Permissions { if perm == pluginproto.OriginPermission { continue } if plugin.ClassifyPermission(perm) == plugin.PermForbidden { t.Errorf("%s requires %q, which the host does not recognize", method, perm) } } } } // TestReadingSnapshotsNeedsOnlyReadPermission keeps the catalog from asking for // more than the operation needs. func TestReadingSnapshotsNeedsOnlyReadPermission(t *testing.T) { spec, ok := pluginproto.Lookup("host/vm.snapshot.list") if !ok || len(spec.Permissions) != 1 || spec.Permissions[0] != "vm:read" { t.Fatalf("host/vm.snapshot.list requires %v, want vm:read only", spec.Permissions) } } func TestStrictParamsFollowTheDeclaredPluginAPI(t *testing.T) { cases := map[string]bool{ "": false, "^1.1.0": false, "^1.2.0": false, "^1.3.0": true, ">=1.3.0": true, } for engines, want := range cases { _, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: engines}}) raw := json.RawMessage(`{"vm":"a","max_width":640,"nope":1}`) _, err := decodeHostParams[pluginproto.ScreenshotParams](mgr, hostContractPlugin, "host/console.screenshot", raw) var rpcErr *plugin.RPCError strict := errors.As(err, &rpcErr) && rpcErr.Code == plugin.RPCInvalidParams if strict != want { t.Errorf("pluginApi %q: strict = %v (%v), want %v", engines, strict, err, want) } } } func TestUnknownFieldIsRejectedWithInvalidParams(t *testing.T) { _, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: "^1.3.0"}}) _, err := decodeHostParams[pluginproto.KeyParams](mgr, hostContractPlugin, "host/console.key", json.RawMessage(`{"vm":"a","key":"cmd","down":true,"hold_ms":5}`)) var rpcErr *plugin.RPCError if !errors.As(err, &rpcErr) || rpcErr.Code != plugin.RPCInvalidParams { t.Fatalf("err = %v, want JSON-RPC %d", err, plugin.RPCInvalidParams) } if !strings.Contains(rpcErr.Message, "hold_ms") { t.Fatalf("message %q does not name the offending field", rpcErr.Message) } } func TestShutdownForceReachesTheHost(t *testing.T) { _, mgr := newHostContractEnv(t, plugin.Manifest{Engines: plugin.Engines{PluginAPI: "^1.3.0"}}) req, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, hostContractPlugin, "host/vm.shutdown", json.RawMessage(`{"vm":"a","force":true}`)) if err != nil { t.Fatalf("a known field was rejected: %v", err) } if !req.Force || req.VM != "a" { t.Fatalf("request = %+v, want force on vm a", req) } if _, err := decodeHostParams[pluginproto.VMShutdownParams](mgr, hostContractPlugin, "host/vm.shutdown", json.RawMessage(`{"vm":"a","hard":true}`)); err == nil { t.Fatal("an undefined field was accepted") } } // TestSecretTypingIsOpenToEveryAuthorizedPlugin checks that typing a secret is // no longer reserved for one plugin id: any plugin reaches the same path and // is stopped only by the VM reference and the user's per-VM access consent. func TestSecretTypingIsOpenToEveryAuthorizedPlugin(t *testing.T) { app, mgr := newHostContractEnv(t, plugin.Manifest{}) _, err := app.handleComputerUseTypeSecret(context.Background(), json.RawMessage(`{"vm":"","setting":"login_password"}`), mgr, hostContractPlugin) if err == nil { t.Fatal("an empty VM reference was accepted") } if strings.Contains(err.Error(), "reserved for") { t.Fatalf("err = %v, want no plugin-id refusal", err) } } // TestCloneOwnershipDoesNotDependOnTheName checks that a plugin may name its // temporary clones freely: the marker the host writes is what makes a VM a // clone. func TestCloneOwnershipDoesNotDependOnTheName(t *testing.T) { dir := t.TempDir() vm := driver.VMInfo{Name: "my-own-name", DriverID: "acme.driver", Directory: dir} key := vm.Ref().Key() if err := writeComputerUseOwnership(dir, hostContractPlugin, key, ""); err != nil { t.Fatal(err) } marker, ok := readComputerUseOwnership(vm) if !ok || marker.PluginID != hostContractPlugin || marker.VMKey != key { t.Fatalf("marker = %+v, ok = %v", marker, ok) } } func TestScreenshotWidthIsBroughtIntoRange(t *testing.T) { cases := map[int]int{ 0: computerUsePreviewWidth, -5: computerUseMinImageWidth, 1: computerUseMinImageWidth, 640: 640, 9999: computerUseMaxImageWidth, } for requested, want := range cases { if got := computerUseScreenshotWidth(requested); got != want { t.Errorf("max_width %d = %d, want %d", requested, got, want) } } } func TestHeldLedgerTracksAndForgets(t *testing.T) { app := &App{} const vmKey = "driver:vm" app.noteHeldKey("p", vmKey, "meta_l", true) app.noteHeldButton("p", vmKey, "left", true) app.noteHeldKey("p", vmKey, "a", true) keys, buttons, _ := app.heldSnapshot("p", vmKey) if len(keys) != 2 || len(buttons) != 1 { t.Fatalf("held = %v %v", keys, buttons) } // Releasing one key keeps the rest. app.dropHeld("p", vmKey, []string{"a"}, nil) if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 1 || keys[0] != "meta_l" { t.Fatalf("keys after drop = %v", keys) } // Lifting everything leaves no record behind. app.dropHeld("p", vmKey, []string{"meta_l"}, []string{"left"}) if vms := app.heldVMs("p"); len(vms) != 0 { t.Fatalf("ledger still holds %v", vms) } // A VM that is not running is forgotten without touching a console. app.noteHeldKey("p", vmKey, "shift", true) app.forgetHeld("p", vmKey) if vms := app.heldVMs("p"); len(vms) != 0 { t.Fatalf("ledger still holds %v after forget", vms) } } // TestHeldLedgerKeepsAPressMadeDuringARelease checks that a release which // finished after the plugin pressed something new does not delete that press // from the record: the fallback would then no longer know to lift it. func TestHeldLedgerKeepsAPressMadeDuringARelease(t *testing.T) { app := &App{} const vmKey = "driver:vm" app.noteHeldKey("p", vmKey, "meta_l", true) keys, buttons, generation := app.heldSnapshot("p", vmKey) // The plugin presses another key while the release is in flight. app.noteHeldKey("p", vmKey, "shift", true) if app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) { t.Fatal("a stale release deleted a press it did not lift") } if keys, _, _ := app.heldSnapshot("p", vmKey); len(keys) != 2 { t.Fatalf("keys = %v, want both presses kept", keys) } // A release whose snapshot is still current does clear the record. keys, buttons, generation = app.heldSnapshot("p", vmKey) if !app.dropHeldIfGeneration("p", vmKey, keys, buttons, generation) { t.Fatal("a current release was refused") } if vms := app.heldVMs("p"); len(vms) != 0 { t.Fatalf("ledger still holds %v", vms) } } // TestHeldLedgerRetriesAfterTheIdleTimeout checks that a record whose fallback // release could not run keeps a timer: a plugin that already exited never // makes the call that would otherwise retry it. func TestHeldLedgerRetriesAfterTheIdleTimeout(t *testing.T) { previousIdle, previousRetry := heldInputIdleTimeout, heldReleaseRetryTimeout heldInputIdleTimeout = time.Hour heldReleaseRetryTimeout = 20 * time.Millisecond t.Cleanup(func() { heldInputIdleTimeout, heldReleaseRetryTimeout = previousIdle, previousRetry }) app := &App{} app.noteHeldKey("p", "driver:vm", "meta_l", true) app.rearmHeld("p", "driver:vm") deadline := time.Now().Add(2 * time.Second) for len(app.heldVMs("p")) > 0 && time.Now().Before(deadline) { time.Sleep(5 * time.Millisecond) } // The VM is not running here, so the retry drops the record instead of // leaving a key pressed forever. if vms := app.heldVMs("p"); len(vms) != 0 { t.Fatalf("the retry left %v behind", vms) } } // TestHeldLedgerReleasesAfterTheIdleTimeout checks that a plugin which stops // calling mid-hold does not leave the guest stuck: the record carries its own // timer, and a VM that is not running has nothing left to lift. func TestHeldLedgerReleasesAfterTheIdleTimeout(t *testing.T) { previous := heldInputIdleTimeout heldInputIdleTimeout = 20 * time.Millisecond t.Cleanup(func() { heldInputIdleTimeout = previous }) app := &App{} app.noteHeldKey("p", "driver:vm", "meta_l", true) if vms := app.heldVMs("p"); len(vms) != 1 { t.Fatalf("ledger = %v, want one record", vms) } deadline := time.Now().Add(2 * time.Second) for len(app.heldVMs("p")) > 0 && time.Now().Before(deadline) { time.Sleep(5 * time.Millisecond) } if vms := app.heldVMs("p"); len(vms) != 0 { t.Fatalf("the idle timer left %v behind", vms) } } func TestHeldLedgerIsPerPlugin(t *testing.T) { app := &App{} app.noteHeldKey("p1", "driver:vm", "meta_l", true) if vms := app.heldVMs("p2"); len(vms) != 0 { t.Fatalf("another plugin sees %v", vms) } if vms := app.heldVMs("p1"); len(vms) != 1 { t.Fatalf("own record = %v", vms) } }