| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "slices" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | |
| 15 | "github.com/google/uuid" |
| 16 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 17 | ) |
| 18 | |
| 19 | func removeProjectRequest(t *testing.T, s *Server, path string, want int) { |
| 20 | t.Helper() |
| 21 | body, _ := json.Marshal(map[string]string{"workspace": path}) |
| 22 | response := windowsBrowserRequestForTest(s, "POST", "/api/projects/remove", body) |
| 23 | if response.Code != want { |
| 24 | t.Fatalf("remove status=%d want=%d body=%s", response.Code, want, response.Body.String()) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | func TestProjectRemovalPersistsRevocationAcrossGuests(t *testing.T) { |
| 29 | for _, system := range []string{"linux", "macos", "windows"} { |
| 30 | t.Run(system, func(t *testing.T) { |
| 31 | s := testServer(t) |
| 32 | if system == "macos" { |
| 33 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"} |
| 34 | } |
| 35 | if system == "windows" { |
| 36 | s.windowsGuest = &guestos.WindowsProfile{} |
| 37 | } |
| 38 | root, _ := filepath.EvalSymlinks(t.TempDir()) |
| 39 | other, _ := filepath.EvalSymlinks(t.TempDir()) |
| 40 | file := filepath.Join(root, "keep.txt") |
| 41 | if err := os.WriteFile(file, []byte("keep project data"), 0600); err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | s.preferences = Preferences{Workspace: root, Keyboard: "native", AutoLanguage: true} |
| 45 | before := s.preferences |
| 46 | for _, path := range []string{root, other} { |
| 47 | if err := s.rememberSharedProject(path); err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | } |
| 51 | id := uuid.NewString() |
| 52 | record := &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{ID: id, Workspace: root, Title: "saved history"}, Turns: []mobileTurn{}}} |
| 53 | if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | history, _ := os.ReadFile(mobileRecordPath(s.profile, id)) |
| 57 | detached := 0 |
| 58 | done := make(chan struct{}) |
| 59 | close(done) |
| 60 | share := &projectShare{done: done, detach: func() { detached++ }} |
| 61 | s.projectShares = map[string]*projectShare{root: share, other: {}} |
| 62 | s.projectErrors = []projectShareError{{Path: root, Message: "old failure"}, {Path: other, Message: "keep failure"}} |
| 63 | s.terminals.sessions = map[string]*terminalSession{"other": {id: "other", workspace: other}} |
| 64 | s.mobileCLI.running = map[string]bool{id: true} |
| 65 | s.mobileCLI.catalog = map[string]mobileSummary{id: {ID: id, Workspace: root}} |
| 66 | removeProjectRequest(t, s, root, 200) |
| 67 | if detached != 1 || s.projectShares[root] != nil || s.projectShares[other] == nil { |
| 68 | t.Fatal("wrong share was detached") |
| 69 | } |
| 70 | if s.terminals.sessions["other"].closed || len(s.projectErrors) != 1 || s.projectErrors[0].Path != other { |
| 71 | t.Fatal("unrelated project was changed") |
| 72 | } |
| 73 | before.Workspace = s.environmentDir() |
| 74 | if s.preferences != before { |
| 75 | t.Fatal("preferences changed beyond current project") |
| 76 | } |
| 77 | saved, err := os.ReadFile(filepath.Join(s.profile, "workbench.json")) |
| 78 | var prefs Preferences |
| 79 | if err != nil || json.Unmarshal(saved, &prefs) != nil || prefs != before { |
| 80 | t.Fatal("current project was not persisted", err) |
| 81 | } |
| 82 | reloaded := &Server{profile: s.profile, preferences: prefs} |
| 83 | paths, err := reloaded.projectPaths() |
| 84 | if err != nil || slices.Contains(paths, root) || !slices.Contains(paths, other) { |
| 85 | t.Fatal("revoked project returned after restart", paths, err) |
| 86 | } |
| 87 | if _, err := s.projectWorkspace(root); err == nil { |
| 88 | t.Fatal("removed grant still authorizes new work") |
| 89 | } |
| 90 | content, _ := os.ReadFile(file) |
| 91 | afterHistory, _ := os.ReadFile(mobileRecordPath(s.profile, id)) |
| 92 | if string(content) != "keep project data" || string(afterHistory) != string(history) { |
| 93 | t.Fatal("project files or history changed") |
| 94 | } |
| 95 | removeProjectRequest(t, s, root, 200) |
| 96 | if detached != 1 { |
| 97 | t.Fatal("retry detached twice") |
| 98 | } |
| 99 | if err := s.rememberSharedProject(root); err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | sessions, err := s.mobileCLI.summaries(s.profile, map[string]bool{root: true}, false) |
| 103 | if err != nil || len(sessions) != 1 { |
| 104 | t.Fatal("re-adding lost history", err) |
| 105 | } |
| 106 | }) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | func TestProjectRemovalRejectsActiveUsersAndUntrustedRequests(t *testing.T) { |
| 111 | for _, kind := range []string{"terminal", "mobile", "observed-cli", "editor", "browser-failure", "operation", "job", "closing", "locked", "origin", "unauthenticated"} { |
| 112 | t.Run(kind, func(t *testing.T) { |
| 113 | s := testServer(t) |
| 114 | root, _ := filepath.EvalSymlinks(t.TempDir()) |
| 115 | if err := s.rememberSharedProject(root); err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | s.projectShares = map[string]*projectShare{root: {}} |
| 119 | want := 409 |
| 120 | switch kind { |
| 121 | case "terminal": |
| 122 | s.terminals.sessions = map[string]*terminalSession{"live": {workspace: root}} |
| 123 | case "mobile": |
| 124 | s.mobileCLI.active = map[string]*mobileRun{"live": {record: &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: root}}}}} |
| 125 | case "observed-cli": |
| 126 | s.ready = true |
| 127 | s.preferences.ClaudeTerminalCommand = "custom-shell" |
| 128 | s.mobileCLI.running = map[string]bool{"live": true} |
| 129 | s.mobileCLI.catalog = map[string]mobileSummary{"live": {Workspace: root}} |
| 130 | case "editor", "browser-failure": |
| 131 | s.ready = true |
| 132 | s.preferences.ClaudeTerminalCommand = "custom-shell" |
| 133 | s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { |
| 134 | if r.URL.Path != "/tabs" { |
| 135 | t.Fatal("unexpected browser operation", r.URL.Path) |
| 136 | } |
| 137 | body, _ := json.Marshal(map[string]any{"tabs": []map[string]string{{"kind": "editor", "workspace": root}}}) |
| 138 | status := 200 |
| 139 | if kind == "browser-failure" { |
| 140 | status = 503 |
| 141 | } |
| 142 | return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(string(body))), Header: http.Header{}}, nil |
| 143 | })) |
| 144 | case "operation": |
| 145 | s.op.Lock() |
| 146 | defer s.op.Unlock() |
| 147 | case "job": |
| 148 | s.setJobForTest(Job{Running: true}) |
| 149 | case "closing": |
| 150 | s.closing = true |
| 151 | want = 503 |
| 152 | case "locked": |
| 153 | s.account.lock() |
| 154 | want = 423 |
| 155 | case "origin", "unauthenticated": |
| 156 | origin, auth := s.origin, true |
| 157 | if kind == "origin" { |
| 158 | origin, want = "https://example.com", 403 |
| 159 | } else { |
| 160 | auth, want = false, 401 |
| 161 | } |
| 162 | body, _ := json.Marshal(map[string]string{"workspace": root}) |
| 163 | response := request(s, "POST", "/api/projects/remove", origin, string(body), auth) |
| 164 | if response.Code != want { |
| 165 | t.Fatal(response.Code, response.Body.String()) |
| 166 | } |
| 167 | } |
| 168 | if kind != "origin" && kind != "unauthenticated" { |
| 169 | removeProjectRequest(t, s, root, want) |
| 170 | } |
| 171 | paths, err := s.projectPaths() |
| 172 | if err != nil || !slices.Contains(paths, root) || s.projectShares[root] == nil { |
| 173 | t.Fatal("rejected removal changed authorization") |
| 174 | } |
| 175 | }) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | func TestProjectRemovalHandlesMissingDirectoriesAndLegacySelection(t *testing.T) { |
| 180 | for _, legacy := range []bool{false, true} { |
| 181 | t.Run(map[bool]string{false: "saved", true: "legacy-current"}[legacy], func(t *testing.T) { |
| 182 | s := testServer(t) |
| 183 | path := filepath.Join(t.TempDir(), "directory-already-moved") |
| 184 | if legacy { |
| 185 | s.preferences.Workspace = path |
| 186 | } else if err := s.rememberSharedProject(path); err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | removeProjectRequest(t, s, path, 200) |
| 190 | paths, err := s.projectPaths() |
| 191 | if err != nil || slices.Contains(paths, path) { |
| 192 | t.Fatal("missing directory could not be removed", err) |
| 193 | } |
| 194 | }) |
| 195 | } |
| 196 | s := testServer(t) |
| 197 | removeProjectRequest(t, s, s.environmentDir(), 400) |
| 198 | removeProjectRequest(t, s, "", 400) |
| 199 | } |
| 200 | |
| 201 | func TestProjectRemovalPreservesGrantWhenPreferencesWriteFails(t *testing.T) { |
| 202 | s := testServer(t) |
| 203 | root, _ := filepath.EvalSymlinks(t.TempDir()) |
| 204 | s.preferences.Workspace = root |
| 205 | s.projectShares = map[string]*projectShare{root: {}} |
| 206 | if err := os.Mkdir(filepath.Join(s.profile, "workbench.json"), 0700); err != nil { |
| 207 | t.Fatal(err) |
| 208 | } |
| 209 | removeProjectRequest(t, s, root, 400) |
| 210 | paths, err := s.projectPaths() |
| 211 | if err != nil || !slices.Contains(paths, root) || s.preferences.Workspace != root || s.projectShares[root] == nil { |
| 212 | t.Fatal("write failure revoked the current project") |
| 213 | } |
| 214 | if err := os.Remove(filepath.Join(s.profile, "workbench.json")); err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | removeProjectRequest(t, s, root, 200) |
| 218 | } |
| 219 | |
| 220 | func TestProjectRemovalRejectsDisconnectedOrUnknownVM(t *testing.T) { |
| 221 | for _, malformed := range []bool{false, true} { |
| 222 | s := testServer(t) |
| 223 | project := t.TempDir() |
| 224 | if err := s.rememberSharedProject(project); err != nil { |
| 225 | t.Fatal(err) |
| 226 | } |
| 227 | record := filepath.Join(s.profile, "state", "lima", "guest", "cage-running.json") |
| 228 | value := any(map[string]int{"pid": os.Getpid()}) |
| 229 | if malformed { |
| 230 | value = map[string]string{"pid": "invalid"} |
| 231 | } |
| 232 | if err := writePrivate(record, value); err != nil { |
| 233 | t.Fatal(err) |
| 234 | } |
| 235 | removeProjectRequest(t, s, project, 409) |
| 236 | paths, err := s.projectPaths() |
| 237 | if err != nil || !slices.Contains(paths, project) { |
| 238 | t.Fatal("disconnected VM lost authorization") |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | func TestAgentProjectRemovalUsesSharedOwner(t *testing.T) { |
| 244 | s := agentTestController(t) |
| 245 | path := t.TempDir() |
| 246 | if err := s.rememberSharedProject(path); err != nil { |
| 247 | t.Fatal(err) |
| 248 | } |
| 249 | input, _ := json.Marshal(map[string]string{"workspace": path}) |
| 250 | if _, err := AgentCall(t.Context(), s.configPath, "project.remove", input); err != nil { |
| 251 | t.Fatal(err) |
| 252 | } |
| 253 | paths, err := s.projectPaths() |
| 254 | if err != nil || slices.Contains(paths, path) { |
| 255 | t.Fatal("agent removal did not revoke grant", err) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func TestProjectRemovalRejectsRestoredMacOSEditor(t *testing.T) { |
| 260 | s := testServer(t) |
| 261 | root, _ := filepath.EvalSymlinks(t.TempDir()) |
| 262 | s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guestdev"} |
| 263 | s.ready = true |
| 264 | s.preferences.ClaudeTerminalCommand = "custom-shell" |
| 265 | if err := s.rememberSharedProject(root); err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | client := fixtureWindowsBrowserClient(t) |
| 269 | start := client.start |
| 270 | client.start = func(ctx context.Context) (*exec.Cmd, error) { |
| 271 | command, err := start(ctx) |
| 272 | if err == nil { |
| 273 | command.Env = append(command.Env, "CAGE_BROWSER_EDITOR_WORKSPACE="+filepath.Base(macOSProjectPath(s.macosGuest.User, root))) |
| 274 | } |
| 275 | return command, err |
| 276 | } |
| 277 | s.windowsBrowserControl = client |
| 278 | body, err := s.browserAction(t.Context(), "tabs", nil) |
| 279 | var state struct { |
| 280 | Tabs []struct { |
| 281 | Workspace string `json:"workspace"` |
| 282 | } `json:"tabs"` |
| 283 | } |
| 284 | if err != nil || json.Unmarshal(body, &state) != nil || len(state.Tabs) != 1 || state.Tabs[0].Workspace != root { |
| 285 | t.Fatal("restored editor lost host workspace", string(body), err) |
| 286 | } |
| 287 | removeProjectRequest(t, s, root, 409) |
| 288 | } |