High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: report the launched browser binary version on /stealth/status (PIN-074)
Luigi Agostid9b711ea5f58
diff --git a/internal/browserprobe/versioncache.go b/internal/browserprobe/versioncache.gonew file mode 100644index 00000000..98699fa9--- /dev/null+++ b/internal/browserprobe/versioncache.go@@ -0,0 +1,61 @@+package browserprobe++import (+ "context"+ "sync"+)++// VersionCache probes a browser binary for its real version at most once per+// resolved binary path. RunVersion spawns a process, so callers on request+// paths must go through a cache rather than probing per call.+//+// The probe function is a constructor parameter rather than a package variable+// so a test can count probes and serve two fake binaries different versions+// without global state.+type VersionCache struct {+ probe func(context.Context, string) (string, error)++ mu sync.Mutex+ entries map[string]string+ probes int+}++func NewVersionCache(probe func(context.Context, string) (string, error)) *VersionCache {+ if probe == nil {+ probe = RunVersion+ }+ return &VersionCache{probe: probe, entries: map[string]string{}}+}++// Version returns the version token the binary reports, or "" when the binary+// is unknown or the probe fails. A failure is cached as "" so a missing or+// unrunnable binary cannot spawn a process on every request.+func (c *VersionCache) Version(ctx context.Context, binary string) string {+ if binary == "" {+ return ""+ }++ c.mu.Lock()+ defer c.mu.Unlock()++ if version, ok := c.entries[binary]; ok {+ return version+ }++ c.probes+++ line, err := c.probe(ctx, binary)+ version := ""+ if err == nil {+ version = ExtractVersionToken(line)+ }+ c.entries[binary] = version+ return version+}++// Probes reports how many times the probe function actually ran, so a test can+// assert the cache serves repeats without spawning another process.+func (c *VersionCache) Probes() int {+ c.mu.Lock()+ defer c.mu.Unlock()+ return c.probes+}diff --git a/internal/browserprobe/versioncache_test.go b/internal/browserprobe/versioncache_test.gonew file mode 100644index 00000000..4f7fb7db--- /dev/null+++ b/internal/browserprobe/versioncache_test.go@@ -0,0 +1,69 @@+package browserprobe++import (+ "context"+ "errors"+ "testing"+)++func TestVersionCacheProbesEachBinaryOnce(t *testing.T) {+ cache := NewVersionCache(func(_ context.Context, binary string) (string, error) {+ return "Google Chrome 150.0.7871.187 " + binary, nil+ })++ for range 3 {+ if got := cache.Version(context.Background(), "/opt/chrome"); got != "150.0.7871.187" {+ t.Fatalf("Version = %q, want the token the binary reported", got)+ }+ }++ if cache.Probes() != 1 {+ t.Errorf("probed %d times for one binary; the cache must not spawn a process per call", cache.Probes())+ }+}++// Keyed by resolved path, so cloak and ghost-chrome are covered without any+// provider-specific code.+func TestVersionCacheKeysByBinaryPath(t *testing.T) {+ versions := map[string]string{+ "/opt/chrome": "Google Chrome 150.0.7871.187",+ "/opt/cloak": "CloakBrowser 131.0.6778.86",+ }+ cache := NewVersionCache(func(_ context.Context, binary string) (string, error) {+ return versions[binary], nil+ })++ if got := cache.Version(context.Background(), "/opt/chrome"); got != "150.0.7871.187" {+ t.Errorf("chrome binary Version = %q", got)+ }+ if got := cache.Version(context.Background(), "/opt/cloak"); got != "131.0.6778.86" {+ t.Errorf("cloak binary Version = %q", got)+ }+ if cache.Probes() != 2 {+ t.Errorf("probes = %d, want one per distinct binary", cache.Probes())+ }+}++func TestVersionCacheFallsBackWhenTheProbeFails(t *testing.T) {+ cache := NewVersionCache(func(context.Context, string) (string, error) {+ return "", errors.New("exec format error")+ })++ if got := cache.Version(context.Background(), "/opt/chrome"); got != "" {+ t.Errorf("Version = %q on a failing probe, want empty so the caller falls back to the literal", got)+ }+ cache.Version(context.Background(), "/opt/chrome")+ if cache.Probes() != 1 {+ t.Errorf("probes = %d; a failing probe must be cached, not retried per request", cache.Probes())+ }+}++func TestVersionCacheIgnoresAnEmptyBinary(t *testing.T) {+ cache := NewVersionCache(func(context.Context, string) (string, error) {+ t.Fatal("probe ran for an empty binary path")+ return "", nil+ })+ if got := cache.Version(context.Background(), ""); got != "" {+ t.Errorf("Version = %q for an empty binary", got)+ }+}diff --git a/internal/handlers/stealth_status.go b/internal/handlers/stealth_status.goindex 16b27853..e436be00 100644--- a/internal/handlers/stealth_status.go+++ b/internal/handlers/stealth_status.go@@ -3,15 +3,30 @@ package handlersimport ("net/http"+ "github.com/pinchtab/pinchtab/internal/browserprobe"+ "github.com/pinchtab/pinchtab/internal/browsers/runtimekit"+ "github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx")+// browserVersionCache keeps the per-binary probe off the request path. The+// cache seam that tests exercise lives in browserprobe.VersionCache; this is+// only the process-wide instance the handler reads through.+var browserVersionCache = browserprobe.NewVersionCache(browserprobe.RunVersion)+func (h *Handlers) HandleStealthStatus(w http.ResponseWriter, r *http.Request) {status := h.Bridge.StealthStatus()if status == nil {writeUnavailable(w, 503, "stealth_unavailable", "stealth bundle unavailable")return}+ // Both fields come from one config here so they can never be read from+ // different sources: what the persona claims, and what the binary that+ // config resolves to reports for itself.+ if h.Config != nil {+ status.AdvertisedBrowserVersion = h.Config.BrowserVersion+ }+ status.BrowserBinaryVersion = probedBrowserVersion(r, h.Config)if tabID := r.URL.Query().Get("tabId"); tabID != "" {if tracker, ok := h.Bridge.(interface{ FingerprintRotateActive(string) bool }); ok {status.TabOverrides["fingerprintRotateActive"] = tracker.FingerprintRotateActive(tabID)@@ -19,3 +34,14 @@ func (h *Handlers) HandleStealthStatus(w http.ResponseWriter, r *http.Request) {}httpx.JSON(w, 200, status)}++// probedBrowserVersion reports the version the launched binary states for+// itself, resolved through the same resolver the launch path uses. It is empty+// when no binary is found or the probe fails, so a caller can tell "unknown"+// from a real disagreement with the advertised version.+func probedBrowserVersion(r *http.Request, cfg *config.RuntimeConfig) string {+ if cfg == nil {+ return ""+ }+ return browserVersionCache.Version(r.Context(), runtimekit.ResolveEffectiveBrowser(cfg).Binary)+}diff --git a/internal/handlers/stealth_status_test.go b/internal/handlers/stealth_status_test.gonew file mode 100644index 00000000..b8e79a9d--- /dev/null+++ b/internal/handlers/stealth_status_test.go@@ -0,0 +1,91 @@+package handlers++import (+ "encoding/json"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++// fakeBrowserBinary writes an executable that answers --version the way a real+// browser does, so the probe has something true to read without a browser.+func fakeBrowserBinary(t *testing.T, version string) string {+ t.Helper()+ if runtime.GOOS == "windows" {+ t.Skip("fake binary uses a shell script")+ }+ path := filepath.Join(t.TempDir(), "fake-chrome")+ script := "#!/bin/sh\necho 'Google Chrome " + version + "'\n"+ if err := os.WriteFile(path, []byte(script), 0o755); err != nil {+ t.Fatalf("write fake binary: %v", err)+ }+ return path+}++func stealthStatusBody(t *testing.T, cfg *config.RuntimeConfig) map[string]any {+ t.Helper()+ h := New(&mockBridge{}, cfg, nil, nil, nil)+ req := httptest.NewRequest("GET", "/stealth/status", nil)+ w := httptest.NewRecorder()++ h.HandleStealthStatus(w, req)++ if w.Code != 200 {+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("parse response: %v", err)+ }+ return resp+}++// The whole point of the two fields: a caller can see the persona and the+// binary disagree instead of having to infer it from a page read.+func TestStealthStatusReportsAdvertisedAndRealBrowserVersions(t *testing.T) {+ resp := stealthStatusBody(t, &config.RuntimeConfig{+ BrowserVersion: "144.0.7559.133",+ BrowserBinary: fakeBrowserBinary(t, "199.0.1234.5"),+ })++ if got := resp["advertisedBrowserVersion"]; got != "144.0.7559.133" {+ t.Errorf("advertisedBrowserVersion = %v, want the version the persona presents", got)+ }+ if got := resp["browserBinaryVersion"]; got != "199.0.1234.5" {+ t.Errorf("browserBinaryVersion = %v, want the version the launched binary reports", got)+ }+}++// Absence control: the mismatch above must come from the two values differing,+// not from the endpoint always reporting them as different.+func TestStealthStatusReportsAgreementWhenTheVersionsMatch(t *testing.T) {+ resp := stealthStatusBody(t, &config.RuntimeConfig{+ BrowserVersion: "199.0.1234.5",+ BrowserBinary: fakeBrowserBinary(t, "199.0.1234.5"),+ })++ if resp["advertisedBrowserVersion"] != resp["browserBinaryVersion"] {+ t.Errorf("advertised %v vs binary %v; equal inputs must report equal",+ resp["advertisedBrowserVersion"], resp["browserBinaryVersion"])+ }+}++// An unprobeable binary must read as unknown rather than as a disagreement,+// or every sandboxed deployment looks like the defect.+func TestStealthStatusOmitsTheBinaryVersionWhenTheProbeFails(t *testing.T) {+ resp := stealthStatusBody(t, &config.RuntimeConfig{+ BrowserVersion: "144.0.7559.133",+ BrowserBinary: filepath.Join(t.TempDir(), "does-not-exist"),+ })++ if got, ok := resp["browserBinaryVersion"]; ok {+ t.Errorf("browserBinaryVersion = %v for an unrunnable binary, want the field omitted", got)+ }+ if got := resp["advertisedBrowserVersion"]; got != "144.0.7559.133" {+ t.Errorf("advertisedBrowserVersion = %v, want it reported regardless of the probe", got)+ }+}diff --git a/internal/stealth/bundle.go b/internal/stealth/bundle.goindex 6b88c1f9..6ee3eb02 100644--- a/internal/stealth/bundle.go+++ b/internal/stealth/bundle.go@@ -69,6 +69,11 @@ type Status struct {Tradeoffs []string `json:"tradeoffs,omitempty"`TabOverrides map[string]bool `json:"tabOverrides"`AttachMutationsSkipped bool `json:"attachMutationsSkipped,omitempty"`+ // AdvertisedBrowserVersion is the version the persona presents to pages.+ // BrowserBinaryVersion is what the launched binary reports for itself; the+ // two disagreeing is the defect a caller can now observe rather than infer.+ AdvertisedBrowserVersion string `json:"advertisedBrowserVersion,omitempty"`+ BrowserBinaryVersion string `json:"browserBinaryVersion,omitempty"`}func NewBundle(cfg *config.RuntimeConfig, seed int64) *Bundle {diff --git a/tests/e2e/scenarios/infra/stealth-basic.sh b/tests/e2e/scenarios/infra/stealth-basic.shindex d5a5007d..d144451e 100644--- a/tests/e2e/scenarios/infra/stealth-basic.sh+++ b/tests/e2e/scenarios/infra/stealth-basic.sh@@ -427,3 +427,76 @@ start_test "stealth-workers: device memory matches worker"assert_eval_poll "window.__stealthWorkerReport.matches.deviceMemory" "true" "page and worker deviceMemory match"end_test++# ─────────────────────────────────────────────────────────────────+# Browser version honesty. Two independent questions:+# 1. do the version surfaces a page can read agree with each other, and+# 2. does the version the persona advertises match the binary that is+# actually running.+# (1) is a guard against a partial wiring: a fix that raises the advertised+# version must move every surface together. (2) is the defect itself, and it+# needs ground truth, which /stealth/status now carries as browserBinaryVersion.++start_test "stealth: advertised version surfaces agree with each other"++pt_post /navigate "{\"url\":\"${FIXTURES_URL}/index.html\"}"+assert_ok "navigate"+VERSION_TAB_ID=$(get_tab_id)++pt_post "/tabs/${VERSION_TAB_ID}/evaluate" '{"expression":"(function(){var m=navigator.userAgent.match(/Chrome\\/(\\d+)/);var b=(navigator.userAgentData&&navigator.userAgentData.brands||[]).filter(function(x){return x.brand===\"Google Chrome\"||x.brand===\"Chromium\"}).map(function(x){return x.version});return JSON.stringify({ua:m?m[1]:\"\",brands:b})})()"}'+assert_ok "read advertised version surfaces"+VERSION_SURFACES=$(echo "$RESULT" | jq -r '.result // "{}"')+UA_MAJOR=$(echo "$VERSION_SURFACES" | jq -r '.ua // ""')+BRAND_MAJORS=$(echo "$VERSION_SURFACES" | jq -r '(.brands // []) | unique | join(",")')++if [ -z "$UA_MAJOR" ]; then+ echo -e " ${RED}✗${NC} could not read a Chrome major from navigator.userAgent"+ ((ASSERTIONS_FAILED++)) || true+elif [ "$BRAND_MAJORS" = "$UA_MAJOR" ]; then+ echo -e " ${GREEN}✓${NC} userAgent and userAgentData.brands both report major ${UA_MAJOR}"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} version surfaces disagree: userAgent major=${UA_MAJOR} brands=${BRAND_MAJORS}"+ echo -e " ${MUTED}a page comparing these sees an inconsistent persona${NC}"+ ((ASSERTIONS_FAILED++)) || true+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "stealth: advertised version matches the launched binary"++pt_get /stealth/status+assert_ok "stealth status"+ADVERTISED_VERSION=$(echo "$RESULT" | jq -r '.advertisedBrowserVersion // ""')+BINARY_VERSION=$(echo "$RESULT" | jq -r '.browserBinaryVersion // ""')+ADVERTISED_MAJOR=${ADVERTISED_VERSION%%.*}+BINARY_MAJOR=${BINARY_VERSION%%.*}++if [ -z "$BINARY_VERSION" ]; then+ # Never silently pass: an unprobeable binary has no ground truth, so this+ # case is reported as unrun rather than counted as agreement.+ echo -e " ${YELLOW}!${NC} browserBinaryVersion is empty — the binary could not be probed, so this assertion did NOT run"+elif [ "$ADVERTISED_MAJOR" = "$BINARY_MAJOR" ]; then+ echo -e " ${GREEN}✓${NC} advertised major ${ADVERTISED_MAJOR} matches the launched binary (${BINARY_VERSION})"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} persona advertises Chrome ${ADVERTISED_MAJOR} while the running binary is ${BINARY_VERSION}"+ echo -e " ${MUTED}advertised:${NC} ${ADVERTISED_VERSION}"+ echo -e " ${MUTED}launched:${NC} ${BINARY_VERSION}"+ ((ASSERTIONS_FAILED++)) || true+fi++# The page must agree with what the status endpoint claims to advertise, or+# the endpoint is reporting a value the browser does not actually present.+if [ -n "$UA_MAJOR" ] && [ -n "$ADVERTISED_MAJOR" ]; then+ if [ "$UA_MAJOR" = "$ADVERTISED_MAJOR" ]; then+ echo -e " ${GREEN}✓${NC} navigator.userAgent major matches advertisedBrowserVersion"+ ((ASSERTIONS_PASSED++)) || true+ else+ echo -e " ${RED}✗${NC} status advertises major ${ADVERTISED_MAJOR} but the page reports ${UA_MAJOR}"+ ((ASSERTIONS_FAILED++)) || true+ fi+fi++end_test