Give the Sidecar Host API one authoritative catalog in pkg/pluginproto: every host/* method's status, required permissions, handshake feature and request and result shapes. The host, pkg/pluginsdk and plugins share those types, so a field can no longer exist on one side only, and permissions come from the catalog instead of from each handler. Tests gate that every served method is catalogued, every stable catalogued method is served, and every catalogued permission is one the host recognizes. Open the interface up instead of adding consent gates. Typing a secret setting is no longer reserved for reims.agent: any plugin that holds qmp:write and that the user authorized for the VM can have the host type the plugin's own setting, which the plugin never reads back. Restoring a snapshot works on any authorized VM, a plugin names its own clones, a held key may carry modifiers, and a screenshot width outside the supported range is brought into range rather than refused. Deleting a VM stays limited to the temporary VMs a plugin created. Record the keys and pointer buttons each plugin holds per VM and lift them when the plugin's process exits, its scope is disposed, the VM stops or it stops calling, so a guest never stays stuck with a modifier down. Requests from plugins that declare pluginApi 1.3 or newer are decoded strictly and answer an undefined field with JSON-RPC -32602, while older plugins keep tolerant decoding. Add typed VM and console methods to pkg/pluginsdk so a plugin no longer needs its own JSON-RPC client. A method the contract does not catalog, or one the host did not advertise in the handshake, is refused before it is sent, and the host's JSON-RPC error code reaches the caller.
256 lines
8.9 KiB
Go
256 lines
8.9 KiB
Go
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.hostHandlers(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.heldState("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.heldState("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)
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
}
|