| 1 | package guestos |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "reflect" |
| 10 | "testing" |
| 11 | |
| 12 | "github.com/google/uuid" |
| 13 | "github.com/sylvinus/agent-vm/internal/cage" |
| 14 | ) |
| 15 | |
| 16 | type windowsStorageBrokerFixture struct { |
| 17 | t *testing.T |
| 18 | vm uuid.UUID |
| 19 | disk windowsStorageDisk |
| 20 | layout *windowsVMStorageLayout |
| 21 | before windowsStorageDisk |
| 22 | pending string |
| 23 | events []string |
| 24 | failAttach bool |
| 25 | failRecovery bool |
| 26 | } |
| 27 | |
| 28 | func (broker *windowsStorageBrokerFixture) call(_ context.Context, id uuid.UUID, input windowsHostStorageRequest) (windowsHostStorageState, error) { |
| 29 | broker.t.Helper() |
| 30 | if id != broker.vm || input.validate() != nil { |
| 31 | broker.t.Fatal("invalid fixed-VM request", input) |
| 32 | } |
| 33 | broker.events = append(broker.events, input.Action) |
| 34 | switch input.Action { |
| 35 | case "status": |
| 36 | return windowsHostStorageState{Disk: broker.disk, Pending: broker.pending, Layout: broker.layout}, nil |
| 37 | case "begin": |
| 38 | broker.before, broker.pending = broker.disk, input.ID |
| 39 | case "attach": |
| 40 | if input.ID != broker.pending { |
| 41 | broker.t.Fatal("attachment lost migration identity") |
| 42 | } |
| 43 | old, err := os.ReadFile(broker.before.Path) |
| 44 | if err != nil { |
| 45 | broker.t.Fatal(err) |
| 46 | } |
| 47 | copied, err := os.ReadFile(input.Disk) |
| 48 | if err != nil || !bytes.Equal(old, copied) { |
| 49 | broker.t.Fatal("runtime attached unverified disk bytes", err) |
| 50 | } |
| 51 | broker.disk = windowsStorageDisk{Path: input.Disk, Volume: 2, FileID: broker.before.FileID + 1} |
| 52 | if broker.failAttach { |
| 53 | return windowsHostStorageState{}, errors.New("response lost after attachment") |
| 54 | } |
| 55 | case "commit", "rollback": |
| 56 | if broker.failRecovery { |
| 57 | return windowsHostStorageState{}, errors.New("helper unavailable during recovery") |
| 58 | } |
| 59 | if input.Action == "rollback" { |
| 60 | if _, err := os.Stat(broker.before.Path); err != nil { |
| 61 | broker.t.Fatal("old stable directory was not restored before VM rollback", err) |
| 62 | } |
| 63 | if _, err := os.Stat(broker.disk.Path); err != nil { |
| 64 | broker.t.Fatal("new disk deleted before VM rollback", err) |
| 65 | } |
| 66 | broker.disk = broker.before |
| 67 | } |
| 68 | broker.pending = "" |
| 69 | } |
| 70 | return windowsHostStorageState{Disk: broker.disk, Pending: broker.pending, Outcome: input.Action}, nil |
| 71 | } |
| 72 | |
| 73 | func windowsStorageFixture(t *testing.T, external bool) (string, *windowsStorageRuntime, *windowsStorageBrokerFixture, WindowsProfile) { |
| 74 | t.Helper() |
| 75 | root, err := filepath.EvalSymlinks(t.TempDir()) |
| 76 | if err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | profile := filepath.Join(root, "profile") |
| 80 | instance := filepath.Join(profile, "state", "windows-existing") |
| 81 | if external { |
| 82 | instance = filepath.Join(root, "existing VM outside profile") |
| 83 | } |
| 84 | if err := os.MkdirAll(instance, 0700); err != nil { |
| 85 | t.Fatal(err) |
| 86 | } |
| 87 | if err := os.MkdirAll(profile, 0700); err != nil { |
| 88 | t.Fatal(err) |
| 89 | } |
| 90 | binding := windowsBindingFixture(profile) |
| 91 | binding.InstanceDirectory = instance |
| 92 | binding.RelayExecutable = filepath.Join(instance, "relay.exe") |
| 93 | binding.PairingFile = filepath.Join(instance, "pairing.dpapi") |
| 94 | binding.NetworkPairingFile = filepath.Join(instance, "network.dpapi") |
| 95 | for _, path := range []string{binding.RelayExecutable, binding.PairingFile, binding.NetworkPairingFile} { |
| 96 | if err := os.WriteFile(path, []byte("synthetic pairing bytes"), 0600); err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | } |
| 100 | disk := filepath.Join(instance, "system.vhdx") |
| 101 | createWindowsStorageFixtureDisk(t, disk) |
| 102 | if err := BindWindowsProfile(profile, binding); err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | broker := &windowsStorageBrokerFixture{t: t, vm: binding.VMID, disk: windowsStorageDisk{Path: disk, Volume: 1, FileID: 11}} |
| 106 | return profile, &windowsStorageRuntime{profile: profile, call: broker.call}, broker, binding |
| 107 | } |
| 108 | |
| 109 | func TestWindowsStorageMigrationPreservesPairingAndPriorDisks(t *testing.T) { |
| 110 | for _, external := range []bool{false, true} { |
| 111 | name := "managed_instance" |
| 112 | if external { |
| 113 | name = "existing_external_instance" |
| 114 | } |
| 115 | t.Run(name, func(t *testing.T) { |
| 116 | profile, runtime, broker, original := windowsStorageFixture(t, external) |
| 117 | originalDisk, err := os.ReadFile(broker.disk.Path) |
| 118 | if err != nil { |
| 119 | t.Fatal(err) |
| 120 | } |
| 121 | for attempt := 0; attempt < 2; attempt++ { |
| 122 | location, err := cage.GetStorageLocation(profile) |
| 123 | if err != nil || !location.HasEnvironment { |
| 124 | t.Fatal("Windows environment not detected", location, err) |
| 125 | } |
| 126 | target := filepath.Join(t.TempDir(), "环境存储") |
| 127 | moved, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil) |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | actual, err := LoadWindowsProfile(profile) |
| 132 | if err != nil || actual == nil || actual.VMID != original.VMID || actual.GUIUserSID != original.GUIUserSID { |
| 133 | t.Fatal("migration changed VM or GUI identity", err) |
| 134 | } |
| 135 | for _, path := range []string{actual.RelayExecutable, actual.PairingFile, actual.NetworkPairingFile} { |
| 136 | data, err := os.ReadFile(path) |
| 137 | if err != nil || string(data) != "synthetic pairing bytes" { |
| 138 | t.Fatal("pairing changed or lost its stable path", path, err) |
| 139 | } |
| 140 | } |
| 141 | if broker.pending != "" || !moved.Custom || moved.Backup == "" { |
| 142 | t.Fatal("migration did not finish or retain backup", moved, broker.pending) |
| 143 | } |
| 144 | if data, err := os.ReadFile(broker.disk.Path); err != nil || !bytes.Equal(data, originalDisk) { |
| 145 | t.Fatal("new disk unavailable", err) |
| 146 | } |
| 147 | if external && attempt == 0 { |
| 148 | private, err := cage.StoragePrivatePaths(profile) |
| 149 | if err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | found := false |
| 153 | for _, path := range private { |
| 154 | found = found || path == original.InstanceDirectory |
| 155 | } |
| 156 | if !found { |
| 157 | t.Fatal("external retained disk lost private-data protection", private) |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | if !reflect.DeepEqual(broker.events, []string{"status", "begin", "attach", "commit", "status", "begin", "attach", "commit"}) { |
| 162 | t.Fatal(broker.events) |
| 163 | } |
| 164 | }) |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestWindowsStorageAttachmentFailureRollsBackAndRetries(t *testing.T) { |
| 169 | profile, runtime, broker, original := windowsStorageFixture(t, false) |
| 170 | location, err := cage.GetStorageLocation(profile) |
| 171 | if err != nil { |
| 172 | t.Fatal(err) |
| 173 | } |
| 174 | target := filepath.Join(t.TempDir(), "destination") |
| 175 | broker.failAttach, broker.failRecovery = true, true |
| 176 | if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil); err == nil { |
| 177 | t.Fatal("lost native response treated as success") |
| 178 | } |
| 179 | if _, err := os.Stat(broker.disk.Path); err != nil { |
| 180 | t.Fatal("unresolved native disk was removed", err) |
| 181 | } |
| 182 | if _, err := cage.GetStorageLocation(profile); !errors.Is(err, cage.ErrStorageRuntimeRecovery) { |
| 183 | t.Fatal("shared loader bypassed native recovery", err) |
| 184 | } |
| 185 | broker.failRecovery = false |
| 186 | if err := cage.RecoverStorage(context.Background(), profile, runtime); err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | actual, err := LoadWindowsProfile(profile) |
| 190 | if err != nil || actual == nil || *actual != original { |
| 191 | t.Fatal("rollback changed original pairing", err) |
| 192 | } |
| 193 | if _, err := os.Stat(filepath.Join(target, "state")); !errors.Is(err, os.ErrNotExist) { |
| 194 | t.Fatal("resolved failed copy not removed", err) |
| 195 | } |
| 196 | broker.failAttach = false |
| 197 | if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil); err != nil { |
| 198 | t.Fatal("retry failed", err) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | func TestWindowsStorageCannotUseFilesystemOnlyMove(t *testing.T) { |
| 203 | profile, _, _, _ := windowsStorageFixture(t, false) |
| 204 | location, err := cage.GetStorageLocation(profile) |
| 205 | if err != nil { |
| 206 | t.Fatal(err) |
| 207 | } |
| 208 | target := filepath.Join(t.TempDir(), "destination") |
| 209 | if _, err := cage.MoveStorage(context.Background(), profile, target, location, nil); err == nil { |
| 210 | t.Fatal("filesystem migration left registered VM bound to its old inode") |
| 211 | } |
| 212 | if _, err := os.Stat(target); !errors.Is(err, os.ErrNotExist) { |
| 213 | t.Fatal("rejected move touched destination", err) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | func TestWindowsStorageExternalMetadataIsOwnedByHyperV(t *testing.T) { |
| 218 | profile, runtime, broker, original := windowsStorageFixture(t, true) |
| 219 | metadata := filepath.Join(original.InstanceDirectory, "Virtual Machines") |
| 220 | if err := os.Mkdir(metadata, 0700); err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | if err := os.WriteFile(filepath.Join(metadata, original.VMID.String()+".vmcx"), []byte("Hyper-V managed configuration"), 0600); err != nil { |
| 224 | t.Fatal(err) |
| 225 | } |
| 226 | if err := os.Chmod(metadata, 0000); err != nil { |
| 227 | t.Fatal(err) |
| 228 | } |
| 229 | t.Cleanup(func() { _ = os.Chmod(metadata, 0700) }) |
| 230 | broker.layout = &windowsVMStorageLayout{Configuration: original.InstanceDirectory, Snapshots: original.InstanceDirectory, Paging: original.InstanceDirectory} |
| 231 | location, err := cage.GetStorageLocation(profile) |
| 232 | if err != nil { |
| 233 | t.Fatal(err) |
| 234 | } |
| 235 | if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, filepath.Join(t.TempDir(), "target"), location, runtime, nil); err != nil { |
| 236 | t.Fatal("ordinary cold copy traversed native metadata", err) |
| 237 | } |
| 238 | next, err := LoadWindowsProfile(profile) |
| 239 | if err != nil { |
| 240 | t.Fatal(err) |
| 241 | } |
| 242 | if _, err := os.Stat(filepath.Join(next.InstanceDirectory, "Virtual Machines")); !errors.Is(err, os.ErrNotExist) { |
| 243 | t.Fatal("unregistered metadata duplicate copied into user storage", err) |
| 244 | } |
| 245 | } |