gunk-dev/the-valley

browser_test.go

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