| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "crypto/ecdsa" |
| 6 | "crypto/elliptic" |
| 7 | "crypto/rand" |
| 8 | "crypto/tls" |
| 9 | "crypto/x509" |
| 10 | "crypto/x509/pkix" |
| 11 | "encoding/json" |
| 12 | "encoding/pem" |
| 13 | "errors" |
| 14 | "fmt" |
| 15 | "math/big" |
| 16 | "net" |
| 17 | "net/http" |
| 18 | "net/http/httputil" |
| 19 | "net/url" |
| 20 | "os" |
| 21 | "os/exec" |
| 22 | "path/filepath" |
| 23 | "strings" |
| 24 | "sync" |
| 25 | "testing" |
| 26 | "time" |
| 27 | |
| 28 | "the-valley/web/export" |
| 29 | ) |
| 30 | |
| 31 | // TestBrowser is the web-reader-browser-e2e check: the packaged |
| 32 | // valley-web, which VALLEY_WEB names, behind a TLS proxy, and headless |
| 33 | // Chromium, which VALLEY_WEB_CHROMIUM names, driven over its automation |
| 34 | // pipe. Chromium trusts the proxy's certificate through a test CA added |
| 35 | // to the temporary profile's certificate database with certutil; nothing |
| 36 | // turns certificate checks or browser security off. It holds the browser |
| 37 | // engine to the reader page alone: loading the page takes the link out of |
| 38 | // the address bar and sends nothing, the page's policy runs its script and |
| 39 | // lets it fetch while it blocks a script put in the page, and one click |
| 40 | // redeems the link once, stores the host-only cookie over HTTPS, and |
| 41 | // lands on /. Two answers the proxy spoils then leave the outcome |
| 42 | // unknown, and the page says so. A redemption, after a sign-out, answered |
| 43 | // 502 with the new session's cookie: the retry asks /-/session, finds |
| 44 | // this link's session, and lands on / with no second sign-out. A |
| 45 | // redemption whose answer never arrived: the retry finds no session, |
| 46 | // signs no one out, and is told the link cannot be used. web-server-unit |
| 47 | // skips it. |
| 48 | func TestBrowser(t *testing.T) { |
| 49 | chromium, web := os.Getenv("VALLEY_WEB_CHROMIUM"), os.Getenv("VALLEY_WEB") |
| 50 | if chromium == "" || web == "" { |
| 51 | if os.Getenv("VALLEY_TEST_TOOLS") == "required" { |
| 52 | t.Fatal("VALLEY_WEB_CHROMIUM or VALLEY_WEB names nothing, and VALLEY_TEST_TOOLS=required") |
| 53 | } |
| 54 | t.Skip("VALLEY_WEB_CHROMIUM and VALLEY_WEB name no browser and no valley-web; the web-reader-browser-e2e check provides both") |
| 55 | } |
| 56 | home := t.TempDir() |
| 57 | certificate := trustedCertificate(t, home) |
| 58 | |
| 59 | // The proxy listens first, so valley-web is given its origin. |
| 60 | ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{certificate}}) |
| 61 | if err != nil { |
| 62 | t.Fatal(err) |
| 63 | } |
| 64 | defer ln.Close() |
| 65 | origin := fmt.Sprintf("https://localhost:%d", ln.Addr().(*net.TCPAddr).Port) |
| 66 | |
| 67 | e := newReaderEdge(t) |
| 68 | first := e.start(exec.Command(web, "--state", e.state, "--listen", "127.0.0.1:0", "--origin", origin)) |
| 69 | e.created() |
| 70 | e.bind(true) |
| 71 | |
| 72 | target, _ := url.Parse("http://" + first.addr) |
| 73 | seen := &requests{} |
| 74 | proxy := httputil.NewSingleHostReverseProxy(target) |
| 75 | proxy.ModifyResponse = seen.answer |
| 76 | proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { |
| 77 | if errors.Is(err, errDropped) { |
| 78 | if c, _, err := http.NewResponseController(w).Hijack(); err == nil { |
| 79 | c.Close() |
| 80 | return |
| 81 | } |
| 82 | } |
| 83 | w.WriteHeader(http.StatusBadGateway) |
| 84 | } |
| 85 | // Each answer closes its connection, so no request the browser sends |
| 86 | // again on a connection it reused hides a dropped answer. |
| 87 | front := &http.Server{Handler: proxy} |
| 88 | front.SetKeepAlivesEnabled(false) |
| 89 | go front.Serve(ln) |
| 90 | |
| 91 | t.Cleanup(func() { |
| 92 | if t.Failed() { |
| 93 | seen.mu.Lock() |
| 94 | defer seen.mu.Unlock() |
| 95 | t.Logf("the proxy passed on %+v, and valley-web logged:\n%s", seen.seen, redacted(first.logged())) |
| 96 | } |
| 97 | }) |
| 98 | b := startBrowser(t, chromium, home) |
| 99 | page := b.page(t) |
| 100 | page.call(t, "Page.enable", nil) |
| 101 | page.open(t, origin+"/-/redeem#"+e.links[0].credential) |
| 102 | if href := page.eval(t, `location.href`); href != origin+"/-/redeem" { |
| 103 | t.Errorf("the address bar holds %s once the page loaded", redacted(fmt.Sprint(href))) |
| 104 | } |
| 105 | if !page.visible(t, "r-redeem") { |
| 106 | t.Error("the reader script did not run under the page's policy: its button is hidden") |
| 107 | } |
| 108 | // The page is read back and searched here, so no expression and no |
| 109 | // failure carries the secret. |
| 110 | if html, ok := page.eval(t, `document.documentElement.outerHTML`).(string); !ok || strings.Contains(html, strings.SplitN(e.links[0].credential, ".", 2)[1]) { |
| 111 | t.Error("the page could not be read, or the link's secret is in it") |
| 112 | } |
| 113 | blocked := page.eval(t, `(() => { |
| 114 | const s = document.createElement("script"); |
| 115 | s.textContent = "window.injected = true"; |
| 116 | document.head.appendChild(s); |
| 117 | return window.injected === undefined; |
| 118 | })()`) |
| 119 | if blocked != true { |
| 120 | t.Error("the page's policy ran a script put in the page") |
| 121 | } |
| 122 | time.Sleep(500 * time.Millisecond) |
| 123 | if n := seen.count("POST", "/-/redeem"); n != 0 { |
| 124 | t.Fatalf("loading the page sent %d redemptions", n) |
| 125 | } |
| 126 | |
| 127 | page.click(t, "r-redeem") |
| 128 | // A command sent while the page navigates may go unanswered, so the |
| 129 | // navigation is followed through the proxy first. |
| 130 | page.until(t, "the browser follows / with its session", func() bool { return seen.cookied("GET", "/") }) |
| 131 | page.until(t, "the click lands on a page of the source", func() bool { return b.landed(origin) }) |
| 132 | if n := seen.count("POST", "/-/redeem"); n != 1 || seen.status("POST", "/-/redeem") != http.StatusNoContent { |
| 133 | t.Errorf("one click sent %d redemptions, the first answered %d", n, seen.status("POST", "/-/redeem")) |
| 134 | } |
| 135 | if !seen.cookied("GET", "/") { |
| 136 | t.Error("the browser did not carry the session cookie to /") |
| 137 | } |
| 138 | cookies := b.cookies(t) |
| 139 | if len(cookies) != 1 { |
| 140 | t.Fatalf("the browser holds %d cookies", len(cookies)) |
| 141 | } |
| 142 | c := cookies[0] |
| 143 | if c.Name != "__Host-valley-reader" || c.Domain != "localhost" || c.Path != "/" || c.SameSite != "Lax" || !c.Secure || !c.HTTPOnly { |
| 144 | t.Errorf("the browser holds the cookie %v", c) |
| 145 | } |
| 146 | |
| 147 | // A switch to another link whose redemption answers 502, with the new |
| 148 | // session's cookie: the outcome is unknown, and the page says so. The |
| 149 | // retry finds this link's session, and lands with no second sign-out. |
| 150 | page.open(t, origin+"/-/redeem#"+e.links[1].credential) |
| 151 | if !page.visible(t, "r-switch") { |
| 152 | t.Fatal("a signed-in browser is not offered to sign out first") |
| 153 | } |
| 154 | seen.spoil(func(res *http.Response) error { |
| 155 | res.StatusCode, res.Status = http.StatusBadGateway, "502 Bad Gateway" |
| 156 | return nil |
| 157 | }) |
| 158 | page.click(t, "r-switch") |
| 159 | page.unknown(t, "r-switch") |
| 160 | page.click(t, "r-switch") |
| 161 | page.until(t, "the retry lands on a page of the source", func() bool { return b.landed(origin) }) |
| 162 | if n := seen.count("POST", "/-/logout"); n != 1 { |
| 163 | t.Errorf("the switch and its retry sent %d logouts, want 1", n) |
| 164 | } |
| 165 | if n, asked := seen.count("POST", "/-/redeem"), seen.count("GET", "/-/session"); n != 2 || asked != 1 { |
| 166 | t.Errorf("the switch and its retry sent %d redemptions in all and asked for the session %d times, want 2 and 1", n, asked) |
| 167 | } |
| 168 | if cookies := b.cookies(t); len(cookies) != 1 || !strings.HasPrefix(cookies[0].Value, e.links[1].binding.ID+".") { |
| 169 | t.Errorf("after the retry the browser holds %v, not the second link's session", cookies) |
| 170 | } |
| 171 | |
| 172 | // A switch whose redemption's answer never arrives: the session it |
| 173 | // started never reaches the browser. The retry finds no session, so |
| 174 | // it signs no one out, and the link, used already, is refused. |
| 175 | page.open(t, origin+"/-/redeem#"+e.links[2].credential) |
| 176 | seen.spoil(func(*http.Response) error { return errDropped }) |
| 177 | page.click(t, "r-switch") |
| 178 | page.unknown(t, "r-switch") |
| 179 | page.click(t, "r-switch") |
| 180 | page.until(t, "the retry is told the link cannot be used", func() bool { return page.visible(t, "r-refused") }) |
| 181 | if n := seen.count("POST", "/-/logout"); n != 2 { |
| 182 | t.Errorf("the second switch and its retry sent %d logouts in all, want 2", n) |
| 183 | } |
| 184 | if n, asked := seen.count("POST", "/-/redeem"), seen.count("GET", "/-/session"); n != 4 || asked != 2 { |
| 185 | t.Errorf("the second switch and its retry sent %d redemptions in all and asked for the session %d times, want 4 and 2", n, asked) |
| 186 | } |
| 187 | if cookies := b.cookies(t); len(cookies) != 0 { |
| 188 | t.Errorf("after a lost answer the browser holds %v", cookies) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | // errDropped is what the proxy's spoiler returns to drop an answer: the |
| 193 | // proxy closes the connection, and writes none of it. |
| 194 | var errDropped = errors.New("the proxy drops this answer") |
| 195 | |
| 196 | // open navigates the tab to a reader page, and waits for it to load. A |
| 197 | // command sent while the page navigates may go unanswered, so it waits |
| 198 | // for the navigation to the page first, and asks again when an answer |
| 199 | // does not come. |
| 200 | func (p *tab) open(t *testing.T, target string) { |
| 201 | t.Helper() |
| 202 | navigated := p.call(t, "Page.navigate", map[string]any{"url": target}) |
| 203 | page, _, _ := strings.Cut(target, "#") |
| 204 | for range 200 { |
| 205 | if p.b.navigated() == page { |
| 206 | loaded, ok := p.evalWithin(t, `document.readyState === "complete" && !!document.getElementById("reader")`, 2*time.Second) |
| 207 | if ok && loaded == true { |
| 208 | return |
| 209 | } |
| 210 | } |
| 211 | time.Sleep(50 * time.Millisecond) |
| 212 | } |
| 213 | p.b.mu.Lock() |
| 214 | events := strings.Join(p.b.events, "\n") |
| 215 | p.b.mu.Unlock() |
| 216 | t.Fatalf("%s did not load within ten seconds: the last navigation went to %s, and Page.navigate answered %s; events:\n%s", page, redacted(p.b.navigated()), navigated, redacted(events)) |
| 217 | } |
| 218 | |
| 219 | // click clicks the middle of the element id, as a reader does. |
| 220 | func (p *tab) click(t *testing.T, id string) { |
| 221 | t.Helper() |
| 222 | box := p.eval(t, `JSON.stringify(document.getElementById(`+jsString(id)+`).getBoundingClientRect())`) |
| 223 | s, _ := box.(string) |
| 224 | var rect struct{ X, Y, Width, Height float64 } |
| 225 | if err := json.Unmarshal([]byte(s), &rect); err != nil || rect.Width == 0 { |
| 226 | t.Fatalf("the page has no %s to click: %v", id, box) |
| 227 | } |
| 228 | x, y := rect.X+rect.Width/2, rect.Y+rect.Height/2 |
| 229 | for _, kind := range []string{"mousePressed", "mouseReleased"} { |
| 230 | p.call(t, "Input.dispatchMouseEvent", map[string]any{"type": kind, "x": x, "y": y, "button": "left", "clickCount": 1}) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // visible reports whether the element id is shown. |
| 235 | func (p *tab) visible(t *testing.T, id string) bool { |
| 236 | t.Helper() |
| 237 | return p.eval(t, `(() => { const e = document.getElementById(`+jsString(id)+`); return !!e && !e.hidden; })()`) == true |
| 238 | } |
| 239 | |
| 240 | // unknown waits for the page to say that an outcome is unknown, with the |
| 241 | // button retried enabled again. |
| 242 | func (p *tab) unknown(t *testing.T, button string) { |
| 243 | t.Helper() |
| 244 | p.until(t, "the page says the outcome is unknown", func() bool { |
| 245 | return p.visible(t, "r-unknown") && p.eval(t, `document.getElementById(`+jsString(button)+`).disabled`) == false |
| 246 | }) |
| 247 | text, _ := p.eval(t, `document.getElementById("r-unknown").textContent`).(string) |
| 248 | if !strings.Contains(text, "cannot tell whether the server used your link") || !strings.Contains(text, "request another link") { |
| 249 | t.Errorf("the page says %q of an unknown outcome", text) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // landed reports whether the last navigation went to a page of this |
| 254 | // origin's source, out of /-/. |
| 255 | func (b *browser) landed(origin string) bool { |
| 256 | u, err := url.Parse(b.navigated()) |
| 257 | return err == nil && u.Host == strings.TrimPrefix(origin, "https://") && !strings.HasPrefix(u.Path, "/-/") |
| 258 | } |
| 259 | |
| 260 | // cookie is a cookie the browser holds, as Storage.getCookies tells it. |
| 261 | type cookie struct { |
| 262 | Name, Value, Domain, Path, SameSite string |
| 263 | Secure bool |
| 264 | HTTPOnly bool `json:"httpOnly"` |
| 265 | } |
| 266 | |
| 267 | // String is the cookie for a failure's message: its metadata, and the |
| 268 | // credential ID its value starts with, never the value. |
| 269 | func (c cookie) String() string { |
| 270 | id, _, _ := strings.Cut(c.Value, ".") |
| 271 | if !export.ValidLinkID(id) { |
| 272 | id = "none" |
| 273 | } |
| 274 | return fmt.Sprintf("{%s for %s%s, SameSite=%s, Secure=%v, HttpOnly=%v, credential ID %s}", c.Name, c.Domain, c.Path, c.SameSite, c.Secure, c.HTTPOnly, id) |
| 275 | } |
| 276 | |
| 277 | func (b *browser) cookies(t *testing.T) []cookie { |
| 278 | t.Helper() |
| 279 | var held struct{ Cookies []cookie } |
| 280 | if err := json.Unmarshal(b.send(t, "", "Storage.getCookies", nil), &held); err != nil { |
| 281 | t.Fatal(err) |
| 282 | } |
| 283 | return held.Cookies |
| 284 | } |
| 285 | |
| 286 | // trustedCertificate makes a test CA, adds it to a certificate database |
| 287 | // under home, as Chromium reads trusted roots there, and returns a |
| 288 | // certificate for localhost it signed. |
| 289 | func trustedCertificate(t *testing.T, home string) tls.Certificate { |
| 290 | t.Helper() |
| 291 | caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 292 | ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "valley test CA"}, |
| 293 | NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), |
| 294 | IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign} |
| 295 | caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, &caKey.PublicKey, caKey) |
| 296 | if err != nil { |
| 297 | t.Fatal(err) |
| 298 | } |
| 299 | ca, _ = x509.ParseCertificate(caDER) |
| 300 | key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 301 | leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "localhost"}, |
| 302 | DNSNames: []string{"localhost"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), |
| 303 | KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| 304 | leafDER, err := x509.CreateCertificate(rand.Reader, leaf, ca, &key.PublicKey, caKey) |
| 305 | if err != nil { |
| 306 | t.Fatal(err) |
| 307 | } |
| 308 | pemFile := filepath.Join(home, "ca.pem") |
| 309 | os.WriteFile(pemFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}), 0o600) |
| 310 | db := "sql:" + filepath.Join(home, ".pki", "nssdb") |
| 311 | os.MkdirAll(filepath.Join(home, ".pki", "nssdb"), 0o700) |
| 312 | for _, args := range [][]string{ |
| 313 | {"-N", "-d", db, "--empty-password"}, |
| 314 | {"-A", "-d", db, "-n", "valley test CA", "-t", "C,,", "-i", pemFile}, |
| 315 | } { |
| 316 | if out, err := exec.Command("certutil", args...).CombinedOutput(); err != nil { |
| 317 | t.Fatalf("certutil %v: %v\n%s", args, err, out) |
| 318 | } |
| 319 | } |
| 320 | return tls.Certificate{Certificate: [][]byte{leafDER}, PrivateKey: key} |
| 321 | } |
| 322 | |
| 323 | // requests are the requests the proxy passed on, with their answers, and |
| 324 | // what the proxy does to the next answer to a redemption. |
| 325 | type requests struct { |
| 326 | mu sync.Mutex |
| 327 | seen []seenRequest |
| 328 | spoiler func(*http.Response) error |
| 329 | } |
| 330 | |
| 331 | // spoil has the proxy pass the next answer to a redemption through f. |
| 332 | func (r *requests) spoil(f func(*http.Response) error) { |
| 333 | r.mu.Lock() |
| 334 | defer r.mu.Unlock() |
| 335 | r.spoiler = f |
| 336 | } |
| 337 | |
| 338 | type seenRequest struct { |
| 339 | method, path string |
| 340 | cookie bool |
| 341 | status int |
| 342 | } |
| 343 | |
| 344 | // answer records an answer valley-web gave, and passes the next answer |
| 345 | // to a redemption through the spoiler a test set, which then is unset. |
| 346 | func (r *requests) answer(res *http.Response) error { |
| 347 | r.mu.Lock() |
| 348 | defer r.mu.Unlock() |
| 349 | q := res.Request |
| 350 | r.seen = append(r.seen, seenRequest{q.Method, q.URL.Path, strings.Contains(q.Header.Get("Cookie"), "__Host-valley-reader="), res.StatusCode}) |
| 351 | if f := r.spoiler; f != nil && q.Method == "POST" && q.URL.Path == "/-/redeem" { |
| 352 | r.spoiler = nil |
| 353 | return f(res) |
| 354 | } |
| 355 | return nil |
| 356 | } |
| 357 | |
| 358 | func (r *requests) find(method, path string) []seenRequest { |
| 359 | r.mu.Lock() |
| 360 | defer r.mu.Unlock() |
| 361 | var found []seenRequest |
| 362 | for _, s := range r.seen { |
| 363 | if s.method == method && s.path == path { |
| 364 | found = append(found, s) |
| 365 | } |
| 366 | } |
| 367 | return found |
| 368 | } |
| 369 | |
| 370 | func (r *requests) count(method, path string) int { return len(r.find(method, path)) } |
| 371 | |
| 372 | func (r *requests) status(method, path string) int { |
| 373 | if f := r.find(method, path); len(f) > 0 { |
| 374 | return f[0].status |
| 375 | } |
| 376 | return 0 |
| 377 | } |
| 378 | |
| 379 | func (r *requests) cookied(method, path string) bool { |
| 380 | for _, s := range r.find(method, path) { |
| 381 | if s.cookie { |
| 382 | return true |
| 383 | } |
| 384 | } |
| 385 | return false |
| 386 | } |
| 387 | |
| 388 | // browser is a headless Chromium driven over its automation pipe: it |
| 389 | // reads messages from the file descriptor 3 it was given and writes them |
| 390 | // to 4, each a JSON object ended by a NUL byte. |
| 391 | type browser struct { |
| 392 | mu sync.Mutex |
| 393 | in *os.File |
| 394 | next int |
| 395 | replies map[int]chan json.RawMessage |
| 396 | // url is where the last navigation of a main frame went, and events |
| 397 | // are the events the browser sent, each its method and its frame's URL |
| 398 | // and parent, which a page that did not load is told with. |
| 399 | url string |
| 400 | events []string |
| 401 | } |
| 402 | |
| 403 | // navigated is where the last navigation of a main frame went, as the |
| 404 | // browser's Page.frameNavigated events tell it. |
| 405 | func (b *browser) navigated() string { |
| 406 | b.mu.Lock() |
| 407 | defer b.mu.Unlock() |
| 408 | return b.url |
| 409 | } |
| 410 | |
| 411 | func startBrowser(t *testing.T, chromium, home string) *browser { |
| 412 | t.Helper() |
| 413 | toBrowser, writer, _ := os.Pipe() |
| 414 | reader, fromBrowser, _ := os.Pipe() |
| 415 | cmd := exec.Command(chromium, "--headless=new", "--user-data-dir="+filepath.Join(home, "profile"), "--remote-debugging-pipe", "about:blank") |
| 416 | cmd.Env = append(os.Environ(), "HOME="+home) |
| 417 | cmd.ExtraFiles = []*os.File{toBrowser, fromBrowser} |
| 418 | logFile, _ := os.Create(filepath.Join(home, "chromium.log")) |
| 419 | cmd.Stdout, cmd.Stderr = logFile, logFile |
| 420 | if err := cmd.Start(); err != nil { |
| 421 | t.Fatal(err) |
| 422 | } |
| 423 | toBrowser.Close() |
| 424 | fromBrowser.Close() |
| 425 | t.Cleanup(func() { |
| 426 | writer.Close() |
| 427 | cmd.Process.Kill() |
| 428 | cmd.Wait() |
| 429 | if t.Failed() { |
| 430 | log, _ := os.ReadFile(logFile.Name()) |
| 431 | var kept []string |
| 432 | for _, line := range strings.Split(string(log), "\n") { |
| 433 | if !strings.Contains(line, "render_text_harfbuzz") { |
| 434 | kept = append(kept, line) |
| 435 | } |
| 436 | } |
| 437 | t.Logf("chromium logged:\n%s", redacted(tail(strings.Join(kept, "\n"), 40))) |
| 438 | } |
| 439 | }) |
| 440 | b := &browser{in: writer, replies: map[int]chan json.RawMessage{}} |
| 441 | go func() { |
| 442 | r := bufio.NewReader(reader) |
| 443 | for { |
| 444 | msg, err := r.ReadBytes(0) |
| 445 | if err != nil { |
| 446 | return |
| 447 | } |
| 448 | var reply struct { |
| 449 | ID int `json:"id"` |
| 450 | Result json.RawMessage `json:"result"` |
| 451 | Error json.RawMessage `json:"error"` |
| 452 | Method string `json:"method"` |
| 453 | Params struct { |
| 454 | Frame struct { |
| 455 | ParentID string `json:"parentId"` |
| 456 | URL string `json:"url"` |
| 457 | } `json:"frame"` |
| 458 | } `json:"params"` |
| 459 | } |
| 460 | if json.Unmarshal(msg[:len(msg)-1], &reply) != nil { |
| 461 | continue |
| 462 | } |
| 463 | if reply.Method != "" { |
| 464 | b.mu.Lock() |
| 465 | b.events = append(b.events, strings.TrimSpace(reply.Method+" "+reply.Params.Frame.URL+" "+reply.Params.Frame.ParentID)) |
| 466 | b.mu.Unlock() |
| 467 | } |
| 468 | if reply.Method == "Page.frameNavigated" && reply.Params.Frame.ParentID == "" { |
| 469 | b.mu.Lock() |
| 470 | b.url = reply.Params.Frame.URL |
| 471 | b.mu.Unlock() |
| 472 | } |
| 473 | if reply.ID == 0 { |
| 474 | continue |
| 475 | } |
| 476 | b.mu.Lock() |
| 477 | c := b.replies[reply.ID] |
| 478 | delete(b.replies, reply.ID) |
| 479 | b.mu.Unlock() |
| 480 | if c != nil { |
| 481 | if reply.Error != nil { |
| 482 | c <- append(json.RawMessage(`{"error":`), append(reply.Error, '}')...) |
| 483 | } else { |
| 484 | c <- reply.Result |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | }() |
| 489 | return b |
| 490 | } |
| 491 | |
| 492 | func tail(s string, n int) string { |
| 493 | lines := strings.Split(s, "\n") |
| 494 | if len(lines) > n { |
| 495 | lines = lines[len(lines)-n:] |
| 496 | } |
| 497 | return strings.Join(lines, "\n") |
| 498 | } |
| 499 | |
| 500 | // send sends one command, in session when it is not "", and waits for its |
| 501 | // result. |
| 502 | func (b *browser) send(t *testing.T, session, method string, params any) json.RawMessage { |
| 503 | t.Helper() |
| 504 | result, ok := b.sendWithin(t, session, method, params, 30*time.Second) |
| 505 | if !ok { |
| 506 | t.Fatalf("%s had no answer", method) |
| 507 | } |
| 508 | return result |
| 509 | } |
| 510 | |
| 511 | // sendWithin is send, waiting at most d for the result, and false when |
| 512 | // none came. |
| 513 | func (b *browser) sendWithin(t *testing.T, session, method string, params any, d time.Duration) (json.RawMessage, bool) { |
| 514 | t.Helper() |
| 515 | b.mu.Lock() |
| 516 | b.next++ |
| 517 | id := b.next |
| 518 | c := make(chan json.RawMessage, 1) |
| 519 | b.replies[id] = c |
| 520 | msg := map[string]any{"id": id, "method": method} |
| 521 | if params != nil { |
| 522 | msg["params"] = params |
| 523 | } |
| 524 | if session != "" { |
| 525 | msg["sessionId"] = session |
| 526 | } |
| 527 | data, _ := json.Marshal(msg) |
| 528 | _, err := b.in.Write(append(data, 0)) |
| 529 | b.mu.Unlock() |
| 530 | if err != nil { |
| 531 | t.Fatalf("sending %s: %v", method, err) |
| 532 | } |
| 533 | select { |
| 534 | case result := <-c: |
| 535 | if strings.HasPrefix(string(result), `{"error":`) { |
| 536 | t.Fatalf("%s failed: %s", method, redacted(string(result))) |
| 537 | } |
| 538 | return result, true |
| 539 | case <-time.After(d): |
| 540 | return nil, false |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | // tab is one page of the browser, attached to its own session. |
| 545 | type tab struct { |
| 546 | b *browser |
| 547 | session string |
| 548 | } |
| 549 | |
| 550 | func (b *browser) page(t *testing.T) *tab { |
| 551 | t.Helper() |
| 552 | var target struct{ TargetID string } |
| 553 | json.Unmarshal(b.send(t, "", "Target.createTarget", map[string]any{"url": "about:blank"}), &target) |
| 554 | var attached struct{ SessionID string } |
| 555 | json.Unmarshal(b.send(t, "", "Target.attachToTarget", map[string]any{"targetId": target.TargetID, "flatten": true}), &attached) |
| 556 | return &tab{b, attached.SessionID} |
| 557 | } |
| 558 | |
| 559 | func (p *tab) call(t *testing.T, method string, params any) json.RawMessage { |
| 560 | t.Helper() |
| 561 | return p.b.send(t, p.session, method, params) |
| 562 | } |
| 563 | |
| 564 | func (p *tab) decode(t *testing.T, data json.RawMessage, v any) { |
| 565 | t.Helper() |
| 566 | if err := json.Unmarshal(data, v); err != nil { |
| 567 | t.Fatal(err) |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | // eval is the value of a JavaScript expression in the page. It runs as |
| 572 | // the automation endpoint's, not as one of the page's scripts. |
| 573 | func (p *tab) eval(t *testing.T, expression string) any { |
| 574 | t.Helper() |
| 575 | v, ok := p.evalWithin(t, expression, 30*time.Second) |
| 576 | if !ok { |
| 577 | t.Fatalf("Runtime.evaluate of %s had no answer", expression) |
| 578 | } |
| 579 | return v |
| 580 | } |
| 581 | |
| 582 | // evalWithin is eval, waiting at most d for the answer, and false when |
| 583 | // none came. |
| 584 | func (p *tab) evalWithin(t *testing.T, expression string, d time.Duration) (any, bool) { |
| 585 | t.Helper() |
| 586 | var r struct { |
| 587 | Result struct { |
| 588 | Value any `json:"value"` |
| 589 | } `json:"result"` |
| 590 | Exception json.RawMessage `json:"exceptionDetails"` |
| 591 | } |
| 592 | result, ok := p.b.sendWithin(t, p.session, "Runtime.evaluate", map[string]any{"expression": expression, "returnByValue": true}, d) |
| 593 | if !ok { |
| 594 | return nil, false |
| 595 | } |
| 596 | p.decode(t, result, &r) |
| 597 | if r.Exception != nil { |
| 598 | return nil, true |
| 599 | } |
| 600 | return r.Result.Value, true |
| 601 | } |
| 602 | |
| 603 | func (p *tab) until(t *testing.T, what string, cond func() bool) { |
| 604 | t.Helper() |
| 605 | for range 200 { |
| 606 | if cond() { |
| 607 | return |
| 608 | } |
| 609 | time.Sleep(50 * time.Millisecond) |
| 610 | } |
| 611 | t.Fatalf("%s: not within ten seconds", what) |
| 612 | } |
| 613 | |
| 614 | func jsString(s string) string { |
| 615 | data, _ := json.Marshal(s) |
| 616 | return string(data) |
| 617 | } |