diff --git a/go.mod b/go.mod index 2782f31bf..78c19a420 100644 --- a/go.mod +++ b/go.mod @@ -40,7 +40,7 @@ require ( github.com/projectdiscovery/rod v0.116.3-0.20261113214723-dd0abeca2a24 github.com/projectdiscovery/tlsx v1.5.0 github.com/projectdiscovery/useragent v0.0.110 - github.com/projectdiscovery/utils v0.11.13 + github.com/projectdiscovery/utils v0.11.17-0.20261122142141-bb5b328c030e github.com/projectdiscovery/wappalyzergo v0.3.8 github.com/rs/xid v1.6.0 github.com/seh-msft/burpxml v1.0.1 @@ -122,7 +122,7 @@ require ( github.com/projectdiscovery/govaluate v0.0.0-20260504230327-80320480bb6e // indirect github.com/projectdiscovery/jarm-go v0.0.0-20260910160638-430e2bae86f6 // indirect github.com/projectdiscovery/machineid v0.0.0-20250715113114-c77eb3567582 // indirect - github.com/projectdiscovery/retryabledns v1.0.118 // indirect + github.com/projectdiscovery/retryabledns v1.0.119 // indirect github.com/refraction-networking/utls v1.8.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect diff --git a/go.sum b/go.sum index e673d859e..e76bda8f1 100644 --- a/go.sum +++ b/go.sum @@ -263,8 +263,8 @@ github.com/projectdiscovery/ratelimit v0.0.95 h1:/vwnXSuVz9di/nJ2x/ebX9d1Hd320nU github.com/projectdiscovery/ratelimit v0.0.95/go.mod h1:QCzQMpdcjlXZNhfy1UJFp6vdPk2E3DaGKxKhFZ3dI48= github.com/projectdiscovery/rawhttp v0.3.1 h1:utudlS3qCAZYa+DU+WK0Q0uuiUxgYXfLwxWIs9dd1Bc= github.com/projectdiscovery/rawhttp v0.3.1/go.mod h1:ezbLgLuzFC3EunY4OqptRunQb6QUM7z78gOBL8DrWYY= -github.com/projectdiscovery/retryabledns v1.0.118 h1:vrWzUgjRyD5fg2QiPF0boDuSL/QYuoxPftgpYQv2MiQ= -github.com/projectdiscovery/retryabledns v1.0.118/go.mod h1:qHuxflnN8BWWqQ+N+TIe9OTqmaMpE/G2+36chAcFQhg= +github.com/projectdiscovery/retryabledns v1.0.119 h1:QljvfDIQ9qw3qtsgyl3g5dkW87RcpNwIv/tKPvBGgjQ= +github.com/projectdiscovery/retryabledns v1.0.119/go.mod h1:DzJqF5OpIgjSm4fR087gHSDYC05JsTRi1RTbbpvrJo8= github.com/projectdiscovery/retryablehttp-go v1.3.35 h1:u4ZnTMh7ZE46buZRBrFL3Yyk0uCrDudcVOlT/VkDWGU= github.com/projectdiscovery/retryablehttp-go v1.3.35/go.mod h1:+UvjTjyTxKJRfPgm023lb84MjAjpDT3jjs1ZO5KuAIE= github.com/projectdiscovery/rod v0.116.3-0.20261113214723-dd0abeca2a24 h1:Hot/bpOreHagjzK10d939dAzEuiDsbScyz/JQ4OTolA= @@ -275,8 +275,8 @@ github.com/projectdiscovery/tlsx v1.5.0 h1:uYHx4qUdLueWJATbFg2Zw5dVxxFdVwKumAFnW github.com/projectdiscovery/tlsx v1.5.0/go.mod h1:w77xx09yOu6Vsz1q8CKabIMvid4o6rAwahXkNlNnTPY= github.com/projectdiscovery/useragent v0.0.110 h1:hoKpQssbFLSSmK/Vxf/fG/a+PToEYdzLafG7HHbvCAc= github.com/projectdiscovery/useragent v0.0.110/go.mod h1:fOeQ2+nlOJHYuPpnWWrBz5q5dUo7efe/AmvWQdNsLUM= -github.com/projectdiscovery/utils v0.11.13 h1:Mn3/rtyQvtn8XZy0UnVkxbAmn0afbHtWuMHUEztwWSw= -github.com/projectdiscovery/utils v0.11.13/go.mod h1:TJgsyVjB02CavwZVFzUzPg6YOSJXQxLhL808JCiQKlU= +github.com/projectdiscovery/utils v0.11.17-0.20261122142141-bb5b328c030e h1:r7kW/SSqI7w3Y2t7zVMOLsv2nad6Rc21kG6p1beXUWs= +github.com/projectdiscovery/utils v0.11.17-0.20261122142141-bb5b328c030e/go.mod h1:xi8KJ+NENlIk4sgfnvihJdcR+4qnEO5Z67fvN5Md33w= github.com/projectdiscovery/wappalyzergo v0.3.8 h1:bjQ99Lanzj8l+2ENwt24/LdZ09uR9IxkamXssBXahIQ= github.com/projectdiscovery/wappalyzergo v0.3.8/go.mod h1:7gTNIjQSXsVmFDJJ3PT8+FhYE+dv6hZLGZSsRAEjVSw= github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo= diff --git a/runner/headless.go b/runner/headless.go index fbe821cef..b155fb2d4 100644 --- a/runner/headless.go +++ b/runner/headless.go @@ -1,21 +1,27 @@ package runner import ( + "context" "fmt" + "maps" "net/url" "os" "path/filepath" + "slices" "strconv" "strings" "time" "github.com/pkg/errors" "github.com/projectdiscovery/fastdialer/fastdialer" + "github.com/projectdiscovery/gologger" "github.com/projectdiscovery/networkpolicy" "github.com/projectdiscovery/rod" "github.com/projectdiscovery/rod/lib/launcher" "github.com/projectdiscovery/rod/lib/launcher/flags" "github.com/projectdiscovery/rod/lib/proto" + rodutils "github.com/projectdiscovery/rod/lib/utils" + "github.com/projectdiscovery/utils/chromeshell" fileutil "github.com/projectdiscovery/utils/file" iputil "github.com/projectdiscovery/utils/ip" mapsutil "github.com/projectdiscovery/utils/maps" @@ -103,6 +109,12 @@ func pathGlobExists(root string, patterns []string) bool { } func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*Browser, error) { + return newBrowser(proxy, proxy, useLocal, optionalArgs) +} + +// newBrowser is NewBrowser with a separate proxy for the chrome-headless-shell +// download. An empty downloadProxy uses the environment proxy. +func newBrowser(proxy, downloadProxy string, useLocal bool, optionalArgs map[string]string) (*Browser, error) { dataStore, err := os.MkdirTemp("", "nuclei-*") if err != nil { return nil, errors.Wrap(err, "could not create temporary directory") @@ -121,7 +133,31 @@ func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*B Set("window-size", fmt.Sprintf("%d,%d", 1080, 1920)). Set("mute-audio", "true"). Set("incognito", "true"). + // Performance: keep background/occluded tabs running at full speed so + // many concurrent screenshot pages don't get render-throttled. + Set("disable-background-timer-throttling", "true"). + Set("disable-backgrounding-occluded-windows", "true"). + Set("disable-renderer-backgrounding", "true"). + Set("disable-hang-monitor", "true"). + // Performance: strip background chrome services we never use. + Set("disable-background-networking", "true"). + Set("disable-client-side-phishing-detection", "true"). + Set("disable-component-update", "true"). + Set("disable-default-apps", "true"). + Set("disable-domain-reliability", "true"). + Set("disable-extensions", "true"). + Set("disable-sync", "true"). + Set("no-first-run", "true"). + Set("no-default-browser-check", "true"). + Set("metrics-recording-only", "true"). + Set("safebrowsing-disable-auto-update", "true"). + // site-per-process stays enabled: screenshots render untrusted pages, so + // Chromium's cross-origin renderer isolation is worth the extra processes. + Set("disable-features", "Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints"). Delete("use-mock-keychain"). + // rod disables IPC flooding protection by default; keep it on because + // untrusted pages share one browser process and must not starve each other. + Delete("disable-ipc-flooding-protection"). Headless(true). UserDataDir(dataStore) @@ -130,12 +166,22 @@ func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*B } // go-rod downloads a glibc Chromium, which cannot run on a musl host. + usingChromeShell := false if preferSystemBrowser(useLocal) { if chromePath, hasChrome := launcher.LookPath(); hasChrome { chromeLauncher.Bin(chromePath) } else { return nil, errors.New("the chrome browser is not installed") } + } else if chromeshell.Supported() { + // Prefer chrome-headless-shell on linux/amd64: smaller download and + // faster headless screenshots than full Chromium snapshots. + if shellPath, err := ensureChromeShell(downloadProxy); err == nil { + chromeLauncher.Bin(shellPath) + usingChromeShell = true + } else { + gologger.Warning().Msgf("Could not prepare chrome-headless-shell, using the default browser: %s\n", err) + } } if proxy == "" { @@ -155,6 +201,13 @@ func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*B } launcherURL, err := chromeLauncher.Launch() + if err != nil && usingChromeShell { + // A damaged cached shell must not disable screenshots: retry once with + // the rod default browser and the same flags. + gologger.Warning().Msgf("Could not launch chrome-headless-shell, using the default browser: %s\n", err) + chromeLauncher = defaultBrowserLauncher(chromeLauncher) + launcherURL, err = chromeLauncher.Launch() + } if err != nil { return nil, err } @@ -181,7 +234,7 @@ func (b *Browser) SetNetworkPolicy(np *networkpolicy.NetworkPolicy, dialer *fast } func (b *Browser) ScreenshotWithBody(url string, timeout time.Duration, idle time.Duration, headers []string, fullPage bool, jsCodes []string) ([]byte, string, []NetworkRequest, error) { - page, router, networkRequests, err := b.setupPageAndNavigate(url, timeout, headers, jsCodes) + page, router, networkRequests, err := b.setupPageAndNavigate(url, timeout, idle, headers, jsCodes) if router != nil { defer func() { _ = router.Stop() }() } @@ -190,7 +243,7 @@ func (b *Browser) ScreenshotWithBody(url string, timeout time.Duration, idle tim } defer b.closePage(page) - screenshot, body, err := b.takeScreenshotAndGetBody(page, idle, fullPage) + screenshot, body, err := b.takeScreenshotAndGetBody(page, fullPage) if err != nil { return nil, "", networkRequests, err } @@ -199,7 +252,7 @@ func (b *Browser) ScreenshotWithBody(url string, timeout time.Duration, idle tim } // setupPageAndNavigate opens a page, performs all adaptive actions including JS injection -func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, headers []string, jsCodes []string) (*rod.Page, *rod.HijackRouter, []NetworkRequest, error) { +func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, idle time.Duration, headers []string, jsCodes []string) (*rod.Page, *rod.HijackRouter, []NetworkRequest, error) { page, err := b.engine.Page(proto.TargetCreateTarget{}) if err != nil { return nil, nil, []NetworkRequest{}, err @@ -276,6 +329,17 @@ func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, header } page = page.Timeout(timeout) + // The readiness waits stop early enough to leave time for the capture, + // so a request that never ends delays the screenshot but does not fail it. + readyCtx, cancelReady := context.WithTimeout(page.GetContext(), timeout-timeout/4) + defer cancelReady() + var waitReqIdle func(context.Context) + if idle > 0 { + // Register before Navigate so the first SPA XHRs are tracked by the + // request-idle waiter. Zero/negative idle skips this (the idle waiter + // and WaitDOMStable reject non-positive durations). + waitReqIdle = waitRequestIdle(page, idle) + } if err := page.Navigate(url); err != nil { return page, router, snapshot(networkRequests), err @@ -288,7 +352,7 @@ func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, header } } - page.Timeout(5 * time.Second).WaitNavigation(proto.PageLifecycleEventNameFirstMeaningfulPaint)() + b.waitPageReady(page.Context(readyCtx), idle, waitReqIdle) return page, router, snapshot(networkRequests), nil } @@ -439,14 +503,103 @@ func mergeRequestHeaders(existing proto.NetworkHeaders, extra map[string]string) return out } -// takeScreenshotAndGetBody performs the screenshot actions -func (b *Browser) takeScreenshotAndGetBody(page *rod.Page, idle time.Duration, fullPage bool) ([]byte, string, error) { - if err := page.WaitLoad(); err != nil { - return nil, "", err +// waitPageReady blocks until the page is visually settled so we don't capture a +// half-rendered SPA. It gates on three independent signals, each bounded by the +// page timeout: +// - window.onload +// - network request-idle (a quiet network window) +// - DOM stability (the rendered tree stops mutating) +// +// SPAs paint late: the network can briefly go quiet before hydration starts, so +// request-idle alone can fire on the boot screen. Requiring DOM stability on top +// closes that gap. DOM stability is re-checked after the network settles so the +// first snapshot is taken post-hydration rather than on the boot screen. +func (b *Browser) waitPageReady(page *rod.Page, idle time.Duration, waitReqIdle func(context.Context)) { + _ = page.WaitLoad() + if idle <= 0 || waitReqIdle == nil { + return + } + waitReqIdle(page.GetContext()) + _ = page.WaitDOMStable(idle, 0) +} + +// idleIgnoredTypes are the request types that do not delay the screenshot, +// the same as the defaults of rod's WaitRequestIdle. +var idleIgnoredTypes = []proto.NetworkResourceType{ + proto.NetworkResourceTypeWebSocket, + proto.NetworkResourceTypeEventSource, + proto.NetworkResourceTypeMedia, + proto.NetworkResourceTypeImage, + proto.NetworkResourceTypeFont, +} + +// waitRequestIdle starts tracking the page requests and returns a function +// that blocks until no tracked request was pending for d, or until its +// context ends. It is rod's WaitRequestIdle without the requests that have +// no loader: Chrome reports the main script request of a dedicated worker +// on the page session with an empty loader id, but reports its end on the +// worker target, which is not attached. rod would wait for that request +// until the page timeout. +func waitRequestIdle(page *rod.Page, d time.Duration) func(context.Context) { + page, cancel := page.WithCancel() + pending := map[proto.NetworkRequestID]struct{}{} + idle := rodutils.NewIdleCounter(d) + done := func(id proto.NetworkRequestID) { + if _, ok := pending[id]; ok { + delete(pending, id) + idle.Done() + } } - _ = page.WaitIdle(idle) + wait := page.EachEvent(func(e *proto.NetworkRequestWillBeSent) { + if e.LoaderID == "" || slices.Contains(idleIgnoredTypes, e.Type) { + return + } + // a redirect sends the same request id again + if _, ok := pending[e.RequestID]; !ok { + pending[e.RequestID] = struct{}{} + idle.Add() + } + }, func(e *proto.NetworkLoadingFinished) { + done(e.RequestID) + }, func(e *proto.NetworkLoadingFailed) { + done(e.RequestID) + }) + return func(ctx context.Context) { + go func() { + idle.Wait(ctx) + cancel() + }() + wait() + } +} - screenshot, err := page.Screenshot(fullPage, &proto.PageCaptureScreenshot{}) +// defaultBrowserLauncher returns a new launcher with the flags of configured, +// minus the browser binary, so rod launches its default browser. A launcher can +// only be launched once. +func defaultBrowserLauncher(configured *launcher.Launcher) *launcher.Launcher { + fallback := launcher.New() + fallback.Flags = maps.Clone(configured.Flags) + fallback.Delete(flags.Bin) + return fallback +} + +// ensureChromeShell fetches the browser under a deadline. The context has to +// reach the download itself: racing a plain Ensure against a timer would only +// abandon the wait, leaving the transfer running and the shared download lock +// held, so the next caller would block behind it. +func ensureChromeShell(proxy string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), chromeshell.DefaultDownloadTimeout) + defer cancel() + return chromeshell.EnsureWithOptions(ctx, chromeshell.Options{Proxy: proxy}) +} + +// takeScreenshotAndGetBody performs the screenshot actions +func (b *Browser) takeScreenshotAndGetBody(page *rod.Page, fullPage bool) ([]byte, string, error) { + _ = page.WaitRepaint() + + screenshot, err := page.Screenshot(fullPage, &proto.PageCaptureScreenshot{ + OptimizeForSpeed: true, + }) if err != nil { return nil, "", err } diff --git a/runner/headless_screenshot_test.go b/runner/headless_screenshot_test.go new file mode 100644 index 000000000..62ffcf351 --- /dev/null +++ b/runner/headless_screenshot_test.go @@ -0,0 +1,161 @@ +package runner + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +const spaHydratedMarker = "hydrated-ok" + +// spaHTML is a tiny SPA-style page: it paints a boot screen first, then +// fetches /app.js which hydrates #root after a short delay. Early captures +// only contain "boot"; a correct wait must include spaHydratedMarker. +const spaHTML = ` +spa-bench + +
boot
+ +` + +const spaJS = ` +setTimeout(function(){ + document.getElementById("root").textContent = "` + spaHydratedMarker + `"; +}, 80); +` + +func startSPAScreenshotServer(t testing.TB) *httptest.Server { + t.Helper() + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = w.Write([]byte(spaHTML)) + }) + mux.HandleFunc("/app.js", func(w http.ResponseWriter, r *http.Request) { + time.Sleep(50 * time.Millisecond) + w.Header().Set("Content-Type", "application/javascript") + _, _ = w.Write([]byte(spaJS)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv +} + +func newScreenshotBrowser(t testing.TB, useLocal bool) *Browser { + t.Helper() + browser, err := NewBrowser("", useLocal, nil) + if err != nil { + t.Skipf("headless browser unavailable: %v", err) + } + t.Cleanup(browser.Close) + return browser +} + +func captureSPA(t testing.TB, browser *Browser, url string) (screenshot []byte, body string) { + t.Helper() + screenshot, body, _, err := browser.ScreenshotWithBody(url, 15*time.Second, 200*time.Millisecond, nil, false, nil) + if err != nil { + t.Fatalf("screenshot: %v", err) + } + return screenshot, body +} + +func TestScreenshotSPAWaitsForHydration(t *testing.T) { + srv := startSPAScreenshotServer(t) + browser := newScreenshotBrowser(t, false) + + screenshot, body := captureSPA(t, browser, srv.URL) + if len(screenshot) == 0 { + t.Fatal("empty screenshot") + } + if !strings.Contains(body, spaHydratedMarker) { + t.Fatalf("early capture: body missing %q\n%s", spaHydratedMarker, body) + } +} + +func TestScreenshotSPAConcurrentNoEarlyCapture(t *testing.T) { + const workers = 8 + srv := startSPAScreenshotServer(t) + browser := newScreenshotBrowser(t, false) + + var wg sync.WaitGroup + errs := make(chan error, workers) + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + screenshot, body, _, err := browser.ScreenshotWithBody(srv.URL, 15*time.Second, 200*time.Millisecond, nil, false, nil) + if err != nil { + errs <- err + return + } + if len(screenshot) == 0 { + errs <- fmt.Errorf("empty screenshot") + return + } + if !strings.Contains(body, spaHydratedMarker) { + errs <- fmt.Errorf("early capture: body missing %q", spaHydratedMarker) + } + }() + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } +} + +// BenchmarkScreenshotSPA times captures of the local SPA. The base sub-benchmarks +// capture sequentially; the "-parallel" ones capture concurrently on the shared +// browser, which is the workload screenshots run under. +// +// On linux/amd64, /default uses chrome-headless-shell when available and +// /local forces a system Chrome via NewBrowser(..., useLocal=true). Compare: +// +// go test -bench=BenchmarkScreenshotSPA -benchtime=20s -count=5 ./runner +func BenchmarkScreenshotSPA(b *testing.B) { + for _, useLocal := range []bool{false, true} { + name := "default" + if useLocal { + name = "local" + } + b.Run(name, func(b *testing.B) { + srv := startSPAScreenshotServer(b) + browser := newScreenshotBrowser(b, useLocal) + b.ResetTimer() + for i := 0; i < b.N; i++ { + if err := benchCaptureSPA(browser, srv.URL); err != nil { + b.Fatal(err) + } + } + }) + b.Run(name+"-parallel", func(b *testing.B) { + srv := startSPAScreenshotServer(b) + browser := newScreenshotBrowser(b, useLocal) + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + if err := benchCaptureSPA(browser, srv.URL); err != nil { + b.Error(err) + return + } + } + }) + }) + } +} + +func benchCaptureSPA(browser *Browser, url string) error { + screenshot, body, _, err := browser.ScreenshotWithBody(url, 15*time.Second, 200*time.Millisecond, nil, false, nil) + if err != nil { + return fmt.Errorf("screenshot: %w", err) + } + if len(screenshot) == 0 || !strings.Contains(body, spaHydratedMarker) { + return fmt.Errorf("early or empty capture") + } + return nil +} diff --git a/runner/headless_test.go b/runner/headless_test.go index 39e5084db..f15ef2755 100644 --- a/runner/headless_test.go +++ b/runner/headless_test.go @@ -18,6 +18,7 @@ import ( "github.com/projectdiscovery/fastdialer/fastdialer" "github.com/projectdiscovery/networkpolicy" "github.com/projectdiscovery/rod/lib/launcher" + "github.com/projectdiscovery/rod/lib/launcher/flags" "github.com/stretchr/testify/require" ) @@ -235,6 +236,73 @@ func TestScreenshotNetworkPolicySubframesAndWorkers(t *testing.T) { } } +// TestScreenshotWorkerPageIsNotDelayed checks that a page which starts +// dedicated workers is captured once its own requests are done. Chrome reports +// the end of a worker script request only on the worker target. +func TestScreenshotWorkerPageIsNotDelayed(t *testing.T) { + if _, ok := launcher.LookPath(); !ok { + t.Skip("chrome is not installed") + } + + mux := http.NewServeMux() + mux.HandleFunc("/worker.js", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/javascript") + _, _ = fmt.Fprint(w, "fetch('/from-worker').catch(function(){})") + }) + mux.HandleFunc("/from-worker", func(w http.ResponseWriter, r *http.Request) {}) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + _, _ = fmt.Fprint(w, `

worker-page

`) + }) + target := httptest.NewServer(mux) + defer target.Close() + + browser, err := NewBrowser("", true, nil) + require.NoError(t, err) + defer browser.Close() + + timeout := 10 * time.Second + start := time.Now() + _, body, _, err := browser.ScreenshotWithBody(target.URL+"/", timeout, 200*time.Millisecond, nil, false, nil) + elapsed := time.Since(start) + require.NoError(t, err) + require.Contains(t, body, "worker-page") + require.Less(t, elapsed, timeout/2, "the screenshot waited for the worker script requests") +} + +// TestScreenshotHangingRequestStillCaptures checks that a request that never +// ends delays the screenshot but does not make it fail. +func TestScreenshotHangingRequestStillCaptures(t *testing.T) { + if _, ok := launcher.LookPath(); !ok { + t.Skip("chrome is not installed") + } + + release := make(chan struct{}) + mux := http.NewServeMux() + mux.HandleFunc("/hang", func(w http.ResponseWriter, r *http.Request) { + select { + case <-release: + case <-r.Context().Done(): + } + }) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + _, _ = fmt.Fprint(w, `

hanging-page

`) + }) + target := httptest.NewServer(mux) + defer target.Close() + defer close(release) + + browser, err := NewBrowser("", true, nil) + require.NoError(t, err) + defer browser.Close() + + screenshot, body, _, err := browser.ScreenshotWithBody(target.URL+"/", 4*time.Second, 200*time.Millisecond, nil, false, nil) + require.NoError(t, err) + require.NotEmpty(t, screenshot) + require.Contains(t, body, "hanging-page") +} + func TestPreferSystemBrowser(t *testing.T) { require.True(t, preferSystemBrowser(true)) @@ -337,3 +405,19 @@ func pathExists(path string) bool { _, err := os.Stat(path) return err == nil } + +func TestDefaultBrowserLauncherKeepsFlagsWithoutBin(t *testing.T) { + configured := launcher.New(). + Bin("/cache/chrome-headless-shell"). + Set("disable-sync", "true"). + Delete("disable-ipc-flooding-protection"). + Proxy("http://127.0.0.1:8080") + + fallback := defaultBrowserLauncher(configured) + + require.False(t, fallback.Has(flags.Bin)) + require.Equal(t, "true", fallback.Get("disable-sync")) + require.Equal(t, "http://127.0.0.1:8080", fallback.Get(flags.ProxyServer)) + require.False(t, fallback.Has("disable-ipc-flooding-protection")) + require.Equal(t, "/cache/chrome-headless-shell", configured.Get(flags.Bin)) +} diff --git a/runner/runner.go b/runner/runner.go index 43c536f6d..9cd876b89 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -380,7 +380,8 @@ func New(options *Options) (*Runner, error) { scanopts.MaxResponseBodySizeToRead = options.MaxResponseBodySizeToRead scanopts.extractRegexps = make(map[string]*regexp.Regexp) if options.Screenshot { - browser, err := NewBrowser(options.HTTPProxy, options.UseInstalledChrome, options.ParseHeadlessOptionalArguments()) + // The browser download goes through -proxy / -http-proxy too. + browser, err := newBrowser(options.HTTPProxy, options.Proxy, options.UseInstalledChrome, options.ParseHeadlessOptionalArguments()) if err != nil { return nil, err }