package remotebrowser import ( "bytes" "context" "errors" "image" "image/color" "image/jpeg" "image/png" "io" "net" "net/http" "net/http/httptest" "net/url" "os" "sync" "sync/atomic" "testing" "time" "github.com/go-rod/rod" "github.com/go-rod/rod/lib/launcher" "github.com/go-rod/rod/lib/proto" "github.com/phishingclub/phishingclub/errs" ) // findChromeBin returns a chrome/chromium binary path, or "" if none is // installed. TEST_CHROME_BIN wins when set. Shared by every test that needs a // real browser. func findChromeBin() string { if bin := os.Getenv("TEST_CHROME_BIN"); bin != "" { return bin } for _, cand := range []string{"/usr/bin/google-chrome", "/usr/bin/chromium-browser", "/usr/bin/chromium"} { if _, err := os.Stat(cand); err == nil { return cand } } return "" } // TestRenderPDFRoutesThroughGuard drives the PDF render a report uses, NewSession // and RenderPDF, and asserts that a report embedding a loopback resource cannot // reach it. It catches removal of the guard wiring from the real render path, // not just flag drift. Skips without a browser. The produced PDF is the // positive control that the render actually ran. func TestRenderPDFRoutesThroughGuard(t *testing.T) { bin := findChromeBin() if bin == "" { t.Skip("no chrome/chromium binary available") } var hits int var mu sync.Mutex victim := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() hits++ mu.Unlock() })) defer victim.Close() html := `Report` ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() s, err := NewSession(ctx, bin) if err != nil { t.Fatalf("new session: %v", err) } defer s.Close() pdf, err := s.RenderPDF(html, PDFOptions{}) if err != nil { t.Fatalf("render: %v", err) } if len(pdf) == 0 { t.Fatalf("no PDF produced; render did not run so the guard was not exercised") } mu.Lock() defer mu.Unlock() if hits != 0 { t.Fatalf("loopback resource reached %d times through RenderPDF; guard wiring missing", hits) } } // startAllowAllProxy is a permissive forward proxy used only to isolate the flag // behavior from the guard policy: it forwards everything (including loopback). func startAllowAllProxy(t *testing.T) (string, func()) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("listen: %v", err) } tr := &http.Transport{} h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodConnect { upstream, err := net.DialTimeout("tcp", r.Host, 5*time.Second) if err != nil { http.Error(w, "", http.StatusBadGateway) return } client, _, err := w.(http.Hijacker).Hijack() if err != nil { _ = upstream.Close() return } _, _ = client.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) go func() { _, _ = io.Copy(upstream, client); _ = upstream.Close() }() _, _ = io.Copy(client, upstream) _ = client.Close() return } out := r.Clone(r.Context()) out.RequestURI = "" resp, err := tr.RoundTrip(out) if err != nil { http.Error(w, "", http.StatusBadGateway) return } defer resp.Body.Close() for k, vs := range resp.Header { for _, v := range vs { w.Header().Add(k, v) } } w.WriteHeader(resp.StatusCode) _, _ = io.Copy(w, resp.Body) }) srv := &http.Server{Handler: h} go func() { _ = srv.Serve(ln) }() return ln.Addr().String(), func() { _ = srv.Close() } } // TestNormalResourcesLoadWithProductionFlags is a smoke test: it confirms Chrome // launches with the full production flag set (including --disable-quic and the // WebRTC policy) and can still fetch a normal proxied resource, and that // proxy-bypass-list=<-loopback> correctly routes even loopback through the proxy. // It exercises the plain HTTP forward path, not the https/QUIC negotiation path, // so it does not by itself prove QUIC fallback; that rests on the reasoning that // QUIC is only ever reached after a TCP connection and always has a TCP fallback. // Skips when no browser is present. func TestNormalResourcesLoadWithProductionFlags(t *testing.T) { bin := "" for _, cand := range []string{"/usr/bin/google-chrome", "/usr/bin/chromium-browser", "/usr/bin/chromium"} { if _, err := os.Stat(cand); err == nil { bin = cand break } } if bin == "" { t.Skip("no chrome/chromium binary available") } var hits int var mu sync.Mutex res := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() hits++ mu.Unlock() w.Header().Set("Content-Type", "image/gif") // 1x1 gif so the browser treats it as a real successful image load w.Write([]byte{0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b}) })) defer res.Close() proxyAddr, closeProxy := startAllowAllProxy(t) defer closeProxy() // the real production flag set, via the shared helper, plus the PNA check // disables so the fetch is attributable to the flags rather than a masking // browser feature. l := applyGuardFlags( launcher.New().Bin(bin).Headless(true). Set("no-sandbox").Set("disable-gpu").Set("disable-dev-shm-usage"), proxyAddr, ). Set("disable-features", "PrivateNetworkAccessChecks,LocalNetworkAccessChecks,BlockInsecurePrivateNetworkRequests") u, err := l.Launch() if err != nil { t.Fatalf("launch: %v", err) } defer l.Cleanup() browser := rod.New().ControlURL(u) if err := browser.Connect(); err != nil { t.Fatalf("connect: %v", err) } defer browser.Close() pg := browser.MustPage() _ = pg.SetDocumentContent(``) deadline := time.Now().Add(8 * time.Second) for func() int { mu.Lock(); defer mu.Unlock(); return hits }() == 0 && time.Now().Before(deadline) { time.Sleep(100 * time.Millisecond) } pg.Close() mu.Lock() defer mu.Unlock() if hits == 0 { t.Fatalf("normal http resource did not load with the production flags (disable-quic may have broken fetching)") } } // TestBrowserLimiterCapsAndQueues checks that only the set number of slots are // handed out and that a waiter gets a slot as soon as one is given back. func TestBrowserLimiterCapsAndQueues(t *testing.T) { b := newBrowserLimiter(2) ctx := context.Background() r1, err := b.acquire(ctx) if err != nil { t.Fatal(err) } r2, err := b.acquire(ctx) if err != nil { t.Fatal(err) } got := make(chan func(), 1) go func() { r, err := b.acquire(ctx) if err != nil { t.Error(err) return } got <- r }() select { case <-got: t.Fatal("a third slot was handed out while two were taken") case <-time.After(50 * time.Millisecond): } r1() // giving a slot back twice must not free a second slot r1() select { case r3 := <-got: r3() case <-time.After(2 * time.Second): t.Fatal("the waiter did not get the freed slot") } if len(b.slots) != 1 { t.Fatalf("slots in use = %d, want 1", len(b.slots)) } r2() if len(b.slots) != 0 { t.Fatalf("slots in use = %d, want 0", len(b.slots)) } } // TestBrowserLimiterContext checks that a waiter gives up when its context // times out or is cancelled, with an error the controllers show to the user. func TestBrowserLimiterContext(t *testing.T) { b := newBrowserLimiter(1) release, err := b.acquire(context.Background()) if err != nil { t.Fatal(err) } defer release() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) defer cancel() start := time.Now() _, err = b.acquire(ctx) var opErr errs.OperationalError if !errors.As(err, &opErr) { t.Fatalf("timeout error = %v, want an OperationalError", err) } if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("timeout error = %v, want it to wrap the deadline", err) } if time.Since(start) > time.Second { t.Fatal("the waiter did not give up at its deadline") } cctx, ccancel := context.WithCancel(context.Background()) done := make(chan error, 1) go func() { _, err := b.acquire(cctx) done <- err }() ccancel() select { case err := <-done: if !errors.As(err, &opErr) || !errors.Is(err, context.Canceled) { t.Fatalf("cancel error = %v, want a cancelled OperationalError", err) } case <-time.After(2 * time.Second): t.Fatal("the waiter did not give up when cancelled") } if len(b.slots) != 1 { t.Fatalf("slots in use = %d, want 1", len(b.slots)) } } // TestBrowserLimiterReserve checks that a reserved slot is used by the session // started with its context, so the session does not wait for a second slot, // and that the time limit set after the reservation does not count the wait. func TestBrowserLimiterReserve(t *testing.T) { b := newBrowserLimiter(1) other, err := b.acquire(context.Background()) if err != nil { t.Fatal(err) } type reserved struct { ctx context.Context release func() } got := make(chan reserved, 1) go func() { ctx, release, err := b.reserve(context.Background(), false) if err != nil { t.Error(err) return } got <- reserved{ctx, release} }() // the reservation waits in line behind the slot in use time.Sleep(50 * time.Millisecond) other() var r reserved select { case r = <-got: case <-time.After(2 * time.Second): t.Fatal("the reservation did not get the freed slot") } // a short time limit made after the reservation still gets the slot at once ctx, cancel := context.WithTimeout(r.ctx, 50*time.Millisecond) defer cancel() inner, err := b.acquire(ctx) if err != nil { t.Fatalf("session on a reserved slot: %v", err) } // the reserved slot is in use, a second session waits and times out if _, err := b.acquire(ctx); err == nil { t.Fatal("a second session took the reserved slot that was in use") } inner() // after the session closes the reserved slot can be used again again, err := b.acquire(r.ctx) if err != nil { t.Fatalf("reserved slot after close: %v", err) } again() if len(b.slots) != 1 { t.Fatalf("slots in use = %d, want 1", len(b.slots)) } r.release() if len(b.slots) != 0 { t.Fatalf("slots in use = %d, want 0", len(b.slots)) } } // TestBrowserLimiterReserveReleased checks that a reservation can not be used // after it is given back: a session started with its context waits for a new // slot instead of running without one func TestBrowserLimiterReserveReleased(t *testing.T) { b := newBrowserLimiter(1) ctx, release, err := b.reserve(context.Background(), false) if err != nil { t.Fatal(err) } release() if len(b.slots) != 0 { t.Fatalf("slots in use = %d, want 0", len(b.slots)) } // the context still carries the reservation, it must take a real slot inner, err := b.acquire(ctx) if err != nil { t.Fatalf("session after release: %v", err) } if len(b.slots) != 1 { t.Fatalf("slots in use = %d, want 1, a released reservation was reused", len(b.slots)) } // with that slot taken a second session waits and times out short, cancel := context.WithTimeout(ctx, 50*time.Millisecond) defer cancel() if _, err := b.acquire(short); err == nil { t.Fatal("a released reservation handed out a slot") } inner() // a second release does nothing release() if len(b.slots) != 0 { t.Fatalf("slots in use = %d, want 0", len(b.slots)) } } // TestBrowserLimiterReserveOneSession checks that a one session reservation // gives its slot back when the session on it closes, before release func TestBrowserLimiterReserveOneSession(t *testing.T) { b := newBrowserLimiter(1) ctx, release, err := b.reserve(context.Background(), true) if err != nil { t.Fatal(err) } defer release() inner, err := b.acquire(ctx) if err != nil { t.Fatalf("session on the reservation: %v", err) } if len(b.slots) != 1 { t.Fatalf("slots in use = %d, want 1", len(b.slots)) } inner() if len(b.slots) != 0 { t.Fatalf("slots in use after the session closed = %d, want 0", len(b.slots)) } // another caller gets the slot while the reserving work goes on other, err := b.acquire(context.Background()) if err != nil { t.Fatal(err) } // the closing release does not free the slot the other caller holds release() if len(b.slots) != 1 { t.Fatalf("slots in use = %d, want 1", len(b.slots)) } other() } func newTestSession(t *testing.T) *Session { t.Helper() bin := findChromeBin() if bin == "" { t.Skip("no chrome/chromium binary available") } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) t.Cleanup(cancel) s, err := NewSession(ctx, bin) if err != nil { t.Fatalf("new session: %v", err) } t.Cleanup(s.Close) return s } func testCaptureOptions() CaptureOptions { return CaptureOptions{Width: 400, Height: 300, MaxHeight: 1000, Timeout: 10 * time.Second} } func decodeJPEG(t *testing.T, data []byte) image.Image { t.Helper() img, err := jpeg.Decode(bytes.NewReader(data)) if err != nil { t.Fatalf("capture is not a JPEG: %v", err) } return img } // isRed reports whether the pixel at x, y is close to pure red. The pages in // these tests are red only while they still show their own content. Callers // sample away from the top left corner, where text is drawn. func isRed(img image.Image, x, y int) bool { r, g, b, _ := img.At(x, y).RGBA() return r>>8 > 200 && g>>8 < 60 && b>>8 < 60 } const redBody = `` func TestCaptureRoutesThroughGuard(t *testing.T) { s := newTestSession(t) var hits int var mu sync.Mutex victim := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() hits++ mu.Unlock() })) defer victim.Close() shot, err := s.Capture(`Report`, testCaptureOptions()) if err != nil { t.Fatalf("capture: %v", err) } decodeJPEG(t, shot) mu.Lock() defer mu.Unlock() if hits != 0 { t.Fatalf("loopback resource reached %d times through Capture; guard wiring missing", hits) } // positive control: the image request reached the guard and was refused there if s.captureBlocked.Load() == 0 { t.Fatalf("the guard refused nothing, the request did not go through it") } } func TestSessionCapturesAndRendersPDFOnOneLaunch(t *testing.T) { s := newTestSession(t) shot, err := s.Capture(`Email`, testCaptureOptions()) if err != nil { t.Fatalf("capture: %v", err) } decodeJPEG(t, shot) pdf, err := s.RenderPDF(`Report`, PDFOptions{}) if err != nil { t.Fatalf("render pdf: %v", err) } if len(pdf) == 0 { t.Fatalf("no PDF produced") } } func TestCaptureKeepsPageWhenItRedirects(t *testing.T) { s := newTestSession(t) pages := map[string]string{ "script": `` + redBody + ``, "meta": `` + redBody + ``, "form": `` + redBody + `
`, "delayed": `` + redBody + ``, } for name, html := range pages { t.Run(name, func(t *testing.T) { shot, err := s.Capture(html, testCaptureOptions()) if err != nil { t.Fatalf("capture: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("page navigated away before the capture") } }) } } func TestCaptureDismissesDialogs(t *testing.T) { s := newTestSession(t) html := `` + redBody + `` shot, err := s.Capture(html, testCaptureOptions()) if err != nil { t.Fatalf("capture: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("unexpected capture content") } } func TestCaptureStopsStuckScriptAndSessionStillWorks(t *testing.T) { s := newTestSession(t) opts := testCaptureOptions() opts.Timeout = 3 * time.Second start := time.Now() _, err := s.Capture(``, opts) if err == nil { t.Fatalf("expected a timeout error for a stuck script") } if took := time.Since(start); took > 10*time.Second { t.Fatalf("stuck capture took %s, the timeout did not hold", took) } shot, err := s.Capture(``+redBody+`ok`, testCaptureOptions()) if err != nil { t.Fatalf("capture after a stuck page: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("unexpected capture content after a stuck page") } pdf, err := s.RenderPDF(`Report`, PDFOptions{}) if err != nil || len(pdf) == 0 { t.Fatalf("render pdf after a stuck page: %v", err) } } func TestCaptureHeightIsCapped(t *testing.T) { s := newTestSession(t) opts := testCaptureOptions() shot, err := s.Capture(`
`, opts) if err != nil { t.Fatalf("capture: %v", err) } b := decodeJPEG(t, shot).Bounds() if b.Dy() != opts.MaxHeight || b.Dx() != opts.Width { t.Fatalf("capture is %dx%d, want %dx%d", b.Dx(), b.Dy(), opts.Width, opts.MaxHeight) } shot, err = s.Capture(`
`, opts) if err != nil { t.Fatalf("capture: %v", err) } if got := decodeJPEG(t, shot).Bounds().Dy(); got != 600 { t.Fatalf("capture height is %d, want the content height 600", got) } } func TestCaptureCanDisableScripts(t *testing.T) { s := newTestSession(t) html := `` + redBody + `` opts := testCaptureOptions() opts.DisableScripts = true shot, err := s.Capture(html, opts) if err != nil { t.Fatalf("capture: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("script ran although scripts were disabled") } opts.DisableScripts = false shot, err = s.Capture(html, opts) if err != nil { t.Fatalf("capture: %v", err) } if isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("script did not run with scripts enabled") } } func TestCaptureAnswersLocalRequests(t *testing.T) { s := newTestSession(t) var mu sync.Mutex asked := map[string]bool{} opts := testCaptureOptions() opts.Local = func(u *url.URL) (*LocalFile, bool) { mu.Lock() asked[u.String()] = true mu.Unlock() if u.Hostname() != "phish.test" { return nil, false } if u.Path == "/style.css" { return &LocalFile{Body: []byte(`body{background:#ff0000}`), ContentType: "text/css"}, true } return nil, true } // phish.test does not resolve, so the red background can only come from // the local answer html := `` + `` + `` shot, err := s.Capture(html, opts) if err != nil { t.Fatalf("capture: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("local stylesheet was not applied") } mu.Lock() defer mu.Unlock() if !asked["https://phish.test/missing.png"] { t.Fatalf("local was not asked about the image request") } if asked["https://phish.test/frame"] { t.Fatalf("local was asked about a document request, which must get 204") } } func TestCaptureKeepsPageWhenFrameOrPopupNavigates(t *testing.T) { s := newTestSession(t) pages := map[string]string{ "iframe": `` + redBody + ``, "popup": `` + redBody + ``, "blank": `` + redBody + `x`, "stuckpop": `` + redBody + ``, } // the browser starts with one tab of its own, only pages opened by a // capture must be gone afterwards openPages := func() map[proto.TargetTargetID]string { targets, err := proto.TargetGetTargets{}.Call(s.browser) if err != nil { t.Fatalf("list targets: %v", err) } out := map[proto.TargetTargetID]string{} for _, ti := range targets.TargetInfos { if ti.Type == proto.TargetTargetInfoTypePage { out[ti.TargetID] = ti.URL } } return out } for name, html := range pages { t.Run(name, func(t *testing.T) { before := openPages() shot, err := s.Capture(html, testCaptureOptions()) if err != nil { t.Fatalf("capture: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("page changed before the capture") } for id, u := range openPages() { if _, ok := before[id]; !ok { t.Fatalf("a page is still open after the capture: %s", u) } } }) } } func TestCaptureKeepsWindowHeightLayout(t *testing.T) { s := newTestSession(t) html := `` + `
` + `
` + `
` opts := testCaptureOptions() shot, err := s.Capture(html, opts) if err != nil { t.Fatalf("capture: %v", err) } img := decodeJPEG(t, shot) want := 100 + opts.Height + 100 if got := img.Bounds().Dy(); got != want { t.Fatalf("capture height is %d, want %d", got, want) } r, g, b, _ := img.At(200, want-10).RGBA() if !(b>>8 > 200 && r>>8 < 60 && g>>8 < 60) { t.Fatalf("the footer is missing from the capture") } } func TestCaptureRejectsMissingOptions(t *testing.T) { s := newTestSession(t) for _, opts := range []CaptureOptions{ {Height: 300, MaxHeight: 1000, Timeout: time.Second}, {Width: 400, MaxHeight: 1000, Timeout: time.Second}, {Width: 400, Height: 300, Timeout: time.Second}, {Width: 400, Height: 300, MaxHeight: 1000}, } { if _, err := s.Capture(``, opts); err == nil { t.Fatalf("options %+v were accepted", opts) } } } func TestCaptureLocalRequestsNeverReachNetwork(t *testing.T) { s := newTestSession(t) var hits int var mu sync.Mutex victim := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() hits++ mu.Unlock() })) defer victim.Close() victimURL, _ := url.Parse(victim.URL) opts := testCaptureOptions() opts.Local = func(u *url.URL) (*LocalFile, bool) { return nil, u.Host == victimURL.Host } html := `` if _, err := s.Capture(html, opts); err != nil { t.Fatalf("capture: %v", err) } mu.Lock() defer mu.Unlock() // a request that left the browser would have been refused by the guard if hits != 0 || s.captureBlocked.Load() != 0 { t.Fatalf("local requests reached the network: %d hits, %d refused by the guard", hits, s.captureBlocked.Load()) } } func TestCaptureBlocksWebSockets(t *testing.T) { s := newTestSession(t) html := `` if _, err := s.Capture(html, testCaptureOptions()); err != nil { t.Fatalf("capture: %v", err) } // a WebSocket that left the browser would have reached the guard if n := s.captureBlocked.Load(); n != 0 { t.Fatalf("websocket requests reached the guard %d times", n) } } func TestCaptureGuardRefusesLocalHosts(t *testing.T) { s := newTestSession(t) var hits int var mu sync.Mutex victim := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() hits++ mu.Unlock() })) defer victim.Close() victimURL, _ := url.Parse(victim.URL) opts := testCaptureOptions() var asked []string opts.Local = func(u *url.URL) (*LocalFile, bool) { mu.Lock() asked = append(asked, u.Path) mu.Unlock() return nil, u.Host == victimURL.Host } opts.LocalHost = func(host string) bool { return host == victimURL.Hostname() } // a prefetch is made by the browser without asking the Fetch handler html := `Report` if _, err := s.Capture(html, opts); err != nil { t.Fatalf("capture: %v", err) } mu.Lock() defer mu.Unlock() if hits != 0 { t.Fatalf("a local host was reached %d times", hits) } if s.captureBlocked.Load() != 0 { t.Fatalf("a local request reached the address check, %d blocked", s.captureBlocked.Load()) } // positive control: the prefetch reached the guard and was refused there if s.captureRefused.Load() == 0 { t.Fatalf("the guard refused nothing, asked locally for %v", asked) } } func TestCaptureRunsConcurrently(t *testing.T) { s := newTestSession(t) colors := []string{"#ff0000", "#00ff00", "#0000ff", "#ffff00", "#ff00ff", "#00ffff"} shots := make([][]byte, len(colors)) errs := make([]error, len(colors)) var wg sync.WaitGroup for i, c := range colors { wg.Add(1) go func(i int, c string) { defer wg.Done() shots[i], errs[i] = s.Capture(`x`, testCaptureOptions()) }(i, c) } wg.Wait() // each capture shows its own page, none got another one's content for i, c := range colors { if errs[i] != nil { t.Fatalf("capture %d: %v", i, errs[i]) } r, g, b, _ := decodeJPEG(t, shots[i]).At(200, 200).RGBA() got := [3]bool{r>>8 > 200, g>>8 > 200, b>>8 > 200} want := [3]bool{c[1:3] == "ff", c[3:5] == "ff", c[5:7] == "ff"} if got != want { t.Fatalf("capture %d shows the wrong page, want %s", i, c) } } } // testPNG is a small red PNG func testPNG(t *testing.T) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, 40, 40)) for x := 0; x < 40; x++ { for y := 0; y < 40; y++ { img.Set(x, y, color.RGBA{R: 255, A: 255}) } } var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } func TestRenderPDFWaitsForLocalImages(t *testing.T) { s := newTestSession(t) body := testPNG(t) var asked atomic.Int32 // the file is slow, the print must still wait for it local := func(u *url.URL) (*LocalFile, bool) { if u.Hostname() != "phish.test" { return nil, false } asked.Add(1) time.Sleep(1500 * time.Millisecond) return &LocalFile{Body: body, ContentType: "image/png"}, true } html := `Report` pdf, err := s.RenderPDF(html, PDFOptions{Local: local}) if err != nil { t.Fatalf("render: %v", err) } if asked.Load() == 0 { t.Fatalf("local was not asked about the image") } // the 40 by 40 test image, not the smaller broken image icon if !bytes.Contains(pdf, []byte("/Width 40")) { t.Fatalf("the slow local image is not in the PDF") } // phish.test does not resolve, so without the local file the image is // not there pdf, err = s.RenderPDF(html, PDFOptions{}) if err != nil { t.Fatalf("render: %v", err) } if bytes.Contains(pdf, []byte("/Width 40")) { t.Fatalf("an image that can not load is in the PDF") } } func TestCaptureWaitsForTimersAnimationsAndReadyAttribute(t *testing.T) { s := newTestSession(t) cases := map[string]struct { html string wait time.Duration }{ "short timer": {html: ``}, "animation": {html: `
`}, "ready attribute": {html: ``}, "transition end event": {html: `
x
`}, "extra wait": { html: ``, wait: 3 * time.Second, }, } for name, c := range cases { opts := testCaptureOptions() opts.ExtraWait = c.wait shot, err := s.Capture(c.html, opts) if err != nil { t.Fatalf("%s: capture: %v", name, err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Errorf("%s: captured before the page was ready", name) } } } func TestCaptureReadyAttributeNeverSetStillCaptures(t *testing.T) { s := newTestSession(t) opts := testCaptureOptions() opts.ExtraWait = 3 * time.Second opts.Timeout = 10*time.Second + opts.ExtraWait // the page names the attribute but never sets it html := `` + redBody + `` shot, err := s.Capture(html, opts) if err != nil { t.Fatalf("a page that never sets the ready attribute must still be captured: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("unexpected capture content") } } func TestCaptureWidensForWideContent(t *testing.T) { s := newTestSession(t) opts := testCaptureOptions() opts.MaxWidth = 700 html := `
` shot, err := s.Capture(html, opts) if err != nil { t.Fatalf("capture: %v", err) } img := decodeJPEG(t, shot) if img.Bounds().Dx() != 550 || !isRed(img, 520, 50) { t.Fatalf("capture is %d wide, want the content width 550", img.Bounds().Dx()) } // wider than MaxWidth is cut at it, narrower keeps Width shot, err = s.Capture(`
`, opts) if err != nil { t.Fatalf("capture: %v", err) } if got := decodeJPEG(t, shot).Bounds().Dx(); got != 700 { t.Fatalf("capture is %d wide, want MaxWidth 700", got) } shot, err = s.Capture(`x`, opts) if err != nil { t.Fatalf("capture: %v", err) } if got := decodeJPEG(t, shot).Bounds().Dx(); got != opts.Width { t.Fatalf("capture is %d wide, want Width %d", got, opts.Width) } } func TestCaptureWithScriptsOffIsNotSlowed(t *testing.T) { s := newTestSession(t) opts := testCaptureOptions() opts.DisableScripts = true start := time.Now() shot, err := s.Capture(``+redBody+`x`, opts) if err != nil { t.Fatalf("capture: %v", err) } if !isRed(decodeJPEG(t, shot), 200, 200) { t.Fatalf("unexpected capture content") } if took := time.Since(start); took > 2500*time.Millisecond { t.Fatalf("a capture with scripts off took %s", took) } } func TestPrepareCaptureHTML(t *testing.T) { cases := map[string]string{ `x`: `` + captureFreezeStyle + `x`, `

x

`: `` + captureFreezeStyle + `

x

`, `x`: `` + captureFreezeStyle + `x`, `

loading="lazy"

`: captureFreezeStyle + `

loading="lazy"

`, ``: captureFreezeStyle + ``, `
x
`: captureFreezeStyle + `
x
`, } for in, want := range cases { if got := prepareCaptureHTML(in); got != want { t.Errorf("prepareCaptureHTML(%q)\n got %q\nwant %q", in, got, want) } } }