Files
Reims-Go/internal/app/console_router_test.go
T
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

238 lines
7.8 KiB
Go

package app
import (
"context"
"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"
)
type consoleTestApp struct {
app *App
drv driver.Driver
ref driver.VMRef
vmRoot string
svc *lifecycle.Service
harness *fakedriver.Harness
}
// newConsoleTestApp wires one hosted VM whose driver serves its own console.
func newConsoleTestApp(t *testing.T) *consoleTestApp {
t.Helper()
h := fakedriver.NewHarness(t)
drv := h.Add("hosted-console", "test.fake.console", "test.driver.console")
ctx := context.Background()
if err := drv.Create(ctx, driver.CreateRequest{DriverID: drv.ID(), Name: "dev"}, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
svc := lifecycle.New(h.Registry, h.Router, nil)
a := &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,
}
t.Cleanup(func() { releaseVMThumbnailForDriver(drv.ID(), "dev") })
ct := &consoleTestApp{app: a, drv: drv, ref: driver.NewVMRef(drv.ID(), "dev"), svc: svc, harness: h,
vmRoot: filepath.Join(h.DataRoot, "vms", drv.ID())}
if _, err := svc.Start(ctx, ct.ref, io.Discard, io.Discard); err != nil {
t.Fatal(err)
}
waitFor(t, "the VM to run", func() bool {
vms, err := a.listVMsInternal(ctx)
if err != nil {
return false
}
for _, vm := range vms {
if vm.Name == "dev" && vm.State == "running" {
return true
}
}
return false
})
return ct
}
func (ct *consoleTestApp) log(t *testing.T) string {
t.Helper()
raw, _ := os.ReadFile(filepath.Join(ct.vmRoot, fakedriver.ConsoleLogName))
return string(raw)
}
func TestDriverConsoleRouteIsChosenForAConsoleDriver(t *testing.T) {
ct := newConsoleTestApp(t)
vm, err := ct.app.resolveVMInfo(ct.drv.ID(), "dev")
if err != nil {
t.Fatal(err)
}
route, err := ct.app.resolveConsoleRoute(vm)
if err != nil || route.kind != consoleRouteDriver || route.console == nil {
t.Fatalf("route = %+v, %v; want the driver console", route, err)
}
// A VM whose capabilities were narrowed below `console` loses the route.
vm.Capabilities = []string{driver.CapHosted}
if _, err := ct.app.resolveConsoleRoute(vm); err == nil {
t.Fatal("a VM without the console capability got a console route")
}
}
func TestDriverConsoleServesGUIThumbnailAndTyping(t *testing.T) {
ct := newConsoleTestApp(t)
a := ct.app
thumb, err := a.GetVMThumbnailWithDriver(ct.drv.ID(), "dev")
if err != nil || !thumb.Live || !strings.HasPrefix(thumb.DataURL, "data:image/jpeg;base64,") {
t.Fatalf("thumbnail = live %v, %.30q, %v; want a live frame from the driver console", thumb.Live, thumb.DataURL, err)
}
n, err := a.TypeTextWithDriver(ct.drv.ID(), "dev", "hello")
if err != nil || n != 5 {
t.Fatalf("TypeTextWithDriver = %d, %v", n, err)
}
if got := ct.log(t); !strings.Contains(got, "type dev hello") {
t.Fatalf("the driver never received the text; its log is %q", got)
}
}
func TestDriverConsoleServesAgentInput(t *testing.T) {
ct := newConsoleTestApp(t)
a := ct.app
vm, err := a.resolveVMInfo(ct.drv.ID(), "dev")
if err != nil {
t.Fatal(err)
}
route, err := a.resolveConsoleRoute(vm)
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
if err := a.consolePointer(ctx, route, driver.ConsolePointerRequest{Action: "click", Button: "left"}); err != nil {
t.Fatal(err)
}
if err := a.consoleKey(ctx, route, "enter", []string{"shift"}); err != nil {
t.Fatal(err)
}
log := ct.log(t)
for _, want := range []string{"pointer dev click left", "key dev enter [shift]"} {
if !strings.Contains(log, want) {
t.Errorf("the driver log lacks %q: %q", want, log)
}
}
path, format, cleanup, err := a.consoleCapture(ctx, route, 1280)
if err != nil {
t.Fatal(err)
}
defer cleanup()
if format != "png" {
t.Fatalf("format = %q", format)
}
if st, err := os.Stat(path); err != nil || st.Size() == 0 {
t.Fatalf("frame file = %v, %v", st, err)
}
cleanup()
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatal("cleanup left the frame file behind")
}
}
// stubConsole is a driver console that writes its frame wherever it likes.
type stubConsole struct {
driver.ConsoleDriver
res driver.ConsoleScreenshotResult
file string // written when non-empty
}
func (s *stubConsole) ConsoleScreenshot(_ context.Context, _ string, req driver.ConsoleScreenshotRequest) (driver.ConsoleScreenshotResult, error) {
if s.file != "" {
if err := os.WriteFile(s.file, []byte("frame"), 0o644); err != nil {
return driver.ConsoleScreenshotResult{}, err
}
}
if s.res.Path == "" && s.file == "" {
if err := os.WriteFile(req.Path, []byte("frame"), 0o644); err != nil {
return driver.ConsoleScreenshotResult{}, err
}
}
return s.res, nil
}
func TestConsoleCaptureGuardsTheFramePathADriverReturns(t *testing.T) {
root := t.TempDir()
a := &App{cfg: &config.Config{DataRoot: root}}
route := func(c driver.ConsoleDriver) consoleRoute {
return consoleRoute{kind: consoleRouteDriver, vm: driver.VMInfo{Name: "dev", DriverID: "acme.driver"}, console: c}
}
ctx := context.Background()
// The frame the host asked for is accepted and deleted by cleanup.
_, _, cleanup, err := a.consoleCapture(ctx, route(&stubConsole{}), 0)
if err != nil {
t.Fatalf("a frame at the requested path was rejected: %v", err)
}
cleanup()
// Any other file is rejected, even one inside the data folder.
own := filepath.Join(root, "own-frame.png")
if _, _, _, err := a.consoleCapture(ctx, route(&stubConsole{file: own, res: driver.ConsoleScreenshotResult{Path: own}}), 0); err == nil {
t.Fatal("a frame at a path the driver chose was accepted")
}
// An unsupported frame format is rejected.
if _, _, _, err := a.consoleCapture(ctx, route(&stubConsole{res: driver.ConsoleScreenshotResult{Format: "bmp"}}), 0); err == nil {
t.Fatal("an unsupported frame format was accepted")
}
}
func TestAgentCallsOnADriverConsoleVMAskForConfirmationInProtectedPhases(t *testing.T) {
ct := newConsoleTestApp(t)
a := ct.app
const plugin = "reims.agent"
a.markComputerUseOwnedVM(plugin, ct.ref.Key(), true) // grants access without a plugin manager
vm, route, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key())
if err != nil || route.kind != consoleRouteDriver || vm.Name != "dev" {
t.Fatalf("a normal-phase driver console VM = %+v, %+v, %v", vm.Name, route.kind, err)
}
for _, phase := range []string{driver.PhaseInstaller, driver.PhaseRecovery} {
if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte(phase), 0o644); err != nil {
t.Fatal(err)
}
if _, _, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()); err == nil || !strings.Contains(err.Error(), "confirmation_required") {
t.Fatalf("phase %s: err = %v, want confirmation_required", phase, err)
}
}
// A phase the host cannot read must not pass for the normal one.
if err := os.WriteFile(filepath.Join(ct.vmRoot, "dev", "phase"), []byte("bogus"), 0o644); err != nil {
t.Fatal(err)
}
if _, _, err := a.resolveComputerUseVM(nil, plugin, ct.ref.Key()); err == nil {
t.Fatal("a VM with an unreadable phase was treated as normal")
}
}
func TestComputerUsePhasePrefersTheDriverReportedPhase(t *testing.T) {
for phase, want := range map[string]string{
"": "normal",
driver.PhaseNormal: "normal",
driver.PhaseInstaller: "installer",
driver.PhaseRecovery: "recovery",
} {
if got := computerUseVMPhase(driver.VMInfo{Phase: phase}); got != want {
t.Errorf("phase %q -> %q, want %q", phase, got, want)
}
}
}