| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "strings" |
| 11 | "sync/atomic" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "github.com/google/uuid" |
| 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | "github.com/sylvinus/agent-vm/internal/mobilelink" |
| 18 | ) |
| 19 | |
| 20 | func pairedHostRequest(s *Server, method, path, body string) *httptest.ResponseRecorder { |
| 21 | r := httptest.NewRequest(method, s.origin+path, strings.NewReader(body)) |
| 22 | r.Header.Set("Origin", s.origin) |
| 23 | r.Header.Set("Content-Type", "application/json") |
| 24 | r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) |
| 25 | w := httptest.NewRecorder() |
| 26 | s.handler().ServeHTTP(w, r) |
| 27 | return w |
| 28 | } |
| 29 | |
| 30 | |
| 31 | |
| 32 | func testPairedBrowser(t *testing.T, ctx context.Context, s *Server, phone *mobilelink.Client, gate *cage.EgressGate) { |
| 33 | t.Helper() |
| 34 | s.phones.mu.Lock() |
| 35 | profile := s.phones.peerLocked() |
| 36 | s.phones.mu.Unlock() |
| 37 | if len(profile) != 64 { |
| 38 | t.Fatal("missing enrollment profile") |
| 39 | } |
| 40 | const customHome = "https://example.com/start?source=desktop" |
| 41 | const blockedHome = "http://127.0.0.1/private" |
| 42 | openedURLs := make(chan string, 6) |
| 43 | const frameTag = "b542cd94286a2489bc2df1241b043c76" |
| 44 | var opens, desktopFrames atomic.Int32 |
| 45 | var desktopVisible atomic.Bool |
| 46 | s.desktopDisplayUpdate = func(show bool) error { desktopVisible.Store(show); return nil } |
| 47 | var slowFrame, desktopDensity atomic.Bool |
| 48 | var desktopOpenStatus, desktopFrameStatus atomic.Int32 |
| 49 | receiving := make(chan struct{}) |
| 50 | id := uuid.NewString() |
| 51 | s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { |
| 52 | var input phoneSurfaceInput |
| 53 | if err := json.NewDecoder(r.Body).Decode(&input); err != nil { |
| 54 | t.Error(err) |
| 55 | } |
| 56 | if input.ID != id { |
| 57 | t.Error("unexpected guest target") |
| 58 | } |
| 59 | body := fmt.Sprintf(`{"id":%q}`, id) |
| 60 | switch r.URL.Path { |
| 61 | case "/phone-browser/open": |
| 62 | openedURLs <- input.URL |
| 63 | if input.URL == blockedHome { |
| 64 | return &http.Response{StatusCode: 403, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("{}"))}, nil |
| 65 | } |
| 66 | if input.Profile != profile || input.Width != 390 || input.Height != 640 { |
| 67 | t.Error("isolated profile or viewport not forwarded") |
| 68 | } |
| 69 | opens.Add(1) |
| 70 | case "/phone-browser/frame": |
| 71 | if input.After == frameTag { |
| 72 | body = fmt.Sprintf(`{"id":%q,"frame_tag":%q,"unchanged":true}`, id, frameTag) |
| 73 | break |
| 74 | } |
| 75 | if slowFrame.Load() { |
| 76 | close(receiving) |
| 77 | <-r.Context().Done() |
| 78 | return nil, r.Context().Err() |
| 79 | } |
| 80 | body = fmt.Sprintf(`{"id":%q,"document":"test","image":"dGVzdA==","width":390,"height":640}`, id) |
| 81 | case "/phone-browser/action": |
| 82 | if input.ReturnFrame { |
| 83 | body = fmt.Sprintf(`{"id":%q,"frame_tag":%q,"image":%q}`, id, frameTag, strings.Repeat("A", 8192)) |
| 84 | } |
| 85 | if input.Type != "tap" || input.Document != "test" || input.X == nil || *input.X != 0 { |
| 86 | t.Error("tap not bound to frame or zero coordinate discarded") |
| 87 | } |
| 88 | case "/phone-browser/close": |
| 89 | case "/phone-desktop/open": |
| 90 | if !desktopVisible.Load() { |
| 91 | t.Error("phone opened before its display lease restored the window") |
| 92 | } |
| 93 | if status := desktopOpenStatus.Load(); status != 0 { |
| 94 | return &http.Response{StatusCode: int(status), Header: make(http.Header), Body: io.NopCloser(strings.NewReader(""))}, nil |
| 95 | } |
| 96 | if input.Profile != "" || input.Width != 390 || input.URL != "" { |
| 97 | t.Error("desktop launch scope or geometry lost") |
| 98 | } |
| 99 | case "/phone-desktop/frame": |
| 100 | if status := desktopFrameStatus.Load(); status != 0 { |
| 101 | return &http.Response{StatusCode: int(status), Header: make(http.Header), Body: io.NopCloser(strings.NewReader(""))}, nil |
| 102 | } |
| 103 | if desktopFrames.Add(1) == 1 { |
| 104 | return &http.Response{StatusCode: 409, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(""))}, nil |
| 105 | } |
| 106 | body = fmt.Sprintf(`{"id":%q,"document":"test","window":"desktop","image":"ZGVza3RvcA==","width":390,"height":640}`, id) |
| 107 | if desktopDensity.Load() { |
| 108 | body = strings.TrimSuffix(body, "}") + `,"pixel_ratio_control":true,"pixel_ratio":3.5,"requested_pixel_ratio":3.5}` |
| 109 | } |
| 110 | case "/phone-desktop/action": |
| 111 | if input.Type == "resize" && input.PixelRatio == 3.5 && input.Width == 390 && input.Height == 640 { |
| 112 | break |
| 113 | } |
| 114 | if input.Type != "login" || input.Document != "test" { |
| 115 | t.Error("wrong desktop window selection") |
| 116 | } |
| 117 | case "/phone-desktop/close": |
| 118 | default: |
| 119 | t.Errorf("unexpected guest route %s", r.URL.Path) |
| 120 | } |
| 121 | return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil |
| 122 | })) |
| 123 | operation := func(surface, method, path, body string, want int) string { |
| 124 | t.Helper() |
| 125 | reply, err := phone.Do(ctx, method, "/api/mobile/"+surface+"/"+path, []byte(body)) |
| 126 | if err != nil { |
| 127 | t.Fatal(err) |
| 128 | } |
| 129 | if reply.Status != want { |
| 130 | t.Fatalf("phone %s: got HTTP %d, want %d (%s)", path, reply.Status, want, reply.Body) |
| 131 | } |
| 132 | return string(reply.Body) |
| 133 | } |
| 134 | do := func(method, path, body string, want int) string { |
| 135 | t.Helper() |
| 136 | return operation("browser", method, path, body, want) |
| 137 | } |
| 138 | screen := func(method, path, body string, want int) string { |
| 139 | t.Helper() |
| 140 | return operation("desktop", method, path, body, want) |
| 141 | } |
| 142 | open := fmt.Sprintf(`{"id":%q,"width":390,"height":640}`, id) |
| 143 | if pairedHostRequest(s, "POST", "/api/mobile/desktop/open", open).Code != 403 { |
| 144 | t.Fatal("unscoped transport could access desktop") |
| 145 | } |
| 146 | screen("POST", "open", strings.Replace(open, `"width"`, `"url":"https://example.test","width"`, 1), 400) |
| 147 | screen("POST", "open", open, 200) |
| 148 | screen("GET", id+"/frame", "", 425) |
| 149 | if !strings.Contains(screen("GET", id+"/frame", "", 200), "ZGVza3RvcA==") { |
| 150 | t.Fatal("wrong guest display") |
| 151 | } |
| 152 | |
| 153 | |
| 154 | s.phones.desktop.op.Lock() |
| 155 | s.phones.desktop.session.startJob = "shared-desktop-start" |
| 156 | s.phones.desktop.session.openInput = phoneSurfaceInput{ID: id, Width: 390, Height: 640} |
| 157 | s.phones.desktop.session.readyUntil = time.Now().Add(time.Minute) |
| 158 | s.phones.desktop.op.Unlock() |
| 159 | s.setJobForTest(Job{ID: "shared-desktop-start", Running: true}) |
| 160 | screen("GET", id+"/frame", "", 425) |
| 161 | s.setJobForTest(Job{ID: "shared-desktop-start"}) |
| 162 | |
| 163 | desktopOpenStatus.Store(412) |
| 164 | screen("GET", id+"/frame", "", 425) |
| 165 | desktopOpenStatus.Store(503) |
| 166 | screen("GET", id+"/frame", "", 425) |
| 167 | desktopOpenStatus.Store(0) |
| 168 | desktopFrameStatus.Store(503) |
| 169 | screen("GET", id+"/frame", "", 425) |
| 170 | desktopFrameStatus.Store(0) |
| 171 | screen("GET", id+"/frame", "", 200) |
| 172 | |
| 173 | desktopFrameStatus.Store(503) |
| 174 | screen("GET", id+"/frame", "", 502) |
| 175 | desktopFrameStatus.Store(0) |
| 176 | screen("POST", id+"/action", `{"type":"navigate","url":"https://example.test"}`, 400) |
| 177 | screen("POST", id+"/action", `{"type":"login","document":"test"}`, 200) |
| 178 | desktopDensity.Store(true) |
| 179 | if !strings.Contains(screen("GET", id+"/frame", "", 200), `"pixel_ratio_supported":true`) { |
| 180 | t.Fatal("host did not negotiate pixel density with a capable guest") |
| 181 | } |
| 182 | screen("POST", id+"/action", `{"type":"resize","width":390,"height":640,"pixel_ratio":3.5}`, 200) |
| 183 | screen("POST", id+"/action", `{"type":"resize","width":390,"height":640,"pixel_ratio":-1}`, 400) |
| 184 | screen("POST", id+"/action", `{"type":"resize","width":390,"height":640,"pixel_ratio":9}`, 400) |
| 185 | if pairedHostRequest(s, "POST", "/api/mobile/browser/open", open).Code != 403 { |
| 186 | t.Fatal("CLI-only/unscoped transport used paired device permission") |
| 187 | } |
| 188 | do("POST", "open", strings.Replace(open, `"width"`, `"profile":"override","width"`, 1), 400) |
| 189 | s.mu.Lock() |
| 190 | s.preferences.BrowserHomeURL = customHome |
| 191 | s.mu.Unlock() |
| 192 | if reply := do("POST", "open", open, 200); !strings.Contains(reply, `"action_frame":true`) { |
| 193 | t.Fatal("browser open did not advertise action frames") |
| 194 | } |
| 195 | if url := <-openedURLs; url != customHome { |
| 196 | t.Fatalf("phone opened %q instead of desktop home", url) |
| 197 | } |
| 198 | do("POST", "open", open, 200) |
| 199 | if opens.Load() != 1 { |
| 200 | t.Fatal("duplicate open started a second guest browser") |
| 201 | } |
| 202 | if !strings.Contains(do("GET", id+"/frame", "", 200), "dGVzdA==") { |
| 203 | t.Fatal("frame did not cross paired link") |
| 204 | } |
| 205 | do("POST", id+"/action", `{"type":"tap","x":0,"y":32,"document":"test"}`, 200) |
| 206 | if out := do("GET", id+"/frame?after="+frameTag, "", 200); !strings.Contains(out, `"unchanged":true`) || strings.Contains(out, `"image"`) { |
| 207 | t.Fatal("unchanged frame did not round-trip through the paired transport") |
| 208 | } |
| 209 | if out := do("POST", id+"/action", `{"type":"tap","x":0,"y":32,"document":"test","return_frame":true}`, 200); !strings.Contains(out, strings.Repeat("A", 8192)) { |
| 210 | t.Fatal("attached action frame truncated or omitted") |
| 211 | } |
| 212 | do("POST", id+"/action", `{"type":"cdp"}`, 400) |
| 213 | do("GET", uuid.NewString()+"/frame", "", 410) |
| 214 | do("POST", id+"/close", "{}", 200) |
| 215 | do("POST", "open", strings.Replace(open, `"width"`, `"url":"https://claude.ai/","width"`, 1), 200) |
| 216 | if url := <-openedURLs; url != "https://claude.ai/" { |
| 217 | t.Fatal("explicit shortcut overridden by home") |
| 218 | } |
| 219 | do("POST", id+"/close", "{}", 200) |
| 220 | s.mu.Lock() |
| 221 | s.preferences.BrowserHomeURL = blockedHome |
| 222 | s.mu.Unlock() |
| 223 | if reply := do("POST", "open", open, 200); !strings.Contains(reply, "home_notice") { |
| 224 | t.Fatal("missing message for unavailable homepage") |
| 225 | } |
| 226 | if first, next := <-openedURLs, <-openedURLs; first != blockedHome || next != "" { |
| 227 | t.Fatal("unavailable homepage must leave a usable browser") |
| 228 | } |
| 229 | |
| 230 | screen("POST", id+"/close", "{}", 200) |
| 231 | do("GET", id+"/frame", "", 200) |
| 232 | desktopOpenStatus.Store(503) |
| 233 | screen("POST", "open", open, 200) |
| 234 | screen("GET", id+"/frame", "", 425) |
| 235 | s.phones.desktop.op.Lock() |
| 236 | s.phones.desktop.session.readyUntil = time.Now().Add(-time.Second) |
| 237 | s.phones.desktop.op.Unlock() |
| 238 | |
| 239 | screen("GET", id+"/frame", "", 502) |
| 240 | desktopOpenStatus.Store(0) |
| 241 | screen("POST", "open", open, 200) |
| 242 | |
| 243 | |
| 244 | slowFrame.Store(true) |
| 245 | pending := make(chan int, 1) |
| 246 | go func() { |
| 247 | reply, err := phone.Do(ctx, "GET", "/api/mobile/browser/"+id+"/frame", nil) |
| 248 | if err != nil { |
| 249 | pending <- 0 |
| 250 | return |
| 251 | } |
| 252 | pending <- reply.Status |
| 253 | }() |
| 254 | select { |
| 255 | case <-receiving: |
| 256 | case <-ctx.Done(): |
| 257 | t.Fatal("guest never received frame request") |
| 258 | } |
| 259 | gate.Close("network revoked") |
| 260 | screen("GET", id+"/frame", "", 409) |
| 261 | s.account.lock() |
| 262 | select { |
| 263 | case code := <-pending: |
| 264 | if code == 200 { |
| 265 | t.Fatal("frame disclosed after account lock") |
| 266 | } |
| 267 | case <-ctx.Done(): |
| 268 | t.Fatal("capture survived account lock") |
| 269 | } |
| 270 | } |