333 lines
11 KiB
Go
333 lines
11 KiB
Go
package builtin
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/config"
|
|
"github.com/Nwflower/reims-go/internal/guesttools"
|
|
"github.com/Nwflower/reims-go/internal/host"
|
|
"github.com/Nwflower/reims-go/internal/plugin"
|
|
)
|
|
|
|
func TestBuiltinClipboardAndInputLifecycleZeroResidue(t *testing.T) {
|
|
reg := plugin.NewRegistry(nil)
|
|
gtSrv := guesttools.NewTransportServer(nil)
|
|
if _, err := gtSrv.Start(-1); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = gtSrv.Close(context.Background()) }()
|
|
|
|
cb := HostCallbacks{
|
|
GetConfig: func() config.Config { return config.Config{DataRoot: t.TempDir()} },
|
|
EnsureGuestTools: func() (*guesttools.Server, int, error) {
|
|
return gtSrv, gtSrv.Port(), nil
|
|
},
|
|
}
|
|
if err := RegisterAll(reg, cb, nil); err != nil {
|
|
t.Fatalf("RegisterAll: %v", err)
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
|
|
// Clipboard extension should be active and have mounted /v1/clipboard + watcher.
|
|
if !reg.IsActive(IDGuestTools) || !reg.IsActive(IDClipboard) {
|
|
t.Fatalf("expected guest-tools and clipboard active")
|
|
}
|
|
if !gtSrv.HasRoute("/v1/clipboard") || !gtSrv.IsClipboardActive() {
|
|
t.Fatal("expected clipboard route mounted while builtin.bridge.clipboard is active")
|
|
}
|
|
|
|
// Disable clipboard live -> route removed, watcher stopped, zero residue!
|
|
if err := reg.SetDesired(context.Background(), IDClipboard, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if gtSrv.HasRoute("/v1/clipboard") || gtSrv.IsClipboardActive() {
|
|
t.Fatal("expected zero clipboard route residue after disabling builtin.bridge.clipboard")
|
|
}
|
|
deadline := time.Now().Add(2 * time.Second)
|
|
for gtSrv.IsClipboardWatcherRunning() && time.Now().Before(deadline) {
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
if gtSrv.IsClipboardWatcherRunning() {
|
|
t.Fatal("expected clipboard watcher stopped after disable")
|
|
}
|
|
|
|
// Re-enable clipboard -> active again.
|
|
if err := reg.SetDesired(context.Background(), IDClipboard, true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !gtSrv.HasRoute("/v1/clipboard") {
|
|
t.Fatal("expected clipboard route restored on re-enable")
|
|
}
|
|
|
|
// Disabling transport service cascades and disables clipboard cleanly.
|
|
if err := reg.SetDesired(context.Background(), IDGuestTools, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if reg.IsActive(IDClipboard) || gtSrv.HasRoute("/v1/clipboard") {
|
|
t.Fatal("disabling guest-tools transport must cascade-unload clipboard")
|
|
}
|
|
|
|
// Input service disables cleanly with zero hook residue.
|
|
if raw, ok := reg.LookupService(ServiceHostInput); !ok || raw == nil {
|
|
t.Fatal("expected host.input service provided")
|
|
}
|
|
if err := reg.SetDesired(context.Background(), IDInput, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, ok := reg.LookupService(ServiceHostInput); ok {
|
|
t.Fatal("expected host.input service removed after disable")
|
|
}
|
|
}
|
|
|
|
func TestInputServiceTypeCheck(t *testing.T) {
|
|
_ = host.NewInputService(nil)
|
|
}
|
|
|
|
func TestGuestToolsInputBridgeEnvGating(t *testing.T) {
|
|
reg := plugin.NewRegistry(nil)
|
|
gtSrv := guesttools.NewTransportServer(nil)
|
|
if _, err := gtSrv.Start(-1); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = gtSrv.Close(context.Background()) }()
|
|
|
|
cb := HostCallbacks{
|
|
GetConfig: func() config.Config { return config.Config{DataRoot: t.TempDir()} },
|
|
EnsureGuestTools: func() (*guesttools.Server, int, error) {
|
|
return gtSrv, gtSrv.Port(), nil
|
|
},
|
|
LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) {
|
|
cfg, err := guesttools.LoadOrCreateVMConfig(dir, name, "", port)
|
|
if err == nil {
|
|
srv.RegisterVM(cfg)
|
|
}
|
|
return cfg, err
|
|
},
|
|
}
|
|
if err := RegisterAll(reg, cb, nil); err != nil {
|
|
t.Fatalf("RegisterAll: %v", err)
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
|
|
vmDir := t.TempDir()
|
|
dispatch := func(caps []string) map[string]string {
|
|
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
|
VMName: "mac",
|
|
VMDir: vmDir,
|
|
DriverID: IDDriverReimsMacOS,
|
|
RuntimeCaps: caps,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("DispatchBeforeStart: %v", err)
|
|
}
|
|
for _, in := range intents {
|
|
if in.PluginID == IDGuestTools {
|
|
return in.Env
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Runtime without safe win32-unicode-input capability (e.g. runtime-3731afd-p3)
|
|
// must NOT receive REIMS_GO_INPUT_URL / REIMS_GO_INPUT_TOKEN.
|
|
if env := dispatch(nil); env["REIMS_GO_INPUT_URL"] != "" || env["REIMS_GO_INPUT_TOKEN"] != "" {
|
|
t.Fatalf("without capability: unexpected input bridge env %v", env)
|
|
}
|
|
|
|
if env := dispatch([]string{"win32-unicode-input"}); env["REIMS_GO_DROP_URL"] != "" || env["REIMS_GO_DROP_TOKEN"] != "" {
|
|
t.Fatal("drop environment injected without window-file-drop")
|
|
}
|
|
checkDrop := func() {
|
|
t.Helper()
|
|
env := dispatch([]string{"window-file-drop"})
|
|
want := gtSrv.HostDropToken("", "mac")
|
|
if want == "" || env["REIMS_GO_DROP_TOKEN"] != want || env["REIMS_GO_DROP_URL"] != fmt.Sprintf("http://127.0.0.1:%d/v1/host-drop", gtSrv.Port()) {
|
|
t.Fatal("incorrect host drop environment")
|
|
}
|
|
}
|
|
checkDrop()
|
|
|
|
// Fixed runtime + active builtin.input plugin -> env vars injected.
|
|
env := dispatch([]string{"win32-unicode-input"})
|
|
if env["REIMS_GO_INPUT_URL"] == "" || env["REIMS_GO_INPUT_TOKEN"] == "" {
|
|
t.Fatalf("with capability and active input plugin: missing input bridge env %v", env)
|
|
}
|
|
|
|
// Disabling builtin.input stops injecting REIMS_GO_INPUT_URL / TOKEN even on fixed runtime.
|
|
if err := reg.SetDesired(context.Background(), IDInput, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
checkDrop()
|
|
if env := dispatch([]string{"win32-unicode-input"}); env["REIMS_GO_INPUT_URL"] != "" || env["REIMS_GO_INPUT_TOKEN"] != "" {
|
|
t.Fatalf("with input plugin disabled: unexpected input bridge env %v", env)
|
|
}
|
|
}
|
|
|
|
// The core plugin is the host itself: user-facing lists leave it out, while
|
|
// lookups by ID and the full registry listing still see it.
|
|
func TestCorePluginHiddenFromVisibleList(t *testing.T) {
|
|
reg := plugin.NewRegistry(nil)
|
|
if err := RegisterAll(reg, HostCallbacks{}, nil); err != nil {
|
|
t.Fatalf("RegisterAll: %v", err)
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
has := func(list []plugin.PluginInfo, id string) bool {
|
|
for _, p := range list {
|
|
if p.ID == id {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
visible := reg.ListVisible()
|
|
if has(visible, IDCore) {
|
|
t.Fatal("ListVisible must not include the core plugin")
|
|
}
|
|
if !has(visible, IDGuestTools) || len(visible) != len(reg.List())-1 {
|
|
t.Fatalf("ListVisible = %d plugins, List = %d", len(visible), len(reg.List()))
|
|
}
|
|
if info, ok := reg.Info(IDCore); !ok || !info.System {
|
|
t.Fatalf("Info(core) = %+v, %v", info, ok)
|
|
}
|
|
}
|
|
|
|
func TestNpcapBridgePluginLifecycleZeroResidue(t *testing.T) {
|
|
reg := plugin.NewRegistry(nil)
|
|
var restored, stopped int
|
|
root := t.TempDir()
|
|
cb := HostCallbacks{
|
|
GetConfig: func() config.Config { return config.Config{DataRoot: root} },
|
|
RestorePacketBridges: func(context.Context) func() {
|
|
restored++
|
|
return nil
|
|
},
|
|
StopPacketBridges: func() {
|
|
stopped++
|
|
},
|
|
}
|
|
if err := RegisterAll(reg, cb, nil); err != nil {
|
|
t.Fatalf("RegisterAll: %v", err)
|
|
}
|
|
reg.Reconcile(context.Background())
|
|
|
|
if !reg.IsActive(IDNpcapBridge) {
|
|
t.Fatal("expected builtin.network.npcap active by default")
|
|
}
|
|
if restored != 1 {
|
|
t.Fatalf("RestorePacketBridges calls = %d, want 1", restored)
|
|
}
|
|
|
|
vmDir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(vmDir, "vm.toml"), []byte("[network]\nenabled = false\nmac = \"02:00:00:00:00:01\"\n"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(vmDir, ".reims-go-network.json"), []byte(`{"version":1,"mode":"bridge","uplink_guid":"{1111}"}`), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
|
VMName: "mac",
|
|
VMDir: vmDir,
|
|
DriverID: IDDriverReimsMacOS,
|
|
ExtraArgs: "-cpu host",
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("DispatchBeforeStart: %v", err)
|
|
}
|
|
ledger := &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}
|
|
res := plugin.ReconcileStartIntents("-cpu host", ledger, reg.ActivePluginIDs(), intents)
|
|
if !strings.Contains(res.ExtraArgs, "addr.type=unix") || !strings.Contains(res.ExtraArgs, "reimsbridge0") || !strings.Contains(res.ExtraArgs, "-cpu host") {
|
|
t.Fatalf("active npcap-bridge ExtraArgs = %q", res.ExtraArgs)
|
|
}
|
|
// Primary bridge NIC (addr=0x3) must always precede guest-tools-network so QEMU never assigns slot 0x3 to reimstools-nic.
|
|
withMgmt := plugin.ReconcileStartIntents("-cpu host", &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}, reg.ActivePluginIDs(), append(intents, plugin.StartIntent{
|
|
PluginID: IDGuestTools,
|
|
Args: []plugin.ArgFragment{{
|
|
PluginID: IDGuestTools,
|
|
Key: "guest-tools-network",
|
|
Tokens: []string{"-device", "virtio-net-pci,id=reimstools-nic,netdev=reimstools-net"},
|
|
Builtin: true,
|
|
Priority: 79,
|
|
}},
|
|
}))
|
|
bridgePos := strings.Index(withMgmt.ExtraArgs, "addr=0x3")
|
|
mgmtPos := strings.Index(withMgmt.ExtraArgs, "reimstools-nic")
|
|
if bridgePos < 0 || mgmtPos < 0 || bridgePos > mgmtPos {
|
|
t.Fatalf("primary bridge addr=0x3 (%d) must precede reimstools-nic (%d) in %q", bridgePos, mgmtPos, withMgmt.ExtraArgs)
|
|
}
|
|
if len(ledger.Owners[IDNpcapBridge]) != 1 {
|
|
t.Fatalf("expected ledger owner for %s, got %+v", IDNpcapBridge, ledger.Owners)
|
|
}
|
|
|
|
// Disabling builtin.network.npcap must stop bridges and leave ZERO residue in ExtraArgs & ledger.
|
|
if err := reg.SetDesired(context.Background(), IDNpcapBridge, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if stopped != 1 {
|
|
t.Fatalf("StopPacketBridges calls = %d, want 1", stopped)
|
|
}
|
|
if _, ok := reg.LookupService(ServiceNpcapBridge); ok {
|
|
t.Fatal("expected network.npcap service removed after disable")
|
|
}
|
|
intentsAfter, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{
|
|
VMName: "mac",
|
|
VMDir: vmDir,
|
|
DriverID: IDDriverReimsMacOS,
|
|
ExtraArgs: res.ExtraArgs,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("DispatchBeforeStart after disable: %v", err)
|
|
}
|
|
resAfter := plugin.ReconcileStartIntents(res.ExtraArgs, ledger, reg.ActivePluginIDs(), intentsAfter)
|
|
if resAfter.ExtraArgs != "-cpu host" {
|
|
t.Fatalf("disabled npcap-bridge left residue in ExtraArgs: %q", resAfter.ExtraArgs)
|
|
}
|
|
if _, ok := ledger.Owners[IDNpcapBridge]; ok {
|
|
t.Fatalf("disabled npcap-bridge left residue in ledger: %+v", ledger.Owners)
|
|
}
|
|
}
|
|
|
|
func TestNpcapBridgeRestorationBelongsToPluginScope(t *testing.T) {
|
|
reg := plugin.NewRegistry(nil)
|
|
var restoreCtx context.Context
|
|
restoreFinished := make(chan struct{})
|
|
stopped := false
|
|
cb := HostCallbacks{
|
|
RestorePacketBridges: func(parent context.Context) func() {
|
|
var cancel context.CancelFunc
|
|
restoreCtx, cancel = context.WithCancel(parent)
|
|
go func() { <-restoreCtx.Done(); close(restoreFinished) }()
|
|
return func() { cancel(); <-restoreFinished }
|
|
},
|
|
StopPacketBridges: func() {
|
|
select {
|
|
case <-restoreFinished:
|
|
stopped = true
|
|
default:
|
|
t.Error("恢复任务退出之前已经释放桥接通道")
|
|
}
|
|
},
|
|
}
|
|
if err := RegisterAll(reg, cb, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
requestCtx, cancelRequest := context.WithCancel(context.Background())
|
|
reg.Reconcile(requestCtx)
|
|
cancelRequest()
|
|
if restoreCtx == nil || restoreCtx.Err() != nil {
|
|
t.Fatal("激活请求结束取消了常驻恢复任务")
|
|
}
|
|
if err := reg.SetDesired(context.Background(), IDNpcapBridge, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !stopped || restoreCtx.Err() == nil {
|
|
t.Fatal("插件停用没有先取消并等待恢复任务")
|
|
}
|
|
}
|