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.
297 lines
9.6 KiB
Go
297 lines
9.6 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/driver"
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/lifecycle"
|
|
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
|
|
"github.com/Nwflower/reims-go/pkg/pluginproto"
|
|
)
|
|
|
|
const testSecret = `p@ss<&>w0rd"é`
|
|
|
|
type secretTestEnv struct {
|
|
app *App
|
|
h *fakedriver.Harness
|
|
ownerPlugin string
|
|
ownerDriver driver.Driver
|
|
otherPlugin string
|
|
otherDriver driver.Driver
|
|
vmDir string
|
|
source secretSource
|
|
sourceCalls int
|
|
}
|
|
|
|
func newSecretTestEnv(t *testing.T) *secretTestEnv {
|
|
t.Helper()
|
|
h := fakedriver.NewHarness(t)
|
|
e := &secretTestEnv{h: h, ownerPlugin: "test.fake.hosted", otherPlugin: "test.fake.process"}
|
|
e.ownerDriver = h.Add("hosted", e.ownerPlugin, "test.driver.hosted")
|
|
e.otherDriver = h.Add("hosted", e.otherPlugin, "test.driver.other")
|
|
ctx := context.Background()
|
|
for _, d := range []driver.Driver{e.ownerDriver, e.otherDriver} {
|
|
if err := d.Create(ctx, driver.CreateRequest{DriverID: d.ID(), Name: "dev"}, io.Discard, io.Discard); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
svc := lifecycle.New(h.Registry, h.Router, nil)
|
|
e.app = &App{
|
|
cfg: &config.Config{DataRoot: h.DataRoot},
|
|
transitions: map[string]string{},
|
|
pendingChanges: map[string][]PendingChange{},
|
|
pollWake: make(chan struct{}, 1),
|
|
diskPaths: map[string]cachedDiskPath{},
|
|
procSamples: map[string]host.ProcessSample{},
|
|
driverRouter: h.Router,
|
|
vmStateTable: h.States,
|
|
lifecycleSvc: svc,
|
|
}
|
|
_, vm, err := h.Router.ResolveRef(ctx, driver.NewVMRef(e.ownerDriver.ID(), "dev"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
e.vmDir = vm.Directory
|
|
e.source = func(pluginID, vmKey, setting string) (string, error) {
|
|
e.sourceCalls++
|
|
return testSecret, nil
|
|
}
|
|
return e
|
|
}
|
|
|
|
func (e *secretTestEnv) materialize(t *testing.T, pluginID string, req map[string]any) (any, error) {
|
|
t.Helper()
|
|
raw, _ := json.Marshal(req)
|
|
return e.app.materializeSecret(nil, e.h.Broker, e.source, pluginID, raw)
|
|
}
|
|
|
|
func (e *secretTestEnv) request(dest, format string) map[string]any {
|
|
return map[string]any{
|
|
"setting": "admin_password",
|
|
"ref": map[string]any{"driver_id": e.ownerDriver.ID(), "name": "dev"},
|
|
"template": "<Password>{{secret}}</Password>",
|
|
"dest": dest,
|
|
"format": format,
|
|
}
|
|
}
|
|
|
|
func (e *secretTestEnv) read(t *testing.T, res any) string {
|
|
t.Helper()
|
|
path := res.(pluginproto.SecretMaterializeResult).Path
|
|
raw, err := os.ReadFile(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return string(raw)
|
|
}
|
|
|
|
func TestMaterializeSecretFormats(t *testing.T) {
|
|
e := newSecretTestEnv(t)
|
|
res, err := e.materialize(t, e.ownerPlugin, e.request("unattend/raw.xml", ""))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := e.read(t, res); got != "<Password>"+testSecret+"</Password>" {
|
|
t.Fatalf("raw = %q", got)
|
|
}
|
|
path := res.(pluginproto.SecretMaterializeResult).Path
|
|
if !pathInside(e.vmDir, path) {
|
|
t.Fatalf("%s is outside the VM folder %s", path, e.vmDir)
|
|
}
|
|
|
|
res, err = e.materialize(t, e.ownerPlugin, e.request("unattend/escaped.xml", "xml"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := e.read(t, res); !strings.Contains(got, "p@ss<&>w0rd"é") {
|
|
t.Fatalf("xml = %q", got)
|
|
}
|
|
|
|
res, err = e.materialize(t, e.ownerPlugin, e.request("unattend/utf16.xml", "base64-utf16le"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got := e.read(t, res)
|
|
enc := strings.TrimSuffix(strings.TrimPrefix(got, "<Password>"), "</Password>")
|
|
raw, err := base64.StdEncoding.DecodeString(enc)
|
|
if err != nil || len(raw)%2 != 0 {
|
|
t.Fatalf("base64-utf16le = %q, %v", enc, err)
|
|
}
|
|
var runes []rune
|
|
for i := 0; i < len(raw); i += 2 {
|
|
runes = append(runes, rune(uint16(raw[i])|uint16(raw[i+1])<<8))
|
|
}
|
|
if string(runes) != testSecret {
|
|
t.Fatalf("decoded %q, want %q", string(runes), testSecret)
|
|
}
|
|
}
|
|
|
|
func TestMaterializeSecretRejectsBadRequests(t *testing.T) {
|
|
e := newSecretTestEnv(t)
|
|
outside := filepath.Join(t.TempDir(), "out.xml")
|
|
cases := map[string]map[string]any{
|
|
"dest above the VM folder": e.request("../escaped.xml", ""),
|
|
"absolute dest elsewhere": e.request(outside, ""),
|
|
"empty dest": e.request("", ""),
|
|
"unknown format": e.request("a.xml", "rot13"),
|
|
}
|
|
noPlaceholder := e.request("a.xml", "")
|
|
noPlaceholder["template"] = "no secret here"
|
|
cases["template without placeholder"] = noPlaceholder
|
|
noSetting := e.request("a.xml", "")
|
|
noSetting["setting"] = ""
|
|
cases["no setting"] = noSetting
|
|
for name, req := range cases {
|
|
if res, err := e.materialize(t, e.ownerPlugin, req); err == nil {
|
|
t.Errorf("%s was accepted: %v", name, res)
|
|
}
|
|
}
|
|
if _, err := os.Stat(outside); !os.IsNotExist(err) {
|
|
t.Fatal("a file was written outside the VM folder")
|
|
}
|
|
|
|
// A symlink at dest must not be followed.
|
|
target := filepath.Join(t.TempDir(), "target.txt")
|
|
if err := os.WriteFile(target, []byte("keep"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
link := filepath.Join(e.vmDir, "link.xml")
|
|
if err := os.Symlink(target, link); err == nil {
|
|
if _, err := e.materialize(t, e.ownerPlugin, e.request("link.xml", "")); err == nil {
|
|
t.Error("a symlink dest was accepted")
|
|
}
|
|
if raw, _ := os.ReadFile(target); string(raw) != "keep" {
|
|
t.Errorf("the symlink target was overwritten: %q", raw)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestMaterializeSecretRefusesAnotherPluginsDriver(t *testing.T) {
|
|
e := newSecretTestEnv(t)
|
|
// The other plugin owns driver test.driver.other, not the owner's driver.
|
|
if res, err := e.materialize(t, e.otherPlugin, e.request("a.xml", "")); err == nil {
|
|
t.Fatalf("a plugin materialized a secret into another driver's VM: %v", res)
|
|
}
|
|
if e.sourceCalls != 0 {
|
|
t.Fatal("the secret was decrypted for a request that was not allowed")
|
|
}
|
|
}
|
|
|
|
func TestMaterializeSecretNeverAuditsTheValue(t *testing.T) {
|
|
e := newSecretTestEnv(t)
|
|
if _, err := e.materialize(t, e.ownerPlugin, e.request("a.xml", "")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
raw, err := os.ReadFile(filepath.Join(e.h.DataRoot, "plugins", "logs", e.ownerPlugin+".log"))
|
|
if err != nil {
|
|
t.Fatalf("no audit log: %v", err)
|
|
}
|
|
log := string(raw)
|
|
if !strings.Contains(log, "SECRET_MATERIALIZE") || !strings.Contains(log, "setting=admin_password") || !strings.Contains(log, "bytes=") {
|
|
t.Fatalf("audit log lacks the expected entry: %q", log)
|
|
}
|
|
if strings.Contains(log, testSecret) || strings.Contains(log, "w0rd") {
|
|
t.Fatalf("the audit log holds the secret: %q", log)
|
|
}
|
|
}
|
|
|
|
func TestDiscardSecretAndVMDeletionRemoveTheFiles(t *testing.T) {
|
|
e := newSecretTestEnv(t)
|
|
first, err := e.materialize(t, e.ownerPlugin, e.request("one.xml", ""))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
second, err := e.materialize(t, e.ownerPlugin, e.request("two.xml", ""))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
p1, p2 := first.(pluginproto.SecretMaterializeResult).Path, second.(pluginproto.SecretMaterializeResult).Path
|
|
|
|
discard := func(plugin string, req map[string]any) int {
|
|
raw, _ := json.Marshal(req)
|
|
res, err := e.app.discardSecret(nil, e.h.Broker, plugin, raw)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return res.(pluginproto.SecretDiscardResult).Removed
|
|
}
|
|
ref := map[string]any{"driver_id": e.ownerDriver.ID(), "name": "dev"}
|
|
if n := discard(e.ownerPlugin, map[string]any{"ref": ref, "path": p1}); n != 1 {
|
|
t.Fatalf("discard one removed %d", n)
|
|
}
|
|
if _, err := os.Stat(p1); !os.IsNotExist(err) {
|
|
t.Fatal("the discarded file is still there")
|
|
}
|
|
if _, err := os.Stat(p2); err != nil {
|
|
t.Fatal("discarding one file removed the other")
|
|
}
|
|
if n := discard(e.ownerPlugin, map[string]any{"ref": ref, "path": p1}); n != 0 {
|
|
t.Fatalf("discarding a gone file removed %d", n)
|
|
}
|
|
|
|
// A fresh App (a restart) still knows the file and deletes it with its VM.
|
|
restarted := &App{cfg: &config.Config{DataRoot: e.h.DataRoot}}
|
|
restarted.discardMaterializedSecretsForVM(driver.NewVMRef(e.ownerDriver.ID(), "dev").Key())
|
|
if _, err := os.Stat(p2); !os.IsNotExist(err) {
|
|
t.Fatal("deleting the VM left its secret file behind")
|
|
}
|
|
if _, err := os.Stat(restarted.materializedSecretsPath()); !os.IsNotExist(err) {
|
|
t.Fatal("the tracking file outlived its last entry")
|
|
}
|
|
}
|
|
|
|
func TestMaterializeSecretKeepsExistingFiles(t *testing.T) {
|
|
e := newSecretTestEnv(t)
|
|
own := filepath.Join(e.vmDir, "disk.img")
|
|
if err := os.WriteFile(own, []byte("keep"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := e.materialize(t, e.ownerPlugin, e.request("disk.img", "")); err == nil {
|
|
t.Fatal("a file the host did not create was overwritten")
|
|
}
|
|
e.app.discardMaterializedSecretsForVM(driver.NewVMRef(e.ownerDriver.ID(), "dev").Key())
|
|
if raw, err := os.ReadFile(own); err != nil || string(raw) != "keep" {
|
|
t.Fatalf("existing file = %q, %v", raw, err)
|
|
}
|
|
for range 2 { // the host may refresh its own file
|
|
if _, err := e.materialize(t, e.ownerPlugin, e.request("a.xml", "")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestDiscardSecretRetriesAFileItCouldNotDelete(t *testing.T) {
|
|
e := newSecretTestEnv(t)
|
|
res, err := e.materialize(t, e.ownerPlugin, e.request("a.xml", ""))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
path := res.(pluginproto.SecretMaterializeResult).Path
|
|
// A non-empty folder in the file's place cannot be removed.
|
|
if err := os.Remove(path); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(path, "x"), 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
all := func(materializedSecret) bool { return true }
|
|
if n, err := e.app.removeMaterialized(all); err == nil || n != 0 {
|
|
t.Fatalf("removed %d, %v; want an error", n, err)
|
|
}
|
|
if err := os.Remove(filepath.Join(path, "x")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n, err := e.app.removeMaterialized(all); err != nil || n != 1 {
|
|
t.Fatalf("the retry removed %d, %v", n, err)
|
|
}
|
|
}
|