package app import ( "context" "encoding/json" "fmt" "os" "path/filepath" "runtime" "strings" "testing" "time" "github.com/chromedp/chromedp" ) func TestWindowSizeIsStablePerURLAndWithinBounds(t *testing.T) { for _, raw := range []string{"https://a.test/", "https://b.test/x", "https://c.test/y?z=1"} { w1, h1 := windowSize(raw) w2, h2 := windowSize(raw) if w1 != w2 || h1 != h2 { t.Fatalf("windowSize(%q) is not deterministic: %dx%d then %dx%d", raw, w1, h1, w2, h2) } if w1 < 1200 || w1 > 1359 || h1 < 800 || h1 > 959 { t.Fatalf("windowSize(%q) = %dx%d outside the intended range", raw, w1, h1) } } } // The presented identity must belong to the host the browser actually runs on. // Claiming another platform is what bot detection looks for, so the user agent // and navigator.platform must agree with each other and with this host. func TestHostIdentityIsCoherent(t *testing.T) { v := chromeVersion{major: "153"} identity := hostIdentity() ua := chromeUserAgent(v) if !strings.Contains(ua, "Chrome/153.0.0.0 Safari/537.36") { t.Fatalf("user agent does not carry the probed major version: %q", ua) } if strings.Contains(ua, "Headless") { t.Fatalf("user agent announces headless mode: %q", ua) } // The platform claim and the user agent must describe one machine. wantPlatform := hostUserAgentFragment() if wantPlatform == "" { t.Skipf("no identity expectations for %s", runtime.GOOS) } if !strings.Contains(ua, wantPlatform) { t.Fatalf("user agent %q does not describe this %s host (want %q)", ua, runtime.GOOS, wantPlatform) } // macOS reports a real Apple GPU in headless mode, so replacing the WebGL // strings there would contradict the rest of the fingerprint. if identity.platform == "" { t.Fatal("identity has no navigator.platform") } if runtime.GOOS == "darwin" && identity.spoofGPU { t.Fatal("macOS identity spoofs the GPU string over a real Apple GPU") } if runtime.GOOS != "darwin" && !identity.spoofGPU { t.Fatalf("%s identity leaves the SwiftShader renderer string in place", runtime.GOOS) } } // The injected script must not carry the WebGL replacement when the host // reports a real GPU, and must carry it when the host renders through // SwiftShader. func TestStealthSnapshotOmitsGPUPatchesForRealGPUs(t *testing.T) { real := stealthSnapshot(browserIdentity{platform: "MacIntel"}) if strings.Contains(real, "0x9246") { t.Fatal("script patches WebGL for an identity that reports a real GPU") } if !strings.Contains(real, "webdriver") || !strings.Contains(real, "outerHeight") { t.Fatal("script dropped the platform-neutral evasions") } swift := stealthSnapshot(browserIdentity{platform: "Linux x86_64", spoofGPU: true}) if !strings.Contains(swift, "0x9246") { t.Fatal("script left the SwiftShader renderer string in place") } if !strings.Contains(swift, "outerHeight") { t.Fatal("script dropped the trailing evasions") } } // The client-hints metadata override must not come back: forcing Sec-CH-UA-* // headers that a real browser only sends when an origin opts in is what reddit // treated as automation. func TestNoClientHintsOverrideInStealthActions(t *testing.T) { if strings.Contains(stealthTestSource(t), "WithUserAgentMetadata") { t.Fatal("stealth path overrides Sec-CH-UA client hints") } } // hostUserAgentFragment is the part of a Chrome user agent that identifies one // operating system. Tests use it to assert the identity matches the host. func hostUserAgentFragment() string { return map[string]string{ "darwin": "Macintosh; Intel Mac OS X", "windows": "Windows NT 10.0; Win64; x64", "linux": "X11; Linux x86_64", }[runtime.GOOS] } func stealthTestSource(t *testing.T) string { t.Helper() source, err := os.ReadFile("browser.go") if err != nil { t.Fatal(err) } return string(source) } // TestLiveStealthFingerprint asserts real Chrome presents a plausible desktop // browser to page scripts instead of announcing automation. It drives Chrome, // so it is opt-in like the other browser tests. func TestLiveStealthFingerprint(t *testing.T) { if os.Getenv("LIVE_BROWSER") != "1" { t.Skip("set LIVE_BROWSER=1 and BROWSER_PATH to exercise chrome") } if os.Getenv("BROWSER_PATH") == "" { t.Fatal("BROWSER_PATH is required") } for _, stealth := range []bool{true, false} { name := "stealth off" if stealth { name = "stealth on" } t.Run(name, func(t *testing.T) { observed := observeFingerprint(t, stealth) if !stealth { t.Logf("baseline: webdriver=%v ua=%q", observed["webdriver"], observed["userAgent"]) return } if observed["webdriver"] != false { t.Errorf("navigator.webdriver = %v, want false", observed["webdriver"]) } ua, _ := observed["userAgent"].(string) if !strings.Contains(ua, "Chrome/") || strings.Contains(ua, "Headless") { t.Errorf("user agent is not desktop Chrome: %q", ua) } // The user agent must describe the host the browser runs on. if fragment := hostUserAgentFragment(); fragment != "" && !strings.Contains(ua, fragment) { t.Errorf("user agent %q does not describe this %s host (want %q)", ua, runtime.GOOS, fragment) } if observed["vendor"] != "Google Inc." { t.Errorf("navigator.vendor = %v", observed["vendor"]) } if !strings.Contains(fmt.Sprint(observed["webdriverGetter"]), "[native code]") { t.Errorf("webdriver getter does not stringify as native: %v", observed["webdriverGetter"]) } if observed["chromeRuntime"] != true { t.Error("window.chrome.runtime is missing") } rendered, _ := observed["webglRenderer"].(string) if strings.Contains(rendered, "SwiftShader") { t.Errorf("webgl renderer is the software rasterizer: %q", rendered) } if runtime.GOOS == "darwin" && !strings.Contains(rendered, "Apple") { t.Errorf("macOS host does not report its real Apple GPU: %q", rendered) } if runtime.GOOS != "darwin" && !strings.Contains(rendered, "Intel") { t.Errorf("SwiftShader host was not given a desktop adapter string: %q", rendered) } if langs := fmt.Sprint(observed["languages"]); !strings.Contains(langs, "en-US") { t.Errorf("navigator.languages = %v", observed["languages"]) } if plugins, ok := observed["plugins"].(float64); !ok || plugins != 5 { t.Errorf("navigator.plugins.length = %v, want 5", observed["plugins"]) } }) } } // observeFingerprint renders a blank page through the production browser setup // and reads back the surface a bot-detection script inspects. func observeFingerprint(t *testing.T, stealth bool) map[string]any { t.Helper() path, err := filepath.Abs(os.Getenv("BROWSER_PATH")) if err != nil { t.Fatal(err) } b := &Browser{path: path, network: newNetwork(true), slots: make(chan struct{}, 1), stealth: stealth, headless: true, waitMS: 1200 * time.Millisecond} defer b.network.transport.CloseIdleConnections() ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() alloc, cancelAlloc := chromedp.NewExecAllocator(ctx, b.execOptions("https://fingerprint.test/", renderOptions{stealth: stealth}, "127.0.0.1:1")...) defer cancelAlloc() tab, cancelTab := chromedp.NewContext(alloc) defer cancelTab() const probe = `(() => { const d = Object.getOwnPropertyDescriptor(Navigator.prototype, 'webdriver'); const gl = document.createElement('canvas').getContext('webgl'); const dbg = gl && gl.getExtension('WEBGL_debug_renderer_info'); return JSON.stringify({ webdriver: navigator.webdriver, vendor: navigator.vendor, languages: navigator.languages, plugins: navigator.plugins.length, userAgent: navigator.userAgent, webdriverGetter: d && d.get ? Function.prototype.toString.call(d.get) : null, chromeRuntime: !!(window.chrome && window.chrome.runtime), webglRenderer: gl ? gl.getParameter(dbg ? dbg.UNMASKED_RENDERER_WEBGL : 0x9246) : null, }); })()` var raw string actions := b.stealthActions(renderOptions{stealth: stealth}) actions = append(actions, chromedp.Navigate("data:text/html,