| 1 | package browser |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "reflect" |
| 11 | "strings" |
| 12 | "sync/atomic" |
| 13 | "testing" |
| 14 | "time" |
| 15 | ) |
| 16 | |
| 17 | const testToken = "broker-token-1" |
| 18 | |
| 19 | // sessionRecorder wraps the fake so the handler-side context can be checked. |
| 20 | type sessionRecorder struct { |
| 21 | *fakeExecutor |
| 22 | sessions []string |
| 23 | } |
| 24 | |
| 25 | func (s *sessionRecorder) Tabs(ctx context.Context) ([]Tab, error) { |
| 26 | s.sessions = append(s.sessions, SessionFromContext(ctx)) |
| 27 | return s.fakeExecutor.Tabs(ctx) |
| 28 | } |
| 29 | |
| 30 | func newRoundTrip(t *testing.T, exec Executor) (Executor, *httptest.Server) { |
| 31 | t.Helper() |
| 32 | srv := httptest.NewServer(NewHTTPHandler(exec, testToken)) |
| 33 | t.Cleanup(srv.Close) |
| 34 | return NewHTTPExecutor(srv.URL, testToken, srv.Client()), srv |
| 35 | } |
| 36 | |
| 37 | func TestHTTPRoundTripEveryMethod(t *testing.T) { |
| 38 | fake := &fakeExecutor{ |
| 39 | tabs: []Tab{{ID: "t1", URL: "https://a.test", Title: "A", Loading: true}, {ID: "t2", URL: "https://b.test", Temporary: true}}, |
| 40 | snapshot: Snapshot{DocumentToken: "doc-1", URL: "https://a.test", Title: "A", Tree: "root\n button \"Go\" ref=e1", Refs: 1}, |
| 41 | screenshot: Screenshot{Path: "/tmp/shot.png", MIME: "image/png", Width: 800, Height: 600}, |
| 42 | act: ActResult{Executed: true, DocumentToken: "doc-2", Outcome: OutcomeExecuted}, |
| 43 | downloads: []Download{{ID: "d1", URL: "https://a.test/f.zip", Path: "/tmp/f.zip", State: "completed", Bytes: 42}}, |
| 44 | } |
| 45 | rec := &sessionRecorder{fakeExecutor: fake} |
| 46 | client, _ := newRoundTrip(t, rec) |
| 47 | ctx := WithSession(context.Background(), "/sessions/one.jsonl") |
| 48 | |
| 49 | tabs, err := client.Tabs(ctx) |
| 50 | if err != nil || !reflect.DeepEqual(tabs, fake.tabs) { |
| 51 | t.Fatalf("tabs = %+v, %v; want %+v", tabs, err, fake.tabs) |
| 52 | } |
| 53 | if !reflect.DeepEqual(rec.sessions, []string{"/sessions/one.jsonl"}) { |
| 54 | t.Fatalf("handler saw sessions %q, want the client's session", rec.sessions) |
| 55 | } |
| 56 | tab, err := client.Open(ctx, OpenRequest{OperationID: "open-1", URL: "https://c.test", Temporary: true}) |
| 57 | if err != nil || tab != (Tab{ID: "t-new", URL: "https://c.test", Temporary: true}) { |
| 58 | t.Fatalf("open = %+v, %v", tab, err) |
| 59 | } |
| 60 | if !reflect.DeepEqual(fake.opens, []OpenRequest{{OperationID: "open-1", URL: "https://c.test", Temporary: true}}) { |
| 61 | t.Fatalf("open request = %+v", fake.opens) |
| 62 | } |
| 63 | tab, err = client.Navigate(ctx, NavigateRequest{OperationID: "nav-1", TabID: "t1", URL: "https://d.test", Action: NavigateURL}) |
| 64 | if err != nil || tab != (Tab{ID: "t1", URL: "https://d.test"}) { |
| 65 | t.Fatalf("navigate = %+v, %v", tab, err) |
| 66 | } |
| 67 | if !reflect.DeepEqual(fake.navs, []NavigateRequest{{OperationID: "nav-1", TabID: "t1", URL: "https://d.test", Action: NavigateURL}}) { |
| 68 | t.Fatalf("navigate request = %+v", fake.navs) |
| 69 | } |
| 70 | snap, err := client.Snapshot(ctx, SnapshotRequest{TabID: "t1", Selector: "main"}) |
| 71 | if err != nil || snap != fake.snapshot { |
| 72 | t.Fatalf("snapshot = %+v, %v", snap, err) |
| 73 | } |
| 74 | if !reflect.DeepEqual(fake.snaps, []SnapshotRequest{{TabID: "t1", Selector: "main"}}) { |
| 75 | t.Fatalf("snapshot request = %+v", fake.snaps) |
| 76 | } |
| 77 | shot, err := client.Screenshot(ctx, ScreenshotRequest{TabID: "t1", Ref: "e1", FullPage: true}) |
| 78 | if err != nil || shot != fake.screenshot { |
| 79 | t.Fatalf("screenshot = %+v, %v", shot, err) |
| 80 | } |
| 81 | if !reflect.DeepEqual(fake.shots, []ScreenshotRequest{{TabID: "t1", Ref: "e1", FullPage: true}}) { |
| 82 | t.Fatalf("screenshot request = %+v", fake.shots) |
| 83 | } |
| 84 | actReq := ActRequest{ |
| 85 | OperationID: "op-1", TabID: "t1", DocumentToken: "doc-1", Action: ActionUpload, Ref: "e1", |
| 86 | Text: "hello", Keys: "Enter", Options: []string{"a", "b"}, Files: []string{"/tmp/x.txt"}, Submit: true, DeltaX: 3, DeltaY: -4, |
| 87 | } |
| 88 | res, err := client.Act(ctx, actReq) |
| 89 | if err != nil || res != fake.act { |
| 90 | t.Fatalf("act = %+v, %v", res, err) |
| 91 | } |
| 92 | if !reflect.DeepEqual(fake.acts, []ActRequest{actReq}) { |
| 93 | t.Fatalf("act request = %+v, want %+v", fake.acts, actReq) |
| 94 | } |
| 95 | downloads, err := client.Downloads(ctx, DownloadsRequest{TabID: "t1", WaitFor: 1500 * time.Millisecond}) |
| 96 | if err != nil || !reflect.DeepEqual(downloads, fake.downloads) { |
| 97 | t.Fatalf("downloads = %+v, %v", downloads, err) |
| 98 | } |
| 99 | if !reflect.DeepEqual(fake.dls, []DownloadsRequest{{TabID: "t1", WaitFor: 1500 * time.Millisecond}}) { |
| 100 | t.Fatalf("downloads request = %+v", fake.dls) |
| 101 | } |
| 102 | if err := client.Close(ctx, CloseRequest{OperationID: "close-1", TabID: "t2"}); err != nil || !reflect.DeepEqual(fake.closed, []string{"t2"}) { |
| 103 | t.Fatalf("close: err=%v closed=%v", err, fake.closed) |
| 104 | } |
| 105 | if len(fake.closes) != 1 || fake.closes[0].OperationID != "close-1" { |
| 106 | t.Fatalf("close operationId lost: %+v", fake.closes) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | func TestHTTPEveryWriteTreatsMalformedReceiptAsUnknown(t *testing.T) { |
| 111 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("{broken")) })) |
| 112 | defer server.Close() |
| 113 | exec := NewHTTPExecutor(server.URL, "token", server.Client()) |
| 114 | ctx := context.Background() |
| 115 | checks := []error{} |
| 116 | _, err := exec.Open(ctx, OpenRequest{OperationID: "open", URL: "https://example.test"}) |
| 117 | checks = append(checks, err) |
| 118 | _, err = exec.Navigate(ctx, NavigateRequest{OperationID: "nav", TabID: "t", Action: NavigateBack}) |
| 119 | checks = append(checks, err) |
| 120 | _, err = exec.Act(ctx, ActRequest{OperationID: "act", TabID: "t", Action: ActionClick}) |
| 121 | checks = append(checks, err) |
| 122 | for _, err := range checks { |
| 123 | if !errors.Is(err, ErrUnknownOutcome) { |
| 124 | t.Fatalf("malformed write receipt: %v", err) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func TestHTTPActRequiresAnExplicitExecutionReceipt(t *testing.T) { |
| 130 | for _, payload := range []string{`{}`, `{"executed":null}`, `{"executed":"false"}`} { |
| 131 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(payload)) })) |
| 132 | exec := NewHTTPExecutor(server.URL, "token", server.Client()) |
| 133 | _, err := exec.Act(context.Background(), ActRequest{OperationID: "act", Action: ActionClick}) |
| 134 | server.Close() |
| 135 | if !errors.Is(err, ErrUnknownOutcome) { |
| 136 | t.Fatalf("payload %s became a known receipt: %v", payload, err) |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | func TestHTTPRoundTripMapsEverySentinel(t *testing.T) { |
| 142 | for _, sentinel := range []error{ErrStaleReference, ErrTakenOver, ErrNoGrant, ErrUnknownOutcome} { |
| 143 | fake := &fakeExecutor{err: fmt.Errorf("%w: from the host", sentinel)} |
| 144 | client, _ := newRoundTrip(t, fake) |
| 145 | ctx := context.Background() |
| 146 | checks := []struct { |
| 147 | name string |
| 148 | err error |
| 149 | }{ |
| 150 | {"tabs", func() error { _, err := client.Tabs(ctx); return err }()}, |
| 151 | {"open", func() error { _, err := client.Open(ctx, OpenRequest{URL: "https://a.test"}); return err }()}, |
| 152 | {"navigate", func() error { |
| 153 | _, err := client.Navigate(ctx, NavigateRequest{TabID: "t1", Action: NavigateBack}) |
| 154 | return err |
| 155 | }()}, |
| 156 | {"snapshot", func() error { _, err := client.Snapshot(ctx, SnapshotRequest{TabID: "t1"}); return err }()}, |
| 157 | {"screenshot", func() error { _, err := client.Screenshot(ctx, ScreenshotRequest{TabID: "t1"}); return err }()}, |
| 158 | {"act", func() error { |
| 159 | _, err := client.Act(ctx, ActRequest{OperationID: "op", TabID: "t1", Action: ActionClick}) |
| 160 | return err |
| 161 | }()}, |
| 162 | {"downloads", func() error { _, err := client.Downloads(ctx, DownloadsRequest{TabID: "t1"}); return err }()}, |
| 163 | {"close", client.Close(ctx, CloseRequest{OperationID: "close-1", TabID: "t1"})}, |
| 164 | } |
| 165 | for _, c := range checks { |
| 166 | if !errors.Is(c.err, sentinel) { |
| 167 | t.Errorf("%s with %v: got %v, want the sentinel", c.name, sentinel, c.err) |
| 168 | } |
| 169 | if c.err != nil && c.err.Error() != sentinel.Error()+": from the host" { |
| 170 | t.Errorf("%s with %v: message %q lost the host's detail", c.name, sentinel, c.err) |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | func TestHTTPRoundTripPlainErrorsAndStatuses(t *testing.T) { |
| 177 | fake := &fakeExecutor{err: errors.New("shell exploded")} |
| 178 | client, srv := newRoundTrip(t, fake) |
| 179 | if _, err := client.Tabs(context.Background()); err == nil || errors.Is(err, ErrNoGrant) || errors.Is(err, ErrUnknownOutcome) { |
| 180 | t.Fatalf("plain error must not map onto a sentinel: %v", err) |
| 181 | } else if got := err.Error(); got != "browser broker: tabs: status 500: shell exploded" { |
| 182 | t.Fatalf("plain error text = %q", got) |
| 183 | } |
| 184 | wrong := NewHTTPExecutor(srv.URL, "other-token", srv.Client()) |
| 185 | if _, err := wrong.Tabs(context.Background()); err == nil || errors.Is(err, ErrNoGrant) { |
| 186 | t.Fatalf("wrong token: got %v, want a plain 401 error", err) |
| 187 | } |
| 188 | if a, ok := wrong.(Availability); !ok || a.Available(context.Background()) { |
| 189 | t.Fatal("wrong token must not be reported available") |
| 190 | } |
| 191 | resp, err := http.Get(srv.URL + "/v1/browser/tabs") |
| 192 | if err != nil { |
| 193 | t.Fatal(err) |
| 194 | } |
| 195 | resp.Body.Close() |
| 196 | if resp.StatusCode != http.StatusUnauthorized { |
| 197 | t.Fatalf("no bearer: status %d, want 401", resp.StatusCode) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // TestHTTPUnknownOutcomeIsNeverRetried covers both ways a receipt is lost: a |
| 202 | // 409 unknown_outcome from the host, and a connection that dies before any |
| 203 | // reply. Either way exactly one request reaches the server. |
| 204 | func TestHTTPUnknownOutcomeIsNeverRetried(t *testing.T) { |
| 205 | var calls atomic.Int32 |
| 206 | fake := &fakeExecutor{err: ErrUnknownOutcome} |
| 207 | counted := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 208 | calls.Add(1) |
| 209 | NewHTTPHandler(fake, testToken).ServeHTTP(w, r) |
| 210 | }) |
| 211 | srv := httptest.NewServer(counted) |
| 212 | defer srv.Close() |
| 213 | client := NewHTTPExecutor(srv.URL, testToken, srv.Client()) |
| 214 | res, err := client.Act(context.Background(), ActRequest{OperationID: "op-1", TabID: "t1", Action: ActionClick}) |
| 215 | if !errors.Is(err, ErrUnknownOutcome) || res.Outcome != OutcomeUnknown { |
| 216 | t.Fatalf("act = %+v, %v; want ErrUnknownOutcome", res, err) |
| 217 | } |
| 218 | if n := calls.Load(); n != 1 { |
| 219 | t.Fatalf("unknown outcome reached the server %d times, want exactly 1", n) |
| 220 | } |
| 221 | |
| 222 | var dropped atomic.Int32 |
| 223 | dropping := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 224 | dropped.Add(1) |
| 225 | conn, _, err := w.(http.Hijacker).Hijack() |
| 226 | if err != nil { |
| 227 | t.Errorf("hijack: %v", err) |
| 228 | return |
| 229 | } |
| 230 | _ = conn.(*net.TCPConn).SetLinger(0) |
| 231 | _ = conn.Close() |
| 232 | })) |
| 233 | defer dropping.Close() |
| 234 | client = NewHTTPExecutor(dropping.URL, testToken, dropping.Client()) |
| 235 | res, err = client.Act(context.Background(), ActRequest{OperationID: "op-2", TabID: "t1", Action: ActionClick}) |
| 236 | if !errors.Is(err, ErrUnknownOutcome) || res.Outcome != OutcomeUnknown { |
| 237 | t.Fatalf("dropped act = %+v, %v; want ErrUnknownOutcome", res, err) |
| 238 | } |
| 239 | if n := dropped.Load(); n != 1 { |
| 240 | t.Fatalf("dropped act reached the server %d times, want exactly 1", n) |
| 241 | } |
| 242 | if _, err := client.Tabs(context.Background()); err == nil || errors.Is(err, ErrUnknownOutcome) { |
| 243 | t.Fatalf("a dropped read is a plain error, got %v", err) |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | func TestHTTPAvailableCachesHealthForThirtySeconds(t *testing.T) { |
| 248 | var probes atomic.Int32 |
| 249 | gate := gatedExecutor{fakeExecutor: &fakeExecutor{}, available: true} |
| 250 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 251 | if r.URL.Path == httpHealthRoute { |
| 252 | probes.Add(1) |
| 253 | } |
| 254 | NewHTTPHandler(gate, testToken).ServeHTTP(w, r) |
| 255 | })) |
| 256 | defer srv.Close() |
| 257 | exec := NewHTTPExecutor(srv.URL, testToken, srv.Client()).(*httpExecutor) |
| 258 | now := time.Unix(1_700_000_000, 0) |
| 259 | exec.now = func() time.Time { return now } |
| 260 | ctx := context.Background() |
| 261 | for range 3 { |
| 262 | if !exec.Available(ctx) { |
| 263 | t.Fatal("healthy broker reported unavailable") |
| 264 | } |
| 265 | } |
| 266 | if n := probes.Load(); n != 1 { |
| 267 | t.Fatalf("health probed %d times within the cache window, want 1", n) |
| 268 | } |
| 269 | now = now.Add(httpHealthTTL) |
| 270 | if !exec.Available(ctx) || probes.Load() != 2 { |
| 271 | t.Fatalf("expired cache must probe again: probes=%d", probes.Load()) |
| 272 | } |
| 273 | gate.available = false |
| 274 | now = now.Add(httpHealthTTL) |
| 275 | if exec.Available(ctx) { |
| 276 | t.Fatal("503 health must report unavailable") |
| 277 | } |
| 278 | if exec.Available(ctx) || probes.Load() != 4 { |
| 279 | t.Fatalf("a failed probe is not cached: probes=%d", probes.Load()) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | func TestHTTPHandlerRejectsOversizedAndMalformedBodies(t *testing.T) { |
| 284 | fake := &fakeExecutor{} |
| 285 | srv := httptest.NewServer(NewHTTPHandler(fake, testToken)) |
| 286 | defer srv.Close() |
| 287 | do := func(body string) int { |
| 288 | req, _ := http.NewRequest(http.MethodPost, srv.URL+"/v1/browser/open", strings.NewReader(body)) |
| 289 | req.Header.Set("Authorization", "Bearer "+testToken) |
| 290 | resp, err := srv.Client().Do(req) |
| 291 | if err != nil { |
| 292 | t.Fatal(err) |
| 293 | } |
| 294 | resp.Body.Close() |
| 295 | return resp.StatusCode |
| 296 | } |
| 297 | if code := do("{not json"); code != http.StatusBadRequest { |
| 298 | t.Fatalf("malformed body: status %d, want 400", code) |
| 299 | } |
| 300 | big := make([]byte, httpMaxRequestBytes+16) |
| 301 | for i := range big { |
| 302 | big[i] = ' ' |
| 303 | } |
| 304 | if code := do(`{"url":"` + string(big) + `"}`); code != http.StatusBadRequest { |
| 305 | t.Fatalf("oversized body: status %d, want 400", code) |
| 306 | } |
| 307 | if len(fake.opens) != 0 { |
| 308 | t.Fatalf("rejected bodies reached the executor: %+v", fake.opens) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | func TestSessionContextRoundTrip(t *testing.T) { |
| 313 | if got := SessionFromContext(context.Background()); got != "" { |
| 314 | t.Fatalf("empty context session = %q", got) |
| 315 | } |
| 316 | ctx := WithSession(context.Background(), "s-1") |
| 317 | if got := SessionFromContext(ctx); got != "s-1" { |
| 318 | t.Fatalf("session = %q, want s-1", got) |
| 319 | } |
| 320 | if WithSession(ctx, "") != ctx { |
| 321 | t.Fatal("an empty session must not replace the context") |
| 322 | } |
| 323 | } |
| 324 |