Files
Reims-Go/pkg/drivertest/drivertest.go
NwflowerandClaude Opus 5.5 44e2174fff fix: harden guest driver host APIs
- run elevated actions as fixed System32 tools instead of a hidden subcommand
- require a SHA-256 for plugin downloads
- keep records of secret files that could not be deleted, and never overwrite
  files the host did not create
- stop two concurrent requests from starting the same VM
- drop invalid endpoints instead of failing the whole VM list, and reject ssh
  users and IPv6 zones that could inject command-line text
- accept driver screenshots only at the requested path
- do not treat an unreadable guest phase as normal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:07:46 -07:00

619 lines
18 KiB
Go

// Package drivertest is the contract test suite for Reims-Go guest drivers.
//
// A driver, built into the host or served by a Sidecar plugin, passes the same
// checks everywhere: lifecycle idempotency, error classification, capability
// bits that match what the driver implements, restore points, clones and disk
// operations, driver-reported readiness and phase, and VMs of the same name in
// two drivers staying independent. The package imports nothing from the host,
// so a plugin repository can run it against its own driver.
package drivertest
import (
"context"
"fmt"
"strings"
"testing"
"time"
)
// VMRef identifies a VM by owning driver and name.
type VMRef struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
}
// GuestOSInfo describes a guest operating system.
type GuestOSInfo struct {
Family string `json:"family,omitempty"`
Distro string `json:"distro,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
}
// VMEndpoint is one way to reach a running guest.
type VMEndpoint struct {
Kind string `json:"kind"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
User string `json:"user,omitempty"`
Distro string `json:"distro,omitempty"`
VM string `json:"vm,omitempty"`
Serial string `json:"serial,omitempty"`
Ready bool `json:"ready"`
}
// VMInfo is the cross-driver VM model.
type VMInfo struct {
Name string `json:"name"`
DriverID string `json:"driver_id"`
DriverName string `json:"driver_name,omitempty"`
State string `json:"state"`
PID *int `json:"pid,omitempty"`
CPUs int `json:"cpus,omitempty"`
Memory string `json:"memory,omitempty"`
DiskSummary string `json:"disk_summary,omitempty"`
DiskPath string `json:"disk_path,omitempty"`
Directory string `json:"directory,omitempty"`
Network bool `json:"network,omitempty"`
SSHPort int `json:"ssh_port,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
DriverData map[string]any `json:"driver_data,omitempty"`
GuestOS *GuestOSInfo `json:"guest_os,omitempty"`
Phase string `json:"phase,omitempty"`
Ready *bool `json:"ready,omitempty"`
Endpoints []VMEndpoint `json:"endpoints,omitempty"`
}
// ValidationIssue is a field-level validation error.
type ValidationIssue struct {
Field string `json:"field"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
}
// CreateRequest asks a driver to create a VM.
type CreateRequest struct {
DriverID string `json:"driver_id"`
Name string `json:"name"`
Dir string `json:"dir,omitempty"`
Options map[string]any `json:"options,omitempty"`
}
// DiskSnapshot is one restore point.
type DiskSnapshot struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt int64 `json:"created_at"`
VMStateBytes int64 `json:"vm_state_bytes"`
}
// DiskResizeResult describes a disk expansion.
type DiskResizeResult struct {
Path string `json:"path"`
OldVirtualBytes uint64 `json:"old_virtual_bytes"`
NewVirtualBytes uint64 `json:"new_virtual_bytes"`
GuestExpandCmd string `json:"guest_expand_cmd"`
}
// DiskCompactResult describes space reclaimed from a disk.
type DiskCompactResult struct {
Path string `json:"path"`
BeforeBytes uint64 `json:"before_bytes"`
AfterBytes uint64 `json:"after_bytes"`
ReclaimedBytes uint64 `json:"reclaimed_bytes"`
}
// Capability bits the suite checks.
const (
CapSnapshot = "snapshot"
CapCowClone = "cow_clone"
CapResize = "resize"
CapHosted = "hosted"
)
// Phases a driver may report.
const (
PhaseNormal = "normal"
PhaseInstaller = "installer"
PhaseRecovery = "recovery"
)
// SuiteDriver is the part of a guest driver every driver implements.
type SuiteDriver interface {
ID() string
Capabilities() []string
List(ctx context.Context) ([]VMInfo, error)
Show(ctx context.Context, name string) (VMInfo, error)
ValidateCreate(ctx context.Context, req CreateRequest) []ValidationIssue
Create(ctx context.Context, req CreateRequest) error
Start(ctx context.Context, name string) error
Stop(ctx context.Context, name string, force bool) error
Delete(ctx context.Context, name string, keepFiles bool) error
}
// SnapshotSuiteDriver is implemented by drivers declaring `snapshot`.
type SnapshotSuiteDriver interface {
ListSnapshots(ctx context.Context, name string) ([]DiskSnapshot, error)
RunSnapshot(ctx context.Context, name, operation, snapName string) error
}
// CloneSuiteDriver is implemented by drivers declaring `cow_clone`.
type CloneSuiteDriver interface {
CloneCoW(ctx context.Context, source, clone string) error
}
// DiskSuiteDriver is implemented by drivers declaring `resize`.
type DiskSuiteDriver interface {
ResizeDisk(ctx context.Context, name, size string) (DiskResizeResult, error)
CompactDisk(ctx context.Context, name string) (DiskCompactResult, error)
}
// LogSuiteDriver is implemented by drivers that expose VM logs.
type LogSuiteDriver interface {
ReadLogs(ctx context.Context, name string, serial bool) (string, error)
}
// PhaseSuiteDriver is implemented by drivers that report installer/recovery.
type PhaseSuiteDriver interface {
Phase(ctx context.Context, name string) (string, error)
}
// Config selects what Run checks.
type Config struct {
Driver SuiteDriver
// PeerDriver is a second driver. When set, a VM of the same name is created
// in both and the suite checks they never affect each other.
PeerDriver SuiteDriver
// VMName is the name of the VM the suite creates (default "drivertest-vm").
VMName string
// CreateOptions are the driver-specific options of a valid create request.
CreateOptions map[string]any
// ResizeSize is the size argument of a disk resize (default "+1G").
ResizeSize string
// Settle bounds how long the suite waits for a state change (default 15s).
Settle time.Duration
}
var (
validStates = map[string]bool{"stopped": true, "starting": true, "running": true, "stopping": true, "suspended": true, "broken": true}
endpointKinds = map[string]bool{"ssh": true, "wsl": true, "rdp": true, "vmconnect": true, "adb": true}
)
func (c *Config) defaults() {
if c.VMName == "" {
c.VMName = "drivertest-vm"
}
if c.ResizeSize == "" {
c.ResizeSize = "+1G"
}
if c.Settle <= 0 {
c.Settle = 15 * time.Second
}
}
func has(caps []string, c string) bool {
for _, x := range caps {
if x == c {
return true
}
}
return false
}
func waitFor(t *testing.T, timeout time.Duration, what string, cond func() (bool, string)) {
t.Helper()
deadline := time.Now().Add(timeout)
last := ""
for time.Now().Before(deadline) {
ok, detail := cond()
if ok {
return
}
last = detail
time.Sleep(25 * time.Millisecond)
}
t.Fatalf("timed out waiting for %s (%s)", what, last)
}
func (c *Config) createReq(d SuiteDriver, name string) CreateRequest {
return CreateRequest{DriverID: d.ID(), Name: name, Options: c.CreateOptions}
}
func checkVMShape(t *testing.T, d SuiteDriver, vm VMInfo) {
t.Helper()
if vm.DriverID != "" && vm.DriverID != d.ID() {
t.Errorf("VM %q reports driver %q, want %q", vm.Name, vm.DriverID, d.ID())
}
if !validStates[vm.State] {
t.Errorf("VM %q reports state %q", vm.Name, vm.State)
}
switch vm.Phase {
case "", PhaseNormal, PhaseInstaller, PhaseRecovery:
default:
t.Errorf("VM %q reports phase %q", vm.Name, vm.Phase)
}
for _, ep := range vm.Endpoints {
if !endpointKinds[ep.Kind] {
t.Errorf("VM %q reports endpoint kind %q", vm.Name, ep.Kind)
}
}
for _, capability := range vm.Capabilities {
if !has(d.Capabilities(), capability) {
t.Errorf("VM %q claims capability %q the driver did not declare", vm.Name, capability)
}
}
if vm.State == "stopped" && vm.Ready != nil && *vm.Ready {
t.Errorf("stopped VM %q reports ready", vm.Name)
}
if has(d.Capabilities(), CapHosted) && vm.PID != nil && *vm.PID > 0 {
t.Errorf("hosted VM %q reports a host-visible PID %d", vm.Name, *vm.PID)
}
}
func find(vms []VMInfo, name string) (VMInfo, bool) {
for _, vm := range vms {
if strings.EqualFold(vm.Name, name) {
return vm, true
}
}
return VMInfo{}, false
}
func show(t *testing.T, d SuiteDriver, name string) VMInfo {
t.Helper()
vm, err := d.Show(context.Background(), name)
if err != nil {
t.Fatalf("Show(%q): %v", name, err)
}
checkVMShape(t, d, vm)
return vm
}
func waitState(t *testing.T, d SuiteDriver, name, want string, timeout time.Duration) VMInfo {
t.Helper()
var got VMInfo
waitFor(t, timeout, fmt.Sprintf("VM %q to be %s", name, want), func() (bool, string) {
vm, err := d.Show(context.Background(), name)
if err != nil {
return false, err.Error()
}
got = vm
return vm.State == want, "state " + vm.State
})
checkVMShape(t, d, got)
return got
}
func cleanup(t *testing.T, d SuiteDriver, name string) {
t.Helper()
ctx := context.Background()
if vm, err := d.Show(ctx, name); err == nil && vm.State != "stopped" {
_ = d.Stop(ctx, name, true)
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if vm, err = d.Show(ctx, name); err != nil || vm.State == "stopped" {
break
}
time.Sleep(25 * time.Millisecond)
}
}
_ = d.Delete(ctx, name, false)
}
// Run executes the contract suite against cfg.Driver.
func Run(t *testing.T, cfg Config) {
t.Helper()
cfg.defaults()
if cfg.Driver == nil {
t.Fatal("drivertest: Config.Driver is nil")
}
d := cfg.Driver
name := cfg.VMName
ctx := context.Background()
t.Cleanup(func() {
cleanup(t, d, name)
cleanup(t, d, name+"-clone")
if cfg.PeerDriver != nil {
cleanup(t, cfg.PeerDriver, name)
}
})
t.Run("MetadataAndCapabilities", func(t *testing.T) { runMetadata(t, d) })
t.Run("UnknownVMAndInvalidCreate", func(t *testing.T) { runErrors(t, &cfg) })
t.Run("Lifecycle", func(t *testing.T) { runLifecycle(t, &cfg) })
t.Run("StorageLogsAndPhase", func(t *testing.T) { runStorage(t, &cfg) })
if cd, ok := d.(ConsoleSuiteDriver); ok {
t.Run("Console", func(t *testing.T) {
cleanup(t, d, name)
runConsole(t, &cfg, cd)
cleanup(t, d, name)
})
}
if cfg.PeerDriver != nil {
t.Run("SameNameIsolation", func(t *testing.T) { runIsolation(t, &cfg) })
}
_ = ctx
}
func runMetadata(t *testing.T, d SuiteDriver) {
if strings.TrimSpace(d.ID()) == "" {
t.Fatal("driver ID is empty")
}
seen := map[string]bool{}
for _, c := range d.Capabilities() {
if strings.TrimSpace(c) == "" || seen[c] {
t.Errorf("capability list has an empty or duplicate entry %q", c)
}
seen[c] = true
}
_, isSnap := d.(SnapshotSuiteDriver)
_, isClone := d.(CloneSuiteDriver)
_, isDisk := d.(DiskSuiteDriver)
for _, tc := range []struct {
capability string
implements bool
}{{CapSnapshot, isSnap}, {CapCowClone, isClone}, {CapResize, isDisk}} {
if has(d.Capabilities(), tc.capability) && !tc.implements {
t.Errorf("capability %q is declared but the driver does not implement its operations", tc.capability)
}
}
}
func runErrors(t *testing.T, cfg *Config) {
d := cfg.Driver
ctx := context.Background()
missing := cfg.VMName + "-does-not-exist"
if _, err := d.Show(ctx, missing); err == nil {
t.Errorf("Show of a missing VM succeeded")
}
if err := d.Start(ctx, missing); err == nil {
t.Errorf("Start of a missing VM succeeded")
}
before, err := d.List(ctx)
if err != nil {
t.Fatalf("List: %v", err)
}
bad := cfg.createReq(d, "")
issues := d.ValidateCreate(ctx, bad)
if len(issues) == 0 {
if err := d.Create(ctx, bad); err == nil {
t.Errorf("a create request without a name was accepted")
}
}
after, err := d.List(ctx)
if err != nil {
t.Fatalf("List: %v", err)
}
if len(after) != len(before) {
t.Errorf("an invalid create changed the VM list: %d -> %d", len(before), len(after))
}
}
func runLifecycle(t *testing.T, cfg *Config) {
d := cfg.Driver
name := cfg.VMName
ctx := context.Background()
if issues := d.ValidateCreate(ctx, cfg.createReq(d, name)); len(issues) > 0 {
t.Fatalf("a valid create request has issues: %+v", issues)
}
if err := d.Create(ctx, cfg.createReq(d, name)); err != nil {
t.Fatalf("Create: %v", err)
}
vms, err := d.List(ctx)
if err != nil {
t.Fatalf("List: %v", err)
}
listed, ok := find(vms, name)
if !ok {
t.Fatalf("created VM %q is not in List", name)
}
checkVMShape(t, d, listed)
if got := show(t, d, name); got.State != "stopped" {
t.Fatalf("a new VM is %q, want stopped", got.State)
}
if err := d.Start(ctx, name); err != nil {
t.Fatalf("Start: %v", err)
}
running := waitState(t, d, name, "running", cfg.Settle)
if running.Ready != nil && !*running.Ready {
waitFor(t, cfg.Settle, "guest readiness", func() (bool, string) {
vm, err := d.Show(ctx, name)
if err != nil {
return false, err.Error()
}
checkVMShape(t, d, vm)
return vm.Ready != nil && *vm.Ready, "not ready yet"
})
}
// Starting a running VM may succeed or fail, but it never stops it.
_ = d.Start(ctx, name)
if got := show(t, d, name); got.State != "running" && got.State != "starting" {
t.Errorf("starting a running VM left it %q", got.State)
}
if err := d.Stop(ctx, name, false); err != nil {
t.Fatalf("Stop: %v", err)
}
waitState(t, d, name, "stopped", cfg.Settle)
_ = d.Stop(ctx, name, false)
if got := show(t, d, name); got.State != "stopped" {
t.Errorf("stopping a stopped VM left it %q", got.State)
}
}
func runStorage(t *testing.T, cfg *Config) {
d := cfg.Driver
name := cfg.VMName
ctx := context.Background()
if vm, err := d.Show(ctx, name); err != nil || vm.State != "stopped" {
if err != nil {
if cerr := d.Create(ctx, cfg.createReq(d, name)); cerr != nil {
t.Fatalf("Create: %v", cerr)
}
} else {
t.Fatalf("VM %q is %q, want stopped", name, vm.State)
}
}
caps := d.Capabilities()
snap, isSnap := d.(SnapshotSuiteDriver)
switch {
case isSnap && has(caps, CapSnapshot):
if err := snap.RunSnapshot(ctx, name, "bogus", "drivertest-a"); err == nil {
t.Error("an unknown snapshot operation was accepted")
}
if err := snap.RunSnapshot(ctx, name, "create", "drivertest-a"); err != nil {
t.Fatalf("snapshot create: %v", err)
}
list, err := snap.ListSnapshots(ctx, name)
if err != nil || !hasSnapshot(list, "drivertest-a") {
t.Fatalf("snapshot list after create = %+v, %v", list, err)
}
if err := snap.RunSnapshot(ctx, name, "restore", "drivertest-a"); err != nil {
t.Errorf("snapshot restore: %v", err)
}
if err := snap.RunSnapshot(ctx, name, "delete", "drivertest-a"); err != nil {
t.Errorf("snapshot delete: %v", err)
}
if list, err = snap.ListSnapshots(ctx, name); err != nil || hasSnapshot(list, "drivertest-a") {
t.Errorf("snapshot list after delete = %+v, %v", list, err)
}
case isSnap:
if err := snap.RunSnapshot(ctx, name, "create", "drivertest-a"); err == nil {
t.Error("a snapshot was created without the snapshot capability")
}
}
clone, isClone := d.(CloneSuiteDriver)
switch {
case isClone && has(caps, CapCowClone):
if err := clone.CloneCoW(ctx, name, name+"-clone"); err != nil {
t.Fatalf("clone: %v", err)
}
if vms, err := d.List(ctx); err != nil {
t.Errorf("List: %v", err)
} else if _, ok := find(vms, name+"-clone"); !ok {
t.Error("the clone is not in List")
}
if err := d.Delete(ctx, name+"-clone", false); err != nil {
t.Errorf("deleting the clone: %v", err)
}
// A running source cannot be cloned.
if err := d.Start(ctx, name); err != nil {
t.Fatalf("Start: %v", err)
}
waitState(t, d, name, "running", cfg.Settle)
if err := clone.CloneCoW(ctx, name, name+"-clone"); err == nil {
t.Error("a running VM was cloned")
_ = d.Delete(ctx, name+"-clone", false)
}
if err := d.Stop(ctx, name, false); err != nil {
t.Fatalf("Stop: %v", err)
}
waitState(t, d, name, "stopped", cfg.Settle)
case isClone:
if err := clone.CloneCoW(ctx, name, name+"-clone"); err == nil {
t.Error("a clone was made without the cow_clone capability")
_ = d.Delete(ctx, name+"-clone", false)
}
}
disk, isDisk := d.(DiskSuiteDriver)
switch {
case isDisk && has(caps, CapResize):
if _, err := disk.ResizeDisk(ctx, name, cfg.ResizeSize); err != nil {
t.Errorf("resize: %v", err)
}
if _, err := disk.CompactDisk(ctx, name); err != nil {
t.Errorf("compact: %v", err)
}
case isDisk:
if _, err := disk.ResizeDisk(ctx, name, cfg.ResizeSize); err == nil {
t.Error("a disk was resized without the resize capability")
}
if _, err := disk.CompactDisk(ctx, name); err == nil {
t.Error("a disk was compacted without the resize capability")
}
}
if logs, ok := d.(LogSuiteDriver); ok {
for _, serial := range []bool{false, true} {
if _, err := logs.ReadLogs(ctx, name, serial); err != nil {
t.Errorf("ReadLogs(serial=%v): %v", serial, err)
}
}
}
if ph, ok := d.(PhaseSuiteDriver); ok {
phase, err := ph.Phase(ctx, name)
if err != nil {
t.Errorf("Phase: %v", err)
}
switch phase {
case PhaseNormal, PhaseInstaller, PhaseRecovery:
default:
t.Errorf("Phase = %q", phase)
}
}
}
func hasSnapshot(list []DiskSnapshot, name string) bool {
for _, s := range list {
if s.Name == name {
return true
}
}
return false
}
func runIsolation(t *testing.T, cfg *Config) {
a, b := cfg.Driver, cfg.PeerDriver
name := cfg.VMName
ctx := context.Background()
if a.ID() == b.ID() {
t.Fatal("PeerDriver must be a different driver")
}
if _, err := a.Show(ctx, name); err != nil {
if err := a.Create(ctx, cfg.createReq(a, name)); err != nil {
t.Fatalf("Create in %s: %v", a.ID(), err)
}
}
if err := b.Create(ctx, cfg.createReq(b, name)); err != nil {
t.Fatalf("Create the same-name VM in %s: %v", b.ID(), err)
}
for _, d := range []SuiteDriver{a, b} {
vms, err := d.List(ctx)
if err != nil {
t.Fatalf("List %s: %v", d.ID(), err)
}
n := 0
for _, vm := range vms {
if strings.EqualFold(vm.Name, name) {
n++
}
}
if n != 1 {
t.Errorf("driver %s lists %d VMs named %q, want 1", d.ID(), n, name)
}
}
if err := a.Start(ctx, name); err != nil {
t.Fatalf("Start in %s: %v", a.ID(), err)
}
waitState(t, a, name, "running", cfg.Settle)
if got := show(t, b, name); got.State != "stopped" {
t.Errorf("starting %s/%s moved the same-name VM of %s to %q", a.ID(), name, b.ID(), got.State)
}
if err := a.Stop(ctx, name, false); err != nil {
t.Fatalf("Stop in %s: %v", a.ID(), err)
}
waitState(t, a, name, "stopped", cfg.Settle)
if err := a.Delete(ctx, name, false); err != nil {
t.Fatalf("Delete in %s: %v", a.ID(), err)
}
if _, err := b.Show(ctx, name); err != nil {
t.Errorf("deleting %s/%s removed the same-name VM of %s: %v", a.ID(), name, b.ID(), err)
}
cleanup(t, b, name)
}