| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/google/uuid" |
| 15 | "github.com/sylvinus/agent-vm/internal/mobilelink" |
| 16 | "github.com/sylvinus/agent-vm/internal/relay" |
| 17 | "github.com/sylvinus/agent-vm/internal/remotelink" |
| 18 | ) |
| 19 | |
| 20 | func windowsMobileFixture(t *testing.T) (*Server, *mobileRecord, func()) { |
| 21 | t.Helper() |
| 22 | s := windowsCLIRelayFixture(t) |
| 23 | workspace, err := filepath.EvalSymlinks(t.TempDir()) |
| 24 | if err != nil { |
| 25 | t.Fatal(err) |
| 26 | } |
| 27 | if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": workspace}); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | id := uuid.NewString() |
| 31 | if _, err := s.mobileCLI.create(s.profile, workspace, id); err != nil { |
| 32 | t.Fatal(err) |
| 33 | } |
| 34 | record, err := s.mobileCLI.record(s.profile, id) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | record.Terminal = true |
| 39 | record.Connection = uuid.NewString() |
| 40 | record.GuestConfig = `C:\Users\Guest\.claude` |
| 41 | record.GuestWorkspace = `C:\Users\Guest\Cage\Projects\` + strings.Repeat("a", 16) |
| 42 | if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | s.projectShares = map[string]*projectShare{workspace: {windowsProject: &windowsProjectBinding{ID: strings.Repeat("a", 16), Grant: strings.Repeat("b", 64), Path: record.GuestWorkspace}, done: make(chan struct{})}} |
| 46 | room, cancel := context.WithCancel(context.Background()) |
| 47 | t.Cleanup(cancel) |
| 48 | s.phones.record = &phoneRecord{} |
| 49 | s.phones.roomCtx, s.phones.roomProof = room, "current-private-room" |
| 50 | s.ready = true |
| 51 | s.windowsState.Available = true |
| 52 | s.windowsState.ComponentsChecked = time.Now() |
| 53 | s.windowsState.Capabilities = []string{"cli", "terminal", "project-mount"} |
| 54 | s.windowsState.Components = map[string]windowsComponentState{"cli": {Installed: true, Ready: true}, "terminal": {Installed: true, Ready: true}, "project-mount": {Installed: true, Ready: true}} |
| 55 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_MOBILE", "1") |
| 56 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_WORKSPACE", record.GuestWorkspace) |
| 57 | return s, record, cancel |
| 58 | } |
| 59 | |
| 60 | func windowsPhoneRequest(t *testing.T, s *Server, method, path, body, proof string) *httptest.ResponseRecorder { |
| 61 | t.Helper() |
| 62 | r := httptest.NewRequest(method, s.origin+path, strings.NewReader(body)) |
| 63 | r.Header.Set("Origin", s.origin) |
| 64 | r.Header.Set("Content-Type", "application/json") |
| 65 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 66 | if proof != "" { |
| 67 | r.Header.Set(mobilelink.PhoneRoomHeader, proof) |
| 68 | } |
| 69 | w := httptest.NewRecorder() |
| 70 | s.handler().ServeHTTP(w, r) |
| 71 | return w |
| 72 | } |
| 73 | |
| 74 | func TestWindowsMobileHandlerRequiresCurrentRoomAndOrdinaryAccountUnlock(t *testing.T) { |
| 75 | s, record, cancel := windowsMobileFixture(t) |
| 76 | path := "/api/mobile/cli/sessions/" + record.ID |
| 77 | for _, proof := range []string{"", "old-private-room"} { |
| 78 | if w := windowsPhoneRequest(t, s, "GET", path, "", proof); w.Code != http.StatusForbidden { |
| 79 | t.Fatalf("untrusted room admitted: %d", w.Code) |
| 80 | } |
| 81 | } |
| 82 | if w := windowsPhoneRequest(t, s, "GET", path, "", s.phones.roomProof); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"can_send":true`) { |
| 83 | t.Fatalf("actual native dispatch failed: %d %s", w.Code, w.Body.String()) |
| 84 | } |
| 85 | s.account.trustedSession = true |
| 86 | if w := windowsPhoneRequest(t, s, "GET", path, "", s.phones.roomProof); w.Code != http.StatusLocked { |
| 87 | t.Fatalf("phone gained desktop-only unlock: %d", w.Code) |
| 88 | } |
| 89 | s.account.trustedSession = false |
| 90 | cancel() |
| 91 | if w := windowsPhoneRequest(t, s, "GET", path, "", s.phones.roomProof); w.Code != http.StatusForbidden { |
| 92 | t.Fatalf("revoked room admitted: %d", w.Code) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | func TestWindowsMobileProjectsReflectInstalledNativeHandlers(t *testing.T) { |
| 97 | s, _, _ := windowsMobileFixture(t) |
| 98 | for _, installed := range []bool{true, false} { |
| 99 | if !installed { |
| 100 | s.windowsState.Capabilities = nil |
| 101 | } |
| 102 | w := windowsPhoneRequest(t, s, "GET", "/api/mobile/cli/projects", "", s.phones.roomProof) |
| 103 | var state struct { |
| 104 | Shared bool `json:"shared_sessions"` |
| 105 | } |
| 106 | if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &state) != nil || state.Shared != installed { |
| 107 | t.Fatalf("native capability reporting: %d", w.Code) |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | func TestWindowsMobilePurgeUsesLiveHostGrantInsteadOfHostGuestPath(t *testing.T) { |
| 113 | s, record, _ := windowsMobileFixture(t) |
| 114 | record.Archived = true |
| 115 | if err := writePrivate(mobileRecordPath(s.profile, record.ID), record); err != nil { |
| 116 | t.Fatal(err) |
| 117 | } |
| 118 | capture := filepath.Join(t.TempDir(), "purge-relay.jsonl") |
| 119 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_CAPTURE", capture) |
| 120 | w := windowsPhoneRequest(t, s, "POST", "/api/mobile/cli/sessions/"+record.ID+"/purge", `{"confirm":true}`, s.phones.roomProof) |
| 121 | if w.Code != http.StatusOK { |
| 122 | t.Fatalf("native purge dispatch: %d %s", w.Code, w.Body.String()) |
| 123 | } |
| 124 | data, err := os.ReadFile(capture) |
| 125 | if err != nil || !strings.Contains(string(data), `"mode":"purge"`) { |
| 126 | t.Fatal("purge did not reach fixed native relay") |
| 127 | } |
| 128 | stored, err := s.mobileCLI.record(s.profile, record.ID) |
| 129 | if err != nil || !stored.Purged { |
| 130 | t.Fatal("confirmed native purge did not persist its tombstone") |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func TestWindowsMobileHandlerUsesHostRecordGrantAndRejectsPhoneGuestPaths(t *testing.T) { |
| 135 | s, record, _ := windowsMobileFixture(t) |
| 136 | capture := filepath.Join(t.TempDir(), "native-requests.jsonl") |
| 137 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_CAPTURE", capture) |
| 138 | requestID := uuid.NewString() |
| 139 | path := "/api/mobile/cli/sessions/" + record.ID + "/messages" |
| 140 | body := `{"request_id":"` + requestID + `","text":"中文 fixture"}` |
| 141 | w := windowsPhoneRequest(t, s, "POST", path, body, s.phones.roomProof) |
| 142 | if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"acknowledged_request_id":"`+requestID+`"`) { |
| 143 | t.Fatalf("native receipt failed: %d %s", w.Code, w.Body.String()) |
| 144 | } |
| 145 | data, err := os.ReadFile(capture) |
| 146 | if err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | if !strings.Contains(string(data), `"mode":"rpc"`) || !strings.Contains(string(data), strings.Repeat("b", 64)) { |
| 150 | t.Fatal("real relay child did not receive host grant") |
| 151 | } |
| 152 | if strings.Contains(w.Body.String(), record.GuestWorkspace) || strings.Contains(w.Body.String(), strings.Repeat("b", 64)) { |
| 153 | t.Fatal("native path/grant leaked to phone") |
| 154 | } |
| 155 | guestBody, _ := json.Marshal(map[string]any{"id": uuid.NewString(), "workspace": record.GuestWorkspace}) |
| 156 | if w := windowsPhoneRequest(t, s, "POST", "/api/mobile/cli/sessions", string(guestBody), s.phones.roomProof); w.Code != http.StatusForbidden { |
| 157 | t.Fatalf("phone selected guest directory: %d", w.Code) |
| 158 | } |
| 159 | other, err := s.mobileCLI.create(s.profile, t.TempDir(), uuid.NewString()) |
| 160 | if err != nil { |
| 161 | t.Fatal(err) |
| 162 | } |
| 163 | if w := windowsPhoneRequest(t, s, "GET", "/api/mobile/cli/sessions/"+other.ID, "", s.phones.roomProof); w.Code != http.StatusForbidden { |
| 164 | t.Fatalf("ungranted project history exposed: %d", w.Code) |
| 165 | } |
| 166 | close(s.projectShares[record.Workspace].done) |
| 167 | if w := windowsPhoneRequest(t, s, "GET", "/api/mobile/cli/sessions/"+record.ID, "", s.phones.roomProof); w.Code == http.StatusOK { |
| 168 | t.Fatal("revoked project reached native view") |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | func TestWindowsLegacyMobileLaunchPreservesHistoryWithoutLinuxFallback(t *testing.T) { |
| 173 | s, record, _ := windowsMobileFixture(t) |
| 174 | record.Terminal = false |
| 175 | record.Resume = true |
| 176 | record.Turns = []mobileTurn{{ID: uuid.NewString(), Prompt: "kept history", Text: "kept answer"}} |
| 177 | if err := writePrivate(mobileRecordPath(s.profile, record.ID), record); err != nil { |
| 178 | t.Fatal(err) |
| 179 | } |
| 180 | if _, _, _, err := s.prepareMobileLaunch(record); err != errWindowsLegacyMobile { |
| 181 | t.Fatalf("legacy Windows fallback: %v", err) |
| 182 | } |
| 183 | w := windowsPhoneRequest(t, s, "POST", "/api/mobile/cli/sessions/"+record.ID+"/open", `{"automatic":true}`, s.phones.roomProof) |
| 184 | if w.Code != http.StatusConflict { |
| 185 | t.Fatalf("legacy Linux record executed: %d", w.Code) |
| 186 | } |
| 187 | data, err := os.ReadFile(mobileRecordPath(s.profile, record.ID)) |
| 188 | if err != nil || !strings.Contains(string(data), "kept answer") { |
| 189 | t.Fatal("legacy history changed") |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | func TestWindowsMobileRoomRevocationCancelsInFlightNativeRequest(t *testing.T) { |
| 194 | s, record, cancel := windowsMobileFixture(t) |
| 195 | marker := filepath.Join(t.TempDir(), "native-started") |
| 196 | t.Setenv("CAGE_WINDOWS_CLI_RELAY_BLOCK", marker) |
| 197 | done := make(chan *httptest.ResponseRecorder, 1) |
| 198 | go func() { |
| 199 | done <- windowsPhoneRequest(t, s, "GET", "/api/mobile/cli/sessions/"+record.ID, "", s.phones.roomProof) |
| 200 | }() |
| 201 | deadline := time.Now().Add(3 * time.Second) |
| 202 | for { |
| 203 | if _, err := os.Stat(marker); err == nil { |
| 204 | break |
| 205 | } |
| 206 | if time.Now().After(deadline) { |
| 207 | t.Fatal("native relay child did not start") |
| 208 | } |
| 209 | time.Sleep(10 * time.Millisecond) |
| 210 | } |
| 211 | cancel() |
| 212 | select { |
| 213 | case result := <-done: |
| 214 | if result.Code == http.StatusOK { |
| 215 | t.Fatal("revoked native read succeeded") |
| 216 | } |
| 217 | case <-time.After(3 * time.Second): |
| 218 | t.Fatal("phone revocation left native request running") |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | func TestWindowsMobileMediaMapsOnlyCurrentLiveProject(t *testing.T) { |
| 223 | s, record, _ := windowsMobileFixture(t) |
| 224 | guestRoot := record.GuestWorkspace |
| 225 | record.GuestWorkspace += `\nested` |
| 226 | record.Turns = []mobileTurn{{ID: uuid.NewString(), Text: ` ` + guestRoot + `\nested\frame.png ../outside.png`}} |
| 227 | if err := writePrivate(mobileRecordPath(s.profile, record.ID), record); err != nil { |
| 228 | t.Fatal(err) |
| 229 | } |
| 230 | if err := os.Mkdir(filepath.Join(record.Workspace, "nested"), 0700); err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | content := append([]byte("\x89PNG\r\n\x1a\n"), make([]byte, 16)...) |
| 234 | if err := os.WriteFile(filepath.Join(record.Workspace, "nested", "frame.png"), content, 0600); err != nil { |
| 235 | t.Fatal(err) |
| 236 | } |
| 237 | for _, reference := range []string{"frame.png", guestRoot + `\nested\frame.png`} { |
| 238 | body, _ := json.Marshal(mediaChunkRequest{Reference: reference}) |
| 239 | w := windowsPhoneRequest(t, s, "POST", "/api/mobile/cli/sessions/"+record.ID+"/media", string(body), s.phones.roomProof) |
| 240 | if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"mime":"image/png"`) { |
| 241 | t.Fatalf("native media path: %d %s", w.Code, w.Body.String()) |
| 242 | } |
| 243 | } |
| 244 | for _, reference := range []string{`C:\outside\frame.png`, `..\..\outside.png`, `\\server\share\frame.png`, `C:frame.png`, guestRoot + `\frame.png:stream`} { |
| 245 | if _, err := windowsMediaFileName(guestRoot, record.GuestWorkspace, reference); err == nil { |
| 246 | t.Fatal("guest media escaped project") |
| 247 | } |
| 248 | } |
| 249 | close(s.projectShares[record.Workspace].done) |
| 250 | body, _ := json.Marshal(mediaChunkRequest{Reference: "frame.png"}) |
| 251 | if w := windowsPhoneRequest(t, s, "POST", "/api/mobile/cli/sessions/"+record.ID+"/media", string(body), s.phones.roomProof); w.Code != http.StatusConflict { |
| 252 | t.Fatalf("revoked media mount accepted: %d", w.Code) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | func TestWindowsMobileRealPairingTransportReachesNativeSession(t *testing.T) { |
| 257 | s, record, cancelOld := windowsMobileFixture(t) |
| 258 | cancelOld() |
| 259 | s.phones.record = nil |
| 260 | s.phones.roomCtx = nil |
| 261 | s.phones.roomProof = "" |
| 262 | client, ctx := pairedWindowsPhoneForTest(t, s) |
| 263 | reply, err := client.Do(ctx, "GET", "/api/mobile/cli/sessions/"+record.ID, nil) |
| 264 | if err != nil || reply.Status != http.StatusOK || !strings.Contains(string(reply.Body), `"can_send":true`) { |
| 265 | t.Fatalf("encrypted phone/native session: %v %#v", err, reply) |
| 266 | } |
| 267 | s.phones.mu.Lock() |
| 268 | privateProof := s.phones.roomProof |
| 269 | s.phones.mu.Unlock() |
| 270 | if strings.Contains(string(reply.Body), record.GuestWorkspace) || strings.Contains(string(reply.Body), privateProof) { |
| 271 | t.Fatal("private backend capability reached phone") |
| 272 | } |
| 273 | if w := windowsBrowserRequestForTest(s, "DELETE", "/api/mobile-pair", []byte(`{}`)); w.Code != http.StatusOK { |
| 274 | t.Fatalf("pair removal: %d", w.Code) |
| 275 | } |
| 276 | if reply, err := client.Do(ctx, "GET", "/api/mobile/cli/sessions/"+record.ID, nil); err == nil && reply.Status == http.StatusOK { |
| 277 | t.Fatal("revoked encrypted phone kept session access") |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | func pairedWindowsPhoneForTest(t *testing.T, s *Server) (*mobilelink.Client, context.Context) { |
| 282 | t.Helper() |
| 283 | edge, err := relay.New(relay.Config{PublicRooms: true, AdminToken: strings.Repeat("x", 32)}) |
| 284 | if err != nil { |
| 285 | t.Fatal(err) |
| 286 | } |
| 287 | relayHTTP := httptest.NewServer(edge) |
| 288 | t.Cleanup(func() { edge.Close(); relayHTTP.Close() }) |
| 289 | server := httptest.NewUnstartedServer(s.handler()) |
| 290 | s.origin = "http://" + server.Listener.Addr().String() |
| 291 | server.Start() |
| 292 | t.Cleanup(server.Close) |
| 293 | t.Cleanup(s.stopPhone) |
| 294 | s.preferences.MobileRelay = relayHTTP.URL |
| 295 | response := windowsBrowserRequestForTest(s, "POST", "/api/mobile-pair", []byte(`{}`)) |
| 296 | var invitation struct{ Manual string } |
| 297 | if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &invitation) != nil { |
| 298 | t.Fatalf("actual pairing route: %d", response.Code) |
| 299 | } |
| 300 | phone, err := remotelink.NewIdentity() |
| 301 | if err != nil { |
| 302 | t.Fatal(err) |
| 303 | } |
| 304 | ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) |
| 305 | t.Cleanup(cancel) |
| 306 | encoded, err := mobilelink.RedeemPair(ctx, invitation.Manual, relayHTTP.URL, phone.Pin) |
| 307 | if err != nil { |
| 308 | t.Fatal(err) |
| 309 | } |
| 310 | var pairing mobilelink.PairedHost |
| 311 | if json.Unmarshal([]byte(encoded), &pairing) != nil { |
| 312 | t.Fatal("pairing decode") |
| 313 | } |
| 314 | var client *mobilelink.Client |
| 315 | for ctx.Err() == nil { |
| 316 | room, err := mobilelink.LookupRoom(ctx, relayHTTP.URL, pairing.Lookup) |
| 317 | if err == nil { |
| 318 | client, err = mobilelink.ConnectClient(ctx, relayHTTP.URL, room.ID, room.ClientToken, phone, pairing.HostPin) |
| 319 | if err != nil { |
| 320 | t.Fatal(err) |
| 321 | } |
| 322 | break |
| 323 | } |
| 324 | time.Sleep(10 * time.Millisecond) |
| 325 | } |
| 326 | if client == nil { |
| 327 | t.Fatal("paired room did not start") |
| 328 | } |
| 329 | t.Cleanup(func() { _ = client.Close() }) |
| 330 | return client, ctx |
| 331 | } |