Files
Reims-Go/internal/app/diagnostics_test.go

699 lines
28 KiB
Go

package app
import (
"archive/zip"
"context"
"encoding/json"
"errors"
"io"
"io/fs"
"maps"
"math"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
func TestWriteDiagnosticsZipRedactsSensitiveData(t *testing.T) {
dataRoot := t.TempDir()
generatedAt := time.Date(2026, 12, 5, 10, 0, 0, 0, time.UTC)
result, err := writeDiagnosticsZip(filepath.Join(dataRoot, "reports"), "macos-tahoe", generatedAt, diagnosticsBundle{
HostReport: host.Report{
OS: "windows", Arch: "amd64", LogicalCPUs: 16, TotalRAMGB: 32, AvailRAMGB: 12,
FreeDiskGB: 64, DataRoot: dataRoot, DataRootDriveType: "fixed",
GPUs: []host.GPUInfo{{Name: "Test GPU", VulkanVersion: "1.3"}},
},
Runtime: &rt.Installed{Commit: "test-commit", Manifest: rt.Manifest{Name: "Test runtime", QemuVersion: "10"}},
VMInfo: &driver.VMInfo{Name: "macos-tahoe", CPUs: 4, Memory: "8G", DiskSummary: "64 GB"},
VMDetail: &reims.VMDetail{
Name: "macos-tahoe",
NetworkSummary: "user, mac 52:54:00:ab:cd:ef, ssh on 127.0.0.1:2222",
ExtraArgs: "-device isa-applesmc,osk=ourhardworkbythesewordsguardedpleasedontsteal",
},
SerialLog: "OpenCore presents iMac20,1, serial C02FAKE123456\n",
QEMULog: "ERROR_DEVICE_LOST " + filepath.Join(dataRoot, "vm.log") + " Authorization: Bearer 0123456789abcdef0123456789abcdef\n",
AppLogs: []string{`REIMS_TOKEN="abcdef0123456789abcdef0123456789"`},
})
if err != nil {
t.Fatalf("writeDiagnosticsZip: %v", err)
}
zr, err := zip.OpenReader(result.Path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
var all strings.Builder
var archivedFiles []string
for _, f := range zr.File {
rc, err := f.Open()
if err != nil {
t.Fatal(err)
}
b, err := io.ReadAll(rc)
rc.Close()
if err != nil {
t.Fatal(err)
}
all.WriteString(f.Name + ":\n" + string(b) + "\n")
archivedFiles = append(archivedFiles, f.Name)
if f.Name == "summary.txt" && string(b) != result.SummaryText {
t.Fatalf("archive summary differs from returned summary")
}
}
wantFiles := []string{"host-report.json", "runtime-manifest.json", "vm-detail.json", "vm-info.json", "serial.log", "qemu.log", "app-logs.txt", "summary.txt"}
if !slices.Equal(result.IncludedFiles, archivedFiles) || !slices.Equal(archivedFiles, wantFiles) {
t.Fatalf("returned files = %v, archived files = %v, want %v", result.IncludedFiles, archivedFiles, wantFiles)
}
info, err := os.Stat(result.Path)
if err != nil {
t.Fatal(err)
}
if result.FileName != info.Name() || result.SizeBytes != info.Size() || result.SizeBytes == 0 ||
result.TargetLabel != "macos-tahoe" || result.CanCopyFile != host.CanCopyFileToClipboard() {
t.Fatalf("unexpected export result: %+v", result)
}
if len(result.Findings) != 1 || result.Findings[0].Code != "gpu_device_lost" ||
strings.Contains(result.Findings[0].Detail, dataRoot) || !strings.Contains(result.Findings[0].Detail, "Bearer [redacted]") {
t.Fatalf("unexpected findings: %+v", result.Findings)
}
for _, fragment := range []string{generatedAt.Format(time.RFC3339), version.Version, "windows amd64",
"16 logical", "12.0 GB available", "64.0 GB free", "Test GPU", "test-commit",
"4 vCPUs", "gpu_device_lost", "- summary.txt", "Bearer [redacted]"} {
if !strings.Contains(result.SummaryText, fragment) {
t.Errorf("summary is missing %q:\n%s", fragment, result.SummaryText)
}
}
text := all.String()
for _, secret := range []string{
"52:54:00:ab:cd:ef",
"C02FAKE123456",
"ourhardworkbythesewordsguardedpleasedontsteal",
"0123456789abcdef0123456789abcdef",
"abcdef0123456789abcdef0123456789",
dataRoot,
strings.ReplaceAll(dataRoot, `\`, `\\`),
} {
if strings.Contains(text, secret) {
t.Fatalf("diagnostics zip leaked secret %q\n%s", secret, text)
}
}
if !strings.Contains(text, "[redacted]") {
t.Fatalf("expected [redacted] markers in zip output")
}
}
func TestWriteDiagnosticsZipEmptyAndFailedExport(t *testing.T) {
reports := filepath.Join(t.TempDir(), "reports")
now := time.Now()
result, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{})
if err != nil {
t.Fatal(err)
}
if !slices.Equal(result.IncludedFiles, []string{"host-report.json", "summary.txt"}) ||
result.Findings == nil || len(result.Findings) != 0 || !strings.Contains(result.SummaryText, "No known issues found") {
t.Fatalf("unexpected empty export: %+v", result)
}
if _, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{HostReport: host.Report{TotalRAMGB: math.NaN()}}); err == nil {
t.Fatal("expected the host report encoding to fail")
}
second, err := writeDiagnosticsZip(reports, "host", now, diagnosticsBundle{})
if err != nil || second.Path == result.Path {
t.Fatalf("same-time export returned %q, %v after %q", second.Path, err, result.Path)
}
files, err := os.ReadDir(reports)
if err != nil || len(files) != 2 {
t.Fatalf("reports directory after two successful exports and one failure: %v, %v", files, err)
}
}
func TestWriteDiagnosticsZipRedactsWindowsPaths(t *testing.T) {
dataRoot := filepath.Join(t.TempDir(), "PrivateData")
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
vmDir := filepath.Join(dataRoot, "PrivateVM")
disk := filepath.Join(dataRoot, "PrivateDisks", "vm.qcow2")
runtimeDir := filepath.Join(dataRoot, "PrivateRuntime")
pathVariant := func(path string) string {
if runtime.GOOS == "windows" {
return strings.ToUpper(filepath.ToSlash(path))
}
return path
}
const driverStore = `C:\Windows\System32\DriverStore\FileRepository\private_gpu.inf\vulkan.json`
const recommendedICD = `D:\Private Drivers\preferred-vulkan.json`
const otherDisk = `E:\Private VM Backups\Disk Images\boot.qcow2`
const anotherLog = `F:/Private Launcher Logs/startup.log`
report := host.Report{
DataRoot: dataRoot,
GPUs: []host.GPUInfo{{VulkanICD: driverStore}},
RecommendedGPU: &host.GPUInfo{VulkanICD: recommendedICD},
}
qemuLog := "ERROR_DEVICE_LOST " + otherDisk
result, err := writeDiagnosticsZip(filepath.Join(t.TempDir(), "reports"), "vm", time.Now(), diagnosticsBundle{
HostReport: report,
Runtime: &rt.Installed{Dir: runtimeDir, Manifest: rt.Manifest{Name: pathVariant(runtimeDir)}},
VMInfo: &driver.VMInfo{Name: "vm", Directory: vmDir, DiskPath: disk, DiskSummary: pathVariant(disk)},
VMDetail: &reims.VMDetail{ExtraArgs: `-device isa-applesmc,osk="test quoted value"`},
QEMULog: qemuLog,
SerialLog: `opening "` + anotherLog + `" for diagnostics`,
AppLogs: []string{pathVariant(dataRoot), pathVariant(home), pathVariant(vmDir)},
PluginDiagnostics: []plugin.DiagnosticsEntry{{
Data: map[string]any{"paths": []string{otherDisk, pathVariant(runtimeDir)}},
}},
})
if err != nil {
t.Fatal(err)
}
if report.GPUs[0].VulkanICD != driverStore || report.RecommendedGPU.VulkanICD != recommendedICD {
t.Fatal("redaction modified the original host report")
}
checkRedacted := func(name, content string) {
t.Helper()
for _, secret := range []string{
dataRoot, pathVariant(dataRoot), home, pathVariant(home), vmDir, pathVariant(vmDir),
disk, pathVariant(disk), runtimeDir, pathVariant(runtimeDir), "private_gpu.inf",
"Private Drivers", "Private VM Backups", "Disk Images", "Private Launcher Logs", "test quoted value",
} {
if strings.Contains(content, secret) || strings.Contains(content, strings.ReplaceAll(secret, `\`, `\\`)) {
t.Errorf("%s leaked %q", name, secret)
}
}
}
zr, err := zip.OpenReader(result.Path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
for _, file := range zr.File {
data, err := readDiagnosticsTestEntry(file)
if err != nil {
t.Fatal(err)
}
checkRedacted(file.Name, string(data))
if filepath.Ext(file.Name) == ".json" {
var value json.RawMessage
if err := json.Unmarshal(data, &value); err != nil {
t.Errorf("%s contains invalid JSON: %v", file.Name, err)
}
}
if file.Name == "host-report.json" {
var entry struct {
Host host.Report `json:"host"`
}
if err := json.Unmarshal(data, &entry); err != nil || len(entry.Host.GPUs) != 1 ||
entry.Host.GPUs[0].VulkanICD != "[redacted]" || entry.Host.RecommendedGPU == nil ||
entry.Host.RecommendedGPU.VulkanICD != "[redacted]" {
t.Errorf("host-report.json did not redact both Vulkan ICDs: %s (%v)", data, err)
}
}
}
checkRedacted("SummaryText", result.SummaryText)
if len(result.Findings) != 1 || result.Findings[0].Detail != "ERROR_DEVICE_LOST [redacted]" {
t.Fatalf("unexpected findings: %+v", result.Findings)
}
for _, finding := range result.Findings {
checkRedacted(finding.Code, finding.Detail)
}
}
func TestRedactDiagnosticsWindowsPathBoundaries(t *testing.T) {
redact := diagnosticsRedactor(diagnosticsBundle{})
for _, tc := range []struct{ input, want string }{
{`open D:\VM Backups\boot.qcow2: access is denied (0x5)`, "open [redacted]: access is denied (0x5)"},
{`-L D:\Runtime Files -m 8G`, "-L [redacted] -m 8G"},
{"GET https://example.test/runtime.zip failed: 404", "GET https://example.test/runtime.zip failed: 404"},
{`GET file://example.test/runtime.zip`, `GET file://example.test/runtime.zip`},
{`saved D:\Private\download.zip https://example.test/runtime.zip`, "saved [redacted] https://example.test/runtime.zip"},
{`GET "http://example.test/runtime.zip" failed: 404`, `GET "http://example.test/runtime.zip" failed: 404`},
{`open \\server\private-share\boot.qcow2: access denied`, "open [redacted]: access denied"},
{`open //server/private-share/boot.qcow2: access denied`, "open [redacted]: access denied"},
{`//server/private-share/boot.qcow2`, "[redacted]"},
{`"\\server\private share\boot.qcow2"`, `"[redacted]"`},
{`'D:\Private, Backup\boot.qcow2' next`, "'[redacted]' next"},
{`Could not open 'D:\O'Brien\boot.qcow2': access denied`, `Could not open '[redacted]': access denied`},
{`file=D:/vm/backups,other=[E:\Private Backup]; (F:\Runtime)`, "file=[redacted],other=[[redacted]]; ([redacted])"},
{"D:\\first\r\nE:\\second", "[redacted]\r\n[redacted]"},
} {
if got := redact(tc.input); got != tc.want {
t.Errorf("redact(%q) = %q, want %q", tc.input, got, tc.want)
}
}
}
func TestRedactDiagnosticsKnownRootWithPunctuation(t *testing.T) {
root := filepath.Join(t.TempDir(), "Private, VM")
path := filepath.Join(root, "private disk.qcow2")
if runtime.GOOS == "windows" {
path = strings.ToUpper(filepath.ToSlash(path))
}
redact := diagnosticsRedactor(diagnosticsBundle{HostReport: host.Report{DataRoot: root}})
if got, want := redact("open "+path+": access denied"), "open [redacted]: access denied"; got != want {
t.Errorf("redacted known root = %q, want %q", got, want)
}
}
func TestWriteDiagnosticsZipRedactsUNCPaths(t *testing.T) {
const qemu = `ERROR_DEVICE_LOST open \\server\private-share\boot.qcow2: access denied`
const serial = `VK_ERROR_INCOMPATIBLE_DRIVER opening "\\server\private share\boot.qcow2"`
const wantQEMU = "ERROR_DEVICE_LOST open [redacted]: access denied"
const wantSerial = `VK_ERROR_INCOMPATIBLE_DRIVER opening "[redacted]"`
result, err := writeDiagnosticsZip(t.TempDir(), "vm", time.Now(), diagnosticsBundle{
QEMULog: qemu, SerialLog: serial, AppLogs: []string{qemu, serial},
})
if err != nil {
t.Fatal(err)
}
for _, finding := range []host.DiagnosticFinding{
{Code: "gpu_device_lost", Severity: "error", Detail: wantQEMU},
{Code: "gpu_vulkan_floor", Severity: "error", Detail: wantSerial},
} {
if !slices.Contains(result.Findings, finding) || !strings.Contains(result.SummaryText, finding.Detail) {
t.Fatalf("missing %+v from findings or summary:\n%+v\n%s", finding, result.Findings, result.SummaryText)
}
}
for name, want := range map[string]string{
"qemu.log": wantQEMU, "serial.log": wantSerial,
"app-logs.txt": wantQEMU + "\n" + wantSerial + "\n", "summary.txt": result.SummaryText,
} {
if got := readDiagnosticsArchiveEntry(t, result.Path, name); got != want {
t.Errorf("%s = %q, want %q", name, got, want)
}
}
report := readDiagnosticsArchiveEntry(t, result.Path, "host-report.json")
var hostReport struct {
Diagnosis host.DiagnosticFinding `json:"gpu_diagnosis"`
}
if err := json.Unmarshal([]byte(report), &hostReport); err != nil || hostReport.Diagnosis.Detail != wantQEMU {
t.Fatalf("host report diagnosis = %+v, err %v", hostReport.Diagnosis, err)
}
for _, secret := range []string{"server", "private-share", "private share", "boot.qcow2"} {
if strings.Contains(result.SummaryText, secret) || strings.Contains(report, secret) {
t.Errorf("summary or host report leaked %q", secret)
}
}
}
func TestWriteDiagnosticsZipRedactsStructuredJSON(t *testing.T) {
result, err := writeDiagnosticsZip(t.TempDir(), "vm", time.Now(), diagnosticsBundle{
PluginDiagnostics: []plugin.DiagnosticsEntry{{Data: map[string]any{
"disks": map[string]string{
`D:\test\disk-a`: "disk A", `D:\test\disk-b`: "disk B", `D:\test\disk-c`: "disk C", "[redacted] #2": "literal key",
},
"hardware": []map[string]string{{
"mac": "02:00:00:00:00:01", "MAC_Address": "another-mac", "OSK": "short",
"SMC_OSK": "test-osk", "serial": "short-serial", "Serial_Number": "another-serial",
"MLB": "test-mlb", "RoM": "test-rom", "System_UUID": "test-uuid",
"smuuid": "", "model": "test-model",
"uuid": "12345678-1234-1234-1234-123456789abc", "token": "syntheticToken0123456789",
"REIMS_TOKEN": "test-reims", "GITHUB_TOKEN": "test-github", "Access_Token": "test-access",
"refresh_token": "test-refresh", "auth_token": "test-auth", "api_key": "test-key", "apikey": "test-apikey",
"password": "test-password", "passwd": "test-passwd", "secret": "test-secret",
"authorization": "test-authorization", "cookie": "test-cookie",
}},
}}},
})
if err != nil {
t.Fatal(err)
}
report := readDiagnosticsArchiveEntry(t, result.Path, "plugin-diagnostics.json")
var entries []struct {
Data struct {
Disks map[string]string
Hardware []map[string]string
}
}
if err := json.Unmarshal([]byte(report), &entries); err != nil || len(entries) != 1 || len(entries[0].Data.Hardware) != 1 {
t.Fatalf("invalid plugin diagnostics: %s (%v)", report, err)
}
wantDisks := map[string]string{
"[redacted]": "disk A", "[redacted] #2": "disk B", "[redacted] #3": "disk C", "[redacted] #2 #2": "literal key",
}
wantHardware := map[string]string{
"mac": "[redacted]", "MAC_Address": "[redacted]", "OSK": "[redacted]", "SMC_OSK": "[redacted]",
"serial": "[redacted]", "Serial_Number": "[redacted]", "MLB": "[redacted]", "RoM": "[redacted]",
"System_UUID": "[redacted]", "smuuid": "", "model": "test-model",
"uuid": "[redacted]", "token": "[redacted]", "REIMS_TOKEN": "[redacted]", "GITHUB_TOKEN": "[redacted]",
"Access_Token": "[redacted]", "refresh_token": "[redacted]", "auth_token": "[redacted]",
"api_key": "[redacted]", "apikey": "[redacted]", "password": "[redacted]", "passwd": "[redacted]",
"secret": "[redacted]", "authorization": "[redacted]", "cookie": "[redacted]",
}
if !maps.Equal(entries[0].Data.Disks, wantDisks) || !maps.Equal(entries[0].Data.Hardware[0], wantHardware) {
t.Fatalf("unexpected redacted data: %s", report)
}
if strings.Contains(report, `D:\\test\\disk-`) || strings.Contains(report, "02:00:00:00:00:01") {
t.Fatalf("plugin diagnostics leaked a path or hardware identifier: %s", report)
}
}
func TestExportDiagnosticsRejectsReadOnlyDataRoot(t *testing.T) {
root := t.TempDir()
a := &App{
cfg: &config.Config{DataRoot: root},
root: dataroot.Status{Dir: root, ReadOnly: true, Reason: dataroot.ReasonNewer},
}
result, err := a.ExportDiagnostics("", "")
if err == nil || !strings.Contains(err.Error(), "E_DATAROOT_NEWER") || result.Path != "" {
t.Fatalf("ExportDiagnostics returned %+v, %v", result, err)
}
if _, err := os.Stat(filepath.Join(root, "reports")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("reports directory stat: %v", err)
}
}
func newDiagnosticsTestApp(t *testing.T, drivers ...*appSecondDriver) *App {
t.Helper()
reg := plugin.NewRegistry(nil)
for _, d := range drivers {
err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test." + d.id, Version: "1.0.0"},
Source: plugin.SourceBuiltin,
Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, d.id, d)
return nil
},
})
if err != nil {
t.Fatal(err)
}
}
reg.Reconcile(t.Context())
return &App{
cfg: &config.Config{DataRoot: t.TempDir()},
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
}
}
func TestExportDiagnosticsVMChecksOnlyTargetAndHostLogs(t *testing.T) {
const dID = driver.BuiltinReimsMacOSDriverID
const otherID = "test.driver.other"
mac := &appSecondDriver{id: dID, vms: []driver.VMInfo{{Name: "vm-a"}, {Name: "vm-b"}}}
other := &appSecondDriver{id: otherID, vms: []driver.VMInfo{{Name: "vm-a"}}}
a := newDiagnosticsTestApp(t, mac, other)
a.emitVMLogForDriver(dID, "vm-b", "ERROR_DEVICE_LOST other instance")
a.emitVMLogForDriver(otherID, "vm-a", "ERROR_DEVICE_LOST other driver")
a.emitVMLogForDriver(dID, "vm-a", "VK_ERROR_INCOMPATIBLE_DRIVER target instance")
a.emitLog("host", "Hypervisor is disabled host detail")
a.emitLog("plugin:demo", "ERROR_DEVICE_LOST unscoped plugin stderr")
a.emitLog("plugin", "ERROR_DEVICE_LOST unscoped plugin error")
result, err := a.ExportDiagnostics(dID, "vm-a")
if err != nil {
t.Fatal(err)
}
if !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool {
return f.Code == "gpu_vulkan_floor" && strings.Contains(f.Detail, "target instance")
}) {
t.Fatalf("target VM's finding is missing: %+v", result.Findings)
}
for _, finding := range result.Findings {
if finding.Code == "gpu_device_lost" || strings.Contains(finding.Detail, "other instance") ||
strings.Contains(finding.Detail, "other driver") {
t.Errorf("another VM contributed a finding: %+v", finding)
}
}
for _, text := range []string{"ERROR_DEVICE_LOST", "gpu_device_lost", "other instance", "other driver", "unscoped plugin stderr", "unscoped plugin error"} {
if strings.Contains(result.SummaryText, text) {
t.Errorf("summary contains another VM's error: %s", result.SummaryText)
}
}
content := readDiagnosticsArchiveEntry(t, result.Path, "app-logs.txt")
for _, line := range []string{"[plugin:demo] ERROR_DEVICE_LOST unscoped plugin stderr", "[plugin] ERROR_DEVICE_LOST unscoped plugin error"} {
if !strings.Contains(content, line) {
t.Errorf("app-logs.txt is missing %q:\n%s", line, content)
}
}
a.emitLog("host", "ERROR_DEVICE_LOST shared host detail")
result, err = a.ExportDiagnostics(dID, "vm-a")
if err != nil {
t.Fatal(err)
}
if !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool {
return f.Code == "gpu_device_lost" && strings.Contains(f.Detail, "shared host detail")
}) {
t.Fatalf("host finding is missing: %+v", result.Findings)
}
}
func TestExportDiagnosticsReadsEarlierBuiltInVMLogs(t *testing.T) {
vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()}
a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}})
logDir := filepath.Join(vm.Directory, "logs")
if err := os.Mkdir(logDir, 0o755); err != nil {
t.Fatal(err)
}
// Both errors precede the preview window. QEMU's error also precedes the last 2 MiB.
tail := strings.Repeat(strings.Repeat("a", 2047)+"\n", 48)
logs := map[string]string{
"qemu.log": "ERROR_DEVICE_LOST earlier QEMU error\n" + strings.Repeat(tail, 24),
"serial.log": "VK_ERROR_INCOMPATIBLE_DRIVER earlier serial error\n" + tail,
}
for name, content := range logs {
if err := os.WriteFile(filepath.Join(logDir, name), []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
result, err := a.ExportDiagnostics(vm.DriverID, vm.Name)
if err != nil {
t.Fatal(err)
}
for _, detail := range []string{"earlier QEMU error", "earlier serial error"} {
if !strings.Contains(result.SummaryText, detail) || !slices.ContainsFunc(result.Findings, func(f host.DiagnosticFinding) bool {
return strings.Contains(f.Detail, detail)
}) {
t.Errorf("earlier error %q is missing from findings or summary", detail)
}
}
if strings.Contains(result.SummaryText, "truncated:") {
t.Fatalf("summary reports truncation for complete logs:\n%s", result.SummaryText)
}
zr, err := zip.OpenReader(result.Path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
for _, file := range zr.File {
want, ok := logs[file.Name]
if !ok {
continue
}
content, err := readDiagnosticsTestEntry(file)
if err != nil || string(content) != want {
t.Fatalf("%s did not retain the full log: got %d bytes, want %d, err %v", file.Name, len(content), len(want), err)
}
delete(logs, file.Name)
}
if len(logs) != 0 {
t.Fatal("expected both VM logs in the archive")
}
}
func TestExportDiagnosticsTruncatesOversizedBuiltInVMLog(t *testing.T) {
vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()}
a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}})
logDir := filepath.Join(vm.Directory, "logs")
if err := os.Mkdir(logDir, 0o755); err != nil {
t.Fatal(err)
}
const start = "ERROR_DEVICE_LOST first startup error\n"
const end = "VK_ERROR_INCOMPATIBLE_DRIVER last crash error\n"
head := start + strings.Repeat("a", (1<<20)-len(start)-1) + "\n"
tail := strings.Repeat("c", (4<<20)-len(end)-1) + "\n" + end
full := head + "middle omitted\n" + strings.Repeat("b", 11<<20) + "\n" + tail
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte(full), 0o600); err != nil {
t.Fatal(err)
}
result, err := a.ExportDiagnostics(vm.DriverID, vm.Name)
if err != nil {
t.Fatal(err)
}
got := readDiagnosticsArchiveEntry(t, result.Path, "qemu.log")
want := head + "\n[log truncated: middle omitted]\n" + tail
if got != want {
t.Fatalf("truncated log differs from the expected head, marker and tail (%d vs %d bytes)", len(got), len(want))
}
for _, finding := range []host.DiagnosticFinding{
{Code: "gpu_device_lost", Severity: "error", Detail: strings.TrimSpace(start)},
{Code: "gpu_vulkan_floor", Severity: "error", Detail: strings.TrimSpace(end)},
} {
if !slices.Contains(result.Findings, finding) {
t.Errorf("missing %+v from findings: %+v", finding, result.Findings)
}
}
const note = "qemu.log truncated: first 1 MiB and last 4 MiB retained"
if !strings.Contains(result.SummaryText, note) || readDiagnosticsArchiveEntry(t, result.Path, "summary.txt") != result.SummaryText {
t.Fatalf("summary is missing the truncation note or differs from summary.txt:\n%s", result.SummaryText)
}
}
func TestExportDiagnosticsDropsPartialLinesAtLogCutoffs(t *testing.T) {
vm := driver.VMInfo{Name: "vm", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir()}
a := newDiagnosticsTestApp(t, &appSecondDriver{id: vm.DriverID, vms: []driver.VMInfo{vm}})
logDir := filepath.Join(vm.Directory, "logs")
if err := os.Mkdir(logDir, 0o755); err != nil {
t.Fatal(err)
}
const start = "first complete line\n"
const end = "last complete line\n"
const partialTail = "Private Folder\\boot.qcow2: access denied\n"
head := start + "partial head line " + strings.Repeat("a", 1<<20) + "\n"
tail := partialTail + strings.Repeat("c", (4<<20)-len(partialTail)-len(end)-1) + "\n" + end
full := head + strings.Repeat("b", 12<<20) + "\nopen D:\\" + tail
if err := os.WriteFile(filepath.Join(logDir, "qemu.log"), []byte(full), 0o600); err != nil {
t.Fatal(err)
}
result, err := a.ExportDiagnostics(vm.DriverID, vm.Name)
if err != nil {
t.Fatal(err)
}
got := readDiagnosticsArchiveEntry(t, result.Path, "qemu.log")
for _, fragment := range []string{"partial head line", "Private Folder", "boot.qcow2"} {
if strings.Contains(got, fragment) {
t.Errorf("truncated log retained incomplete line fragment %q", fragment)
}
}
if !strings.HasPrefix(got, start+"\n[log truncated: middle omitted]\n") || !strings.HasSuffix(got, end) {
t.Fatal("truncated log lost a complete line or the truncation marker")
}
}
func readDiagnosticsArchiveEntry(t *testing.T, path, name string) string {
t.Helper()
zr, err := zip.OpenReader(path)
if err != nil {
t.Fatal(err)
}
defer zr.Close()
data, err := fs.ReadFile(zr, name)
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
return string(data)
}
func readDiagnosticsTestEntry(file *zip.File) ([]byte, error) {
rc, err := file.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return io.ReadAll(rc)
}
func TestResolveDiagnosticsZipPath(t *testing.T) {
root := t.TempDir()
reports := filepath.Join(root, "reports")
dir := filepath.Join(reports, "dir.zip")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
outside := filepath.Join(root, "reports-backup")
if err := os.Mkdir(outside, 0o755); err != nil {
t.Fatal(err)
}
valid := filepath.Join(reports, "export.ZIP")
wrongExt := filepath.Join(reports, "export.txt")
escaped := filepath.Join(outside, "export.zip")
nested := filepath.Join(dir, "nested.zip")
for _, path := range []string{valid, wrongExt, escaped, nested} {
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
}
link := filepath.Join(reports, "link")
if runtime.GOOS == "windows" {
if out, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput(); err != nil {
t.Fatalf("make junction: %v\n%s", err, out)
}
} else if err := os.Symlink(outside, link); err != nil {
t.Fatal(err)
}
want, err := filepath.EvalSymlinks(valid)
if err != nil {
t.Fatal(err)
}
if got, err := resolveDiagnosticsZipPath(root, valid); err != nil || got != want {
t.Fatalf("resolveDiagnosticsZipPath(%q) = %q, %v, want %q", valid, got, err, want)
}
for name, path := range map[string]string{
"empty": "", "directory": dir, "missing": filepath.Join(reports, "missing.zip"),
"outside": escaped, "wrong extension": wrongExt, "link escape": filepath.Join(link, "export.zip"),
"nested file": nested,
"traversal": reports + string(os.PathSeparator) + "../reports-backup/export.zip",
} {
t.Run(name, func(t *testing.T) {
if got, err := resolveDiagnosticsZipPath(root, path); err == nil {
t.Errorf("accepted %q as %q", path, got)
}
})
}
}
func TestResolveDiagnosticsZipPathRejectsCaseSensitiveSibling(t *testing.T) {
root := t.TempDir()
var caseOutput []byte
if runtime.GOOS == "windows" {
output, err := exec.Command("fsutil.exe", "file", "setCaseSensitiveInfo", root, "enable").CombinedOutput()
if err != nil {
t.Skipf("cannot enable case sensitivity on the temporary directory: %v (%s)", err, output)
}
caseOutput = output
}
reports := filepath.Join(root, "reports")
sibling := filepath.Join(root, "REPORTS")
for _, dir := range []string{reports, sibling} {
if err := os.Mkdir(dir, 0o755); err != nil {
if dir == sibling && errors.Is(err, os.ErrExist) {
t.Skipf("temporary directory is case-insensitive: %v (%s)", err, strings.TrimSpace(string(caseOutput)))
}
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "export.zip"), nil, 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := resolveDiagnosticsZipPath(root, filepath.Join(reports, "export.zip")); err != nil {
t.Fatalf("authorized reports directory rejected: %v", err)
}
if path, err := resolveDiagnosticsZipPath(root, filepath.Join(sibling, "export.zip")); err == nil {
t.Fatalf("accepted export from case-sensitive sibling: %s", path)
}
}
func TestResolveDiagnosticsZipPathRejectsDirectSymlinkEscape(t *testing.T) {
root := t.TempDir()
reports := filepath.Join(root, "reports")
if err := os.Mkdir(reports, 0o755); err != nil {
t.Fatal(err)
}
outside := filepath.Join(root, "outside.zip")
if err := os.WriteFile(outside, nil, 0o600); err != nil {
t.Fatal(err)
}
link := filepath.Join(reports, "link.zip")
if err := os.Symlink(outside, link); err != nil {
t.Skipf("cannot create a symbolic link: %v", err)
}
if path, err := resolveDiagnosticsZipPath(root, link); err == nil {
t.Fatalf("accepted symlink to outside of reports: %s", path)
}
}