gunk-dev/the-valley

browser_test.go

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