| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "net/http/cookiejar" |
| 13 | "net/url" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "path/filepath" |
| 17 | "runtime" |
| 18 | "strings" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "github.com/google/uuid" |
| 23 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 24 | ) |
| 25 | |
| 26 | func storageRecoveryServer(t *testing.T) *Server { |
| 27 | t.Helper() |
| 28 | s := testServer(t) |
| 29 | workspace := filepath.Join(t.TempDir(), "workspace") |
| 30 | if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": workspace}); err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | instance := filepath.Join(s.profile, "state", "guest-os", "synthetic-vm") |
| 34 | if err := os.MkdirAll(instance, 0700); err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | binding := guestos.WindowsProfile{ |
| 38 | Version: 1, VMID: uuid.New(), GUIUserSID: "S-1-5-21-1-2-3-1001", |
| 39 | InstanceDirectory: instance, RelayExecutable: filepath.Join(instance, "missing-relay.exe"), |
| 40 | PairingFile: filepath.Join(instance, "synthetic-pairing.dpapi"), |
| 41 | } |
| 42 | if err := guestos.BindWindowsProfile(s.profile, binding); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | s.windowsGuest = &binding |
| 46 | return s |
| 47 | } |
| 48 | |
| 49 | func storageRecoveryJournal(t *testing.T, s *Server) string { |
| 50 | t.Helper() |
| 51 | id := strings.Repeat("a", 32) |
| 52 | target := filepath.Join(t.TempDir(), "destination") |
| 53 | journal := filepath.Join(s.profile, "environment-storage-pending.json") |
| 54 | if err := writePrivate(journal, map[string]any{ |
| 55 | "Next": map[string]any{"Directory": target, "ID": id}, |
| 56 | "Runtime": "windows-hyperv", |
| 57 | "Transition": map[string]any{ |
| 58 | "id": id, "source": filepath.Join(s.profile, "state"), |
| 59 | "destination": filepath.Join(target, "state"), "backup": filepath.Join(s.profile, "state-backup-"+id), |
| 60 | "state": map[string]any{ |
| 61 | "profile": s.windowsGuest, "instance": s.windowsGuest.InstanceDirectory, |
| 62 | "disk": map[string]any{"path": filepath.Join(s.windowsGuest.InstanceDirectory, "disk.vhdx"), "volume": 1, "file_id": 2}, |
| 63 | }, |
| 64 | }, |
| 65 | }); err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | return journal |
| 69 | } |
| 70 | |
| 71 | func TestStorageRecoveryKeepsHostAccessAndBlocksEnvironmentMutations(t *testing.T) { |
| 72 | s := storageRecoveryServer(t) |
| 73 | s.ready = true |
| 74 | s.windowsState.Running = true |
| 75 | s.networkIntentError = "synthetic independent network failure" |
| 76 | s.failStorageRecovery(errors.New("synthetic system manager unavailable")) |
| 77 | for _, endpoint := range []string{"/api/account", "/api/status", "/api/settings", "/api/environment/storage", "/api/environment/initialization", "/api/diagnostics", "/api/diagnostics/export"} { |
| 78 | response := windowsBrowserRequestForTest(s, http.MethodGet, endpoint, nil) |
| 79 | if response.Code != http.StatusOK { |
| 80 | t.Fatalf("host access %s returned %d %s", endpoint, response.Code, response.Body.String()) |
| 81 | } |
| 82 | if endpoint == "/api/status" { |
| 83 | var view struct { |
| 84 | Ready bool `json:"ready"` |
| 85 | NetworkError string `json:"network_error"` |
| 86 | StorageRecovery storageRecoveryView `json:"storage_recovery"` |
| 87 | } |
| 88 | if err := json.Unmarshal(response.Body.Bytes(), &view); err != nil { |
| 89 | t.Fatal(err) |
| 90 | } |
| 91 | if view.Ready || !view.StorageRecovery.Required || view.StorageRecovery.Error != "synthetic system manager unavailable" || view.NetworkError != s.networkIntentError { |
| 92 | t.Fatal("recovery did not preserve the independent causes", view) |
| 93 | } |
| 94 | } |
| 95 | if endpoint == "/api/diagnostics/export" { |
| 96 | if _, err := zip.NewReader(bytes.NewReader(response.Body.Bytes()), int64(response.Body.Len())); err != nil { |
| 97 | t.Fatal("pending recovery prevented a valid diagnostic export", err) |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | for _, endpoint := range []string{ |
| 102 | "/api/start", "/api/stop", "/api/settings", "/api/projects/open", "/api/environment/resources", |
| 103 | "/api/environment/storage", "/api/environment/update", "/api/environment/initialization", |
| 104 | "/api/browser/open", "/api/input", "/api/input/paste/start", "/api/clipboard/copy", "/api/account/logout", |
| 105 | } { |
| 106 | response := windowsBrowserRequestForTest(s, http.MethodPost, endpoint, []byte(`{}`)) |
| 107 | if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "synthetic system manager unavailable") { |
| 108 | t.Fatalf("mutation %s reached its receiver: %d %s", endpoint, response.Code, response.Body.String()) |
| 109 | } |
| 110 | } |
| 111 | for _, endpoint := range []string{"/api/browser/state", "/api/vnc", "/api/terminals", "/api/audio"} { |
| 112 | if response := windowsBrowserRequestForTest(s, http.MethodGet, endpoint, nil); response.Code != http.StatusConflict { |
| 113 | t.Fatalf("guest session %s was admitted: %d", endpoint, response.Code) |
| 114 | } |
| 115 | } |
| 116 | if err := s.attachWindowsGuestContext(context.Background()); err == nil || !strings.Contains(err.Error(), "synthetic system manager unavailable") { |
| 117 | t.Fatal("periodic attach bypassed recovery", err) |
| 118 | } |
| 119 | if err := s.startWindowsGuest(); err == nil || !strings.Contains(err.Error(), "synthetic system manager unavailable") { |
| 120 | t.Fatal("direct start bypassed recovery", err) |
| 121 | } |
| 122 | if _, err := s.submitJob("network-recovery", func() error { t.Error("background mutation ran"); return nil }); err == nil { |
| 123 | t.Fatal("background job bypassed recovery") |
| 124 | } |
| 125 | s.monitorNetworkTick() |
| 126 | if s.jobs.snapshot().ID != "" { |
| 127 | t.Fatal("recovery gate created an environment job") |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | func TestStorageRecoverySuccessfulRetryPreparesEnvironmentAndPreservesBinding(t *testing.T) { |
| 132 | s := storageRecoveryServer(t) |
| 133 | original, err := os.ReadFile(guestos.WindowsProfilePath(s.profile)) |
| 134 | if err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | s.failStorageRecovery(errors.New("previous attempt lost its helper connection")) |
| 138 | response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)) |
| 139 | if response.Code != http.StatusOK { |
| 140 | t.Fatal(response.Code, response.Body.String()) |
| 141 | } |
| 142 | job := awaitJobIdle(t, &s.jobs) |
| 143 | if job.Error != "" || job.Kind != "storage-recovery" || s.storageRecoveryStatus().Required || s.ready { |
| 144 | t.Fatal("successful retry failed to restore admission without starting a VM", job, s.storageRecoveryStatus()) |
| 145 | } |
| 146 | if info, err := os.Stat(s.environmentDir()); err != nil || !info.IsDir() { |
| 147 | t.Fatal("normal environment preparation did not run", err) |
| 148 | } |
| 149 | if current, err := os.ReadFile(guestos.WindowsProfilePath(s.profile)); err != nil || !bytes.Equal(current, original) { |
| 150 | t.Fatal("retry changed VM or pairing identity", err) |
| 151 | } |
| 152 | if response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/storage", nil); response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"directory"`) { |
| 153 | t.Fatal("recovered storage form remained unavailable", response.Code, response.Body.String()) |
| 154 | } |
| 155 | admitted := false |
| 156 | if _, err := s.submitJob("start", func() error { admitted = true; return nil }); err != nil { |
| 157 | t.Fatal("successful recovery kept normal start admission closed", err) |
| 158 | } |
| 159 | awaitJobIdle(t, &s.jobs) |
| 160 | if !admitted { |
| 161 | t.Fatal("normal start was not executed") |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | func TestStorageRecoveryFailureAndReadOnlyLocationPreserveJournal(t *testing.T) { |
| 166 | if runtime.GOOS == "windows" { |
| 167 | t.Skip("the synthetic native journal uses the non-Windows rejection without contacting a real Hyper-V service") |
| 168 | } |
| 169 | s := storageRecoveryServer(t) |
| 170 | journal := storageRecoveryJournal(t, s) |
| 171 | original, err := os.ReadFile(journal) |
| 172 | if err != nil { |
| 173 | t.Fatal(err) |
| 174 | } |
| 175 | response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/storage", nil) |
| 176 | if response.Code != http.StatusOK || !s.storageRecoveryStatus().Required { |
| 177 | t.Fatal("location did not expose native recovery", response.Code, response.Body.String()) |
| 178 | } |
| 179 | for _, repair := range []bool{false, true} { |
| 180 | response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(fmt.Sprintf(`{"repair":%t}`, repair))) |
| 181 | if response.Code != http.StatusOK { |
| 182 | t.Fatal(response.Code, response.Body.String()) |
| 183 | } |
| 184 | job := awaitJobIdle(t, &s.jobs) |
| 185 | state := s.storageRecoveryStatus() |
| 186 | if job.Error == "" || !state.Required || state.Error != job.Error || s.ready { |
| 187 | t.Fatal("failed recovery cleared the cause or resumed writes", repair, job, state) |
| 188 | } |
| 189 | if current, err := os.ReadFile(journal); err != nil || !bytes.Equal(current, original) { |
| 190 | t.Fatal("failed native recovery changed its durable ownership record", repair, err) |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | func TestStorageRecoveryPreparationFailureKeepsWritesClosed(t *testing.T) { |
| 196 | s := storageRecoveryServer(t) |
| 197 | if err := os.WriteFile(s.environmentDir(), []byte("synthetic occupied workspace path"), 0600); err != nil { |
| 198 | t.Fatal(err) |
| 199 | } |
| 200 | s.failStorageRecovery(errors.New("previous native recovery failure")) |
| 201 | response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)) |
| 202 | if response.Code != http.StatusOK { |
| 203 | t.Fatal(response.Code, response.Body.String()) |
| 204 | } |
| 205 | job := awaitJobIdle(t, &s.jobs) |
| 206 | if job.Error == "" || !s.storageRecoveryStatus().Required || s.ready { |
| 207 | t.Fatal("failed workspace preparation resumed environment writes", job) |
| 208 | } |
| 209 | if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/start", []byte(`{}`)); response.Code != http.StatusConflict { |
| 210 | t.Fatal("preparation failure opened start admission", response.Code) |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | func TestStorageRecoveryRejectsChangedBindingAndKeepsAuthentication(t *testing.T) { |
| 215 | s := storageRecoveryServer(t) |
| 216 | s.failStorageRecovery(errors.New("synthetic pending migration")) |
| 217 | if response := request(s, http.MethodPost, "/api/environment/storage/recover", s.origin, `{}`, false); response.Code != http.StatusUnauthorized { |
| 218 | t.Fatal("unauthenticated recovery was admitted", response.Code) |
| 219 | } |
| 220 | if response := request(s, http.MethodPost, "/api/environment/storage/recover", s.origin, `{}`, true); response.Code != http.StatusForbidden { |
| 221 | t.Fatal("untrusted native recovery was admitted", response.Code) |
| 222 | } |
| 223 | s.account.lock() |
| 224 | if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)); response.Code != http.StatusLocked { |
| 225 | t.Fatal("locked account could recover storage", response.Code) |
| 226 | } |
| 227 | s.account.setKey(make([]byte, 32)) |
| 228 | changed := *s.windowsGuest |
| 229 | changed.VMID = uuid.New() |
| 230 | if err := writePrivate(guestos.WindowsProfilePath(s.profile), changed); err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)); response.Code != http.StatusOK { |
| 234 | t.Fatal(response.Code, response.Body.String()) |
| 235 | } |
| 236 | job := awaitJobIdle(t, &s.jobs) |
| 237 | if job.Error == "" || !s.storageRecoveryStatus().Required { |
| 238 | t.Fatal("recovery switched to an unrelated VM", job) |
| 239 | } |
| 240 | if _, err := os.Stat(s.environmentDir()); !errors.Is(err, os.ErrNotExist) { |
| 241 | t.Fatal("identity mismatch reached environment preparation", err) |
| 242 | } |
| 243 | local := testServer(t) |
| 244 | local.remote = newRemoteGateway(local.profile) |
| 245 | defer local.remote.manager.Close() |
| 246 | local.remote.setRemote(true) |
| 247 | if response := request(local, http.MethodPost, "/api/environment/storage/recover", local.origin, `{}`, true); response.Code != http.StatusForbidden { |
| 248 | t.Fatal("remote connection could dispatch local recovery", response.Code) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | func TestStorageRecoveryDoesNotCaptureUnrelatedNetworkFailure(t *testing.T) { |
| 253 | s := storageRecoveryServer(t) |
| 254 | s.networkIntentError = "synthetic proxy connection failure" |
| 255 | response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/status", nil) |
| 256 | if response.Code != http.StatusOK || s.storageRecoveryStatus().Required || !strings.Contains(response.Body.String(), s.networkIntentError) { |
| 257 | t.Fatal("network failure became a storage failure", response.Code, response.Body.String()) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | func TestStorageRecoveryProductionStartupKeepsLoginAndDiagnostics(t *testing.T) { |
| 262 | if runtime.GOOS == "windows" { |
| 263 | t.Skip("isolated production startup uses a non-Windows native rejection and never contacts Hyper-V") |
| 264 | } |
| 265 | const helper = "CAGE_TEST_STORAGE_RECOVERY_CONFIG" |
| 266 | if config := os.Getenv(helper); config != "" { |
| 267 | if err := Serve(config); err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | return |
| 271 | } |
| 272 | for _, pending := range []bool{true, false} { |
| 273 | t.Run(fmt.Sprintf("native_pending=%t", pending), func(t *testing.T) { |
| 274 | testStorageRecoveryProductionStartup(t, pending) |
| 275 | }) |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | func testStorageRecoveryProductionStartup(t *testing.T, pending bool) { |
| 280 | s := storageRecoveryServer(t) |
| 281 | var journal string |
| 282 | var original []byte |
| 283 | if pending { |
| 284 | journal = storageRecoveryJournal(t, s) |
| 285 | var err error |
| 286 | original, err = os.ReadFile(journal) |
| 287 | if err != nil { |
| 288 | t.Fatal(err) |
| 289 | } |
| 290 | } else if err := os.WriteFile(s.environmentDir(), []byte("synthetic occupied workspace path"), 0600); err != nil { |
| 291 | t.Fatal(err) |
| 292 | } |
| 293 | if err := writePrivate(filepath.Join(s.profile, "initialization.json"), initializationRecord{Version: 1, Started: true}); err != nil { |
| 294 | t.Fatal(err) |
| 295 | } |
| 296 | account, err := loadLocalAccount(s.profile) |
| 297 | if err != nil { |
| 298 | t.Fatal(err) |
| 299 | } |
| 300 | if err := account.create("Storage QA", "synthetic-recovery-password", ""); err != nil { |
| 301 | t.Fatal(err) |
| 302 | } |
| 303 | account.lock() |
| 304 | ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 305 | defer cancel() |
| 306 | command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStorageRecoveryProductionStartupKeepsLoginAndDiagnostics$", "-test.timeout=20s") |
| 307 | command.Env = append(os.Environ(), "CAGE_TEST_STORAGE_RECOVERY_CONFIG="+s.configPath) |
| 308 | var output bytes.Buffer |
| 309 | command.Stdout, command.Stderr = &output, &output |
| 310 | if err := command.Start(); err != nil { |
| 311 | t.Fatal(err) |
| 312 | } |
| 313 | done := make(chan error, 1) |
| 314 | go func() { done <- command.Wait() }() |
| 315 | finished := false |
| 316 | t.Cleanup(func() { |
| 317 | if !finished { |
| 318 | _ = command.Process.Kill() |
| 319 | <-done |
| 320 | } |
| 321 | if t.Failed() { |
| 322 | t.Log(output.String()) |
| 323 | } |
| 324 | }) |
| 325 | var control controlFile |
| 326 | deadline := time.Now().Add(5 * time.Second) |
| 327 | for time.Now().Before(deadline) { |
| 328 | data, err := os.ReadFile(filepath.Join(s.profile, "control.json")) |
| 329 | if err == nil && json.Unmarshal(data, &control) == nil && control.PID == command.Process.Pid { |
| 330 | break |
| 331 | } |
| 332 | select { |
| 333 | case err := <-done: |
| 334 | finished = true |
| 335 | t.Fatalf("storage recovery terminated the production workbench: %v", err) |
| 336 | default: |
| 337 | } |
| 338 | time.Sleep(10 * time.Millisecond) |
| 339 | } |
| 340 | if control.PID != command.Process.Pid { |
| 341 | t.Fatal("pending recovery did not publish a reachable workbench") |
| 342 | } |
| 343 | origin := fmt.Sprintf("http://localhost:%d", control.Port) |
| 344 | base, _ := url.Parse(origin) |
| 345 | jar, _ := cookiejar.New(nil) |
| 346 | jar.SetCookies(base, []*http.Cookie{{Name: cookieName + "_" + base.Port() + "-desktop", Value: trustedViewProof(control.Token), Path: "/"}}) |
| 347 | client := &http.Client{Jar: jar, Timeout: 3 * time.Second} |
| 348 | call := func(method, path, body string, expected int) []byte { |
| 349 | t.Helper() |
| 350 | request, err := http.NewRequestWithContext(ctx, method, origin+path, strings.NewReader(body)) |
| 351 | if err != nil { |
| 352 | t.Fatal(err) |
| 353 | } |
| 354 | request.Header.Set("Origin", origin) |
| 355 | request.Header.Set("Content-Type", "application/json") |
| 356 | response, err := client.Do(request) |
| 357 | if err != nil { |
| 358 | t.Fatal(err) |
| 359 | } |
| 360 | defer response.Body.Close() |
| 361 | data, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) |
| 362 | if err != nil || response.StatusCode != expected { |
| 363 | t.Fatalf("%s %s returned %d %s (%v)", method, path, response.StatusCode, data, err) |
| 364 | } |
| 365 | return data |
| 366 | } |
| 367 | var launch launchResponse |
| 368 | if err := json.Unmarshal(call(http.MethodPost, "/api/launch", fmt.Sprintf(`{"token":%q}`, control.Token), http.StatusOK), &launch); err != nil { |
| 369 | t.Fatal(err) |
| 370 | } |
| 371 | entry, err := url.Parse(launch.URL) |
| 372 | if err != nil || entry.Fragment == "" { |
| 373 | t.Fatal("launcher did not issue a workbench ticket", err) |
| 374 | } |
| 375 | call(http.MethodPost, "/api/session", fmt.Sprintf(`{"token":%q}`, entry.Fragment), http.StatusOK) |
| 376 | call(http.MethodGet, "/api/account", "", http.StatusOK) |
| 377 | call(http.MethodGet, "/api/status", "", http.StatusLocked) |
| 378 | call(http.MethodPost, "/api/account/unlock", `{"password":"synthetic-recovery-password"}`, http.StatusOK) |
| 379 | var status struct { |
| 380 | Ready bool `json:"ready"` |
| 381 | Recovery storageRecoveryView `json:"storage_recovery"` |
| 382 | } |
| 383 | if err := json.Unmarshal(call(http.MethodGet, "/api/status", "", http.StatusOK), &status); err != nil || status.Ready || !status.Recovery.Required || status.Recovery.Error == "" || pending && !strings.Contains(status.Recovery.Error, "Hyper-V") { |
| 384 | t.Fatal("startup did not retain the actual native failure", status, err) |
| 385 | } |
| 386 | call(http.MethodGet, "/api/settings", "", http.StatusOK) |
| 387 | var initialization initializationView |
| 388 | if err := json.Unmarshal(call(http.MethodGet, "/api/environment/initialization", "", http.StatusOK), &initialization); err != nil || initialization.Required { |
| 389 | t.Fatal("old initialization record hid the storage recovery screen", initialization, err) |
| 390 | } |
| 391 | call(http.MethodPost, "/api/start", `{}`, http.StatusConflict) |
| 392 | bundle := call(http.MethodGet, "/api/diagnostics/export", "", http.StatusOK) |
| 393 | if _, err := zip.NewReader(bytes.NewReader(bundle), int64(len(bundle))); err != nil { |
| 394 | t.Fatal("live workbench did not export a valid diagnostic bundle", err) |
| 395 | } |
| 396 | if pending { |
| 397 | if current, err := os.ReadFile(journal); err != nil || !bytes.Equal(current, original) { |
| 398 | t.Fatal("workbench access changed the pending native transaction", err) |
| 399 | } |
| 400 | if _, err := os.Stat(s.environmentDir()); !errors.Is(err, os.ErrNotExist) { |
| 401 | t.Fatal("pending startup wrote environment data", err) |
| 402 | } |
| 403 | } else if current, err := os.ReadFile(s.environmentDir()); err != nil || string(current) != "synthetic occupied workspace path" { |
| 404 | t.Fatal("workspace preparation failure changed the occupied file", err) |
| 405 | } |
| 406 | } |