| 1 | package vm |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 16 | ) |
| 17 | |
| 18 | func TestVMStartErrorPreservesQEMUFailureAndRedactsSecrets(t *testing.T) { |
| 19 | previous := diagnostics.Default() |
| 20 | store := diagnostics.New(t.TempDir()) |
| 21 | diagnostics.SetDefault(store) |
| 22 | t.Cleanup(func() { diagnostics.SetDefault(previous) }) |
| 23 | dir := t.TempDir() |
| 24 | log := strings.Repeat("{\"msg\":\"[qemu[stderr]] warning: host doesn't support requested feature\"}\n", 12) + `{"msg":"[qemu[stderr]] WHPX: Failed to enable nested virtualization, hr=80370302"} |
| 25 | {"msg":"[qemu[stderr]] failed to initialize whpx: Invalid argument token=private-test-value"} |
| 26 | panic: send on closed channel |
| 27 | ` |
| 28 | if err := os.WriteFile(filepath.Join(dir, "ha.stderr.log"), []byte(log), 0600); err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | cause := errors.New("host agent process has exited") |
| 32 | err := vmStartError(cause, dir, time.Time{}) |
| 33 | if !errors.Is(err, cause) || !strings.Contains(err.Error(), "80370302") || strings.Contains(err.Error(), "private-test-value") || strings.Contains(err.Error(), "panic:") { |
| 34 | t.Fatalf("bad startup error: %v", err) |
| 35 | } |
| 36 | var bundle bytes.Buffer |
| 37 | if err := store.Export(&bundle, "test", nil, "guest never booted"); err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | archive, err := zip.NewReader(bytes.NewReader(bundle.Bytes()), int64(bundle.Len())) |
| 41 | if err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | var exported strings.Builder |
| 45 | for _, file := range archive.File { |
| 46 | if !strings.HasPrefix(file.Name, "logs/") { |
| 47 | continue |
| 48 | } |
| 49 | r, err := file.Open() |
| 50 | if err != nil { |
| 51 | t.Fatal(err) |
| 52 | } |
| 53 | data, err := io.ReadAll(r) |
| 54 | r.Close() |
| 55 | if err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | exported.Write(data) |
| 59 | } |
| 60 | if text := exported.String(); !strings.Contains(text, "80370302") || !strings.Contains(text, "panic:") || strings.Contains(text, "private-test-value") { |
| 61 | t.Fatalf("diagnostic export lost details or exposed credentials: %s", text) |
| 62 | } |
| 63 | if vmStartError(context.Canceled, dir, time.Time{}) != context.Canceled { |
| 64 | t.Fatal("cancellation replaced by an old QEMU error") |
| 65 | } |
| 66 | if vmStartError(cause, dir, time.Now().Add(time.Second)) != cause { |
| 67 | t.Fatal("an earlier attempt's log replaced this failure") |
| 68 | } |
| 69 | } |