High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: two-phase static-first navigate, credentials coordination, and nav guard hardening
Bosch993b6ebcf366
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex c0ec5dd6..245e5463 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -141,6 +141,9 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {if sess, ok := session.FromRequest(r); ok && sess != nil {sessionBrowser = sess.Browser}+ if h.rejectBrowserConflictWithRunning(w, requestBrowser, sessionBrowser) {+ return+ }var instanceBrowser stringif req.TabID != "" && h.Orchestrator != nil {if inst, ok := h.Orchestrator.FindInstanceByTab(req.TabID); ok && inst != nil && inst.Browser != "" {@@ -503,10 +506,21 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, reif len(req.Actions) > 0 {requestBrowser = strings.TrimSpace(req.Actions[0].Browser)}+ // A batch executes on one browser; differing values on later actions+ // would be silently ignored — reject them instead.+ for i, a := range req.Actions {+ if b := strings.TrimSpace(a.Browser); b != "" && !strings.EqualFold(b, requestBrowser) {+ httpx.Error(w, 400, fmt.Errorf("mixed browser values in a batch are not supported: actions[0]=%q, actions[%d]=%q", requestBrowser, i, b))+ return+ }+ }var sessionBrowser stringif sess, ok := session.FromRequest(r); ok && sess != nil {sessionBrowser = sess.Browser}+ if h.rejectBrowserConflictWithRunning(w, requestBrowser, sessionBrowser) {+ return+ }var instanceBrowser stringif req.TabID != "" && h.Orchestrator != nil {if inst, ok := h.Orchestrator.FindInstanceByTab(req.TabID); ok && inst != nil && inst.Browser != "" {@@ -797,6 +811,14 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {if len(req.Steps) > 0 {macroRequestBrowser = strings.TrimSpace(req.Steps[0].Browser)}+ // A macro executes on one browser; differing values on later steps+ // would be silently ignored — reject them instead.+ for i, s := range req.Steps {+ if b := strings.TrimSpace(s.Browser); b != "" && !strings.EqualFold(b, macroRequestBrowser) {+ httpx.Error(w, 400, fmt.Errorf("mixed browser values in a macro are not supported: steps[0]=%q, steps[%d]=%q", macroRequestBrowser, i, b))+ return+ }+ }var macroSessionBrowser stringif sess, ok := session.FromRequest(r); ok && sess != nil {macroSessionBrowser = sess.Browserdiff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.goindex 4b7be142..663a0790 100644--- a/internal/handlers/actions_test.go+++ b/internal/handlers/actions_test.go@@ -5,6 +5,7 @@ import ("context""encoding/json""fmt"+ "net/http""net/http/httptest""strings""testing"@@ -599,3 +600,37 @@ func TestHandleMacro_Disabled(t *testing.T) {t.Errorf("expected 403 when macro disabled, got %d", w.Code)}}++// L7(f): differing browser values across batch actions would be silently+// ignored (only actions[0] is consulted) — they must 400 instead.+func TestHandleBatchActions_MixedBrowsersRejected(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak},+ }, nil, nil, nil)++ body := []byte(`{"actions":[{"kind":"click","ref":"e1","browser":"chrome"},{"kind":"click","ref":"e2","browser":"cloak"}]}`)+ req := httptest.NewRequest("POST", "/actions", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleActions(w, req)++ if w.Code != 400 {+ t.Fatalf("mixed browsers should 400, got %d body=%s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "mixed browser") {+ t.Fatalf("error should name the mixed-browser problem: %s", w.Body.String())+ }+}++// L7(d): the pre-rename lazy-init path must keep serving for old orchestrators.+func TestEnsureChromeAliasServes(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, func() {})++ req := httptest.NewRequest("POST", "/ensure-chrome", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound {+ t.Fatal("/ensure-chrome back-compat alias must not 404")+ }+}diff --git a/internal/handlers/capture.go b/internal/handlers/capture.goindex 3f676124..a45d4b0e 100644--- a/internal/handlers/capture.go+++ b/internal/handlers/capture.go@@ -55,6 +55,9 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {if sess, ok := session.FromRequest(r); ok && sess != nil {sessionBrowser = sess.Browser}+ if h.rejectBrowserConflictWithRunning(w, requestBrowser, sessionBrowser) {+ return+ }var instanceBrowser stringif tabID != "" && h.Orchestrator != nil {if inst, ok := h.Orchestrator.FindInstanceByTab(tabID); ok && inst != nil && inst.Browser != "" {diff --git a/internal/handlers/credentials.go b/internal/handlers/credentials.goindex 9b1dbd0c..15751205 100644--- a/internal/handlers/credentials.go+++ b/internal/handlers/credentials.go@@ -10,6 +10,8 @@ import ("time""github.com/pinchtab/pinchtab/internal/activity"+ bridgeruntime "github.com/pinchtab/pinchtab/internal/bridge/runtime"+ "github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/httpx")@@ -138,10 +140,19 @@ func (h *Handlers) setCredentials(w http.ResponseWriter, r *http.Request, req cr// Clear credentials: disable fetch domain and remove stored credentials.h.credentialStore.Delete(resolvedTabID)- if err := h.Bridge.DisableFetch(tCtx); err != nil {+ if proxyAuthConfigured(h.Config) {+ // Proxy auth shares the Fetch domain; keep it enabled with auth+ // handling instead of disabling, and hand pause dispatch back to+ // the proxy-auth listener.+ if err := h.Bridge.EnableFetchWithAuth(tCtx); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP fetch re-enable for proxy auth: %w", err))+ return+ }+ } else if err := h.Bridge.DisableFetch(tCtx); err != nil {httpx.Error(w, 500, fmt.Errorf("CDP fetch disable: %w", err))return}+ h.setFetchPauseSuppressed(resolvedTabID, false)h.recordActivity(r, activity.Update{Action: "emulation.credentials", TabID: resolvedTabID})@@ -161,6 +172,12 @@ func (h *Handlers) setCredentials(w http.ResponseWriter, r *http.Request, req crhttpx.Error(w, 500, fmt.Errorf("CDP fetch enable: %w", err))return}+ // The credentials listener continues paused requests itself; quiet the+ // proxy-auth listener's blanket continue while this session is active.+ // Precedence on auth challenges is racy by design: the proxy-auth+ // listener answers proxy-source challenges, this listener answers via+ // stored credentials; a double answer logs a debug error harmlessly.+ h.setFetchPauseSuppressed(resolvedTabID, true)// Install event listener only once per tab. The listener reads credentials// from the store dynamically, so updating creds doesn't need a new listener.@@ -193,3 +210,22 @@ func (h *Handlers) setCredentials(w http.ResponseWriter, r *http.Request, req cr"status": "applied",})}++// fetchPauseSuppressor is probed on the bridge for Fetch-domain coordination+// with the proxy-auth listener. The ghost-chrome adapter does not promote+// this method (interface-embedded *Bridge), so suppression is skipped there —+// acceptable: routes/credentials + proxy auth on ghost-chrome is an edge of+// an edge, and the failure mode is a raced duplicate continue, not a hang.+type fetchPauseSuppressor interface {+ SetFetchPauseSuppressed(tabID string, v bool)+}++func (h *Handlers) setFetchPauseSuppressed(tabID string, v bool) {+ if sup, ok := h.Bridge.(fetchPauseSuppressor); ok {+ sup.SetFetchPauseSuppressed(tabID, v)+ }+}++func proxyAuthConfigured(cfg *config.RuntimeConfig) bool {+ return cfg != nil && bridgeruntime.ProxyAuthEnabled(cfg.Proxy)+}diff --git a/internal/handlers/download.go b/internal/handlers/download.goindex 100b1606..74952bbf 100644--- a/internal/handlers/download.go+++ b/internal/handlers/download.go@@ -129,11 +129,6 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {},})if err != nil {- if bErr := requestGuard.BlockedError(); bErr != nil {- if writeDownloadGuardError(w, bErr, maxDownloadBytes) {- return- }- }// Chrome aborts navigation for binary downloads (.gz, etc.).// Fall back to a direct Go HTTP fetch using the browser's cookies.if isNavigationAborted(err) {@@ -160,13 +155,13 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 422, fmt.Errorf("download: %w", err))return}- if strings.Contains(err.Error(), "download response too large") {+ if errors.Is(err, bridge.ErrDownloadTooLarge) {httpx.ErrorCode(w, http.StatusRequestEntityTooLarge, "download_too_large", err.Error(), false, map[string]any{"maxBytes": maxDownloadBytes,})return}- if strings.Contains(err.Error(), "timed out") {+ if errors.Is(err, bridge.ErrDownloadTimeout) {httpx.Error(w, 504, fmt.Errorf("download timed out"))return}diff --git a/internal/handlers/download_guard.go b/internal/handlers/download_guard.goindex 73ecbfb2..0f26590f 100644--- a/internal/handlers/download_guard.go+++ b/internal/handlers/download_guard.go@@ -8,7 +8,6 @@ import ("net/url""strconv""strings"- "sync""sync/atomic""time"@@ -19,7 +18,8 @@ import ("github.com/pinchtab/pinchtab/internal/netguard")-var errDownloadTooLarge = errors.New("download response too large")+// Aliased to the bridge sentinel so errors from either layer classify identically.+var errDownloadTooLarge = bridge.ErrDownloadTooLargetype downloadURLGuard struct {allowedDomains []string@@ -148,9 +148,6 @@ type downloadRequestGuard struct {validator *downloadURLGuardmaxRedirects intredirects atomic.Int32-- mu sync.Mutex- blockedErr error}func newDownloadRequestGuard(validator *downloadURLGuard, maxRedirects int) *downloadRequestGuard {@@ -178,20 +175,6 @@ func (g *downloadRequestGuard) Validate(rawURL string, redirected bool) error {return nil}-func (g *downloadRequestGuard) NoteBlocked(err error) {- g.mu.Lock()- if g.blockedErr == nil {- g.blockedErr = err- }- g.mu.Unlock()-}--func (g *downloadRequestGuard) BlockedError() error {- g.mu.Lock()- defer g.mu.Unlock()- return g.blockedErr-}-func downloadTooLargeError(size int64, maxBytes int) error {return fmt.Errorf("%w: received %d bytes, max %d", errDownloadTooLarge, size, maxBytes)}diff --git a/internal/handlers/download_test.go b/internal/handlers/download_test.goindex 5d1d69db..e8719f7b 100644--- a/internal/handlers/download_test.go+++ b/internal/handlers/download_test.go@@ -3,6 +3,7 @@ package handlersimport ("context""errors"+ "fmt""net""net/http""net/http/httptest"@@ -422,3 +423,24 @@ func TestHandleDownload_RejectsURLOutsideAllowedDomains(t *testing.T) {t.Fatalf("expected allowlist error in response, got %s", w.Body.String())}}++// M12 regression: status mapping is driven by errors.Is on the bridge+// sentinels, surviving arbitrary extra wrapping — not by message substrings.+func TestDownloadErrorSentinelsClassifyThroughWrapping(t *testing.T) {+ tooLarge := fmt.Errorf("navigate to download URL: %w",+ fmt.Errorf("%w: received 10 bytes, max 5", bridge.ErrDownloadTooLarge))+ if !errors.Is(tooLarge, bridge.ErrDownloadTooLarge) {+ t.Fatal("wrapped too-large error should match the sentinel")+ }+ rec := httptest.NewRecorder()+ if !writeDownloadGuardError(rec, tooLarge, 5) {+ t.Fatal("guard writer should classify the sentinel error")+ }+ if rec.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("status = %d, want 413", rec.Code)+ }++ if !errors.Is(fmt.Errorf("ctx: %w", bridge.ErrDownloadTimeout), bridge.ErrDownloadTimeout) {+ t.Fatal("wrapped timeout error should match the sentinel")+ }+}diff --git a/internal/handlers/handler_browser.go b/internal/handlers/handler_browser.goindex 056d0cf7..a53931a5 100644--- a/internal/handlers/handler_browser.go+++ b/internal/handlers/handler_browser.go@@ -1,13 +1,51 @@package handlers-import "github.com/pinchtab/pinchtab/internal/config"+import (+ "fmt"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++// rejectBrowserConflictWithRunning writes a 409 and reports true when an+// explicitly requested browser (request param, falling back to session) cannot+// be honored because a different browser process is already running.+// EnsureBrowser ignores the requested config once initialized, so without this+// check an explicit mismatch silently executes on the wrong browser — a+// stealth regression. Implicit resolution (global default, instance-derived,+// capability downgrades) must not be passed here.+func (h *Handlers) rejectBrowserConflictWithRunning(w http.ResponseWriter, requestBrowser, sessionBrowser string) bool {+ explicit := requestBrowser+ if explicit == "" {+ explicit = sessionBrowser+ }+ if explicit == "" || h.Bridge == nil {+ return false+ }+ running, ok := h.Bridge.RunningBrowser()+ if !ok || running == "" {+ return false+ }+ if config.NormalizeBrowser(explicit) == config.NormalizeBrowser(running) {+ return false+ }+ httpx.ErrorCode(w, http.StatusConflict, "browser_conflict",+ fmt.Sprintf("browser %q requested but %q is already running; restart the server with --browser %s or launch an instance with that browser", explicit, running, explicit),+ false, map[string]any{+ "requestedBrowser": explicit,+ "runningBrowser": running,+ })+ return true+}// resolveEffectiveConfig returns a RuntimeConfig with target-specific overrides// (binary, proxy, Cloak, extraFlags) merged in. The browser parameter is a// provider name (e.g. "cloak"); it is resolved internally to the matching-// target. When the browser name is empty, targets are not configured, or-// resolution fails, the global h.Config is returned unchanged so the caller-// always gets a usable config.+// target. An empty browser name, no configured targets, or no target for the+// provider legitimately fall back to the global h.Config — but a target that+// EXISTS and fails to resolve is an error: silently substituting the global+// config would run the request with the wrong binary/proxy/fingerprint.func (h *Handlers) resolveEffectiveConfig(browser string) (*config.RuntimeConfig, error) {if browser == "" || h.Config == nil || len(h.Config.Targets) == 0 {return h.Config, nil@@ -19,7 +57,7 @@ func (h *Handlers) resolveEffectiveConfig(browser string) (*config.RuntimeConfigcase 1:resolved, err := config.ResolveExplicitBrowserTarget(h.Config, matches[0])if err != nil {- return h.Config, nil+ return nil, fmt.Errorf("resolve browser target %q: %w", matches[0], err)}return resolved.Config, nildefault:@@ -29,7 +67,7 @@ func (h *Handlers) resolveEffectiveConfig(browser string) (*config.RuntimeConfigif m == dt {resolved, err := config.ResolveExplicitBrowserTarget(h.Config, dt)if err != nil {- return h.Config, nil+ return nil, fmt.Errorf("resolve default browser target %q: %w", dt, err)}return resolved.Config, nil}diff --git a/internal/handlers/handler_browser_test.go b/internal/handlers/handler_browser_test.goindex 6ca90dc4..28d83326 100644--- a/internal/handlers/handler_browser_test.go+++ b/internal/handlers/handler_browser_test.go@@ -1,6 +1,7 @@package handlersimport (+ "strings""testing""time"@@ -121,3 +122,42 @@ func TestResolveEffectiveConfig_AmbiguousBrowser(t *testing.T) {t.Fatalf("AmbiguousBrowserError.Browser = %q, want cloak", ambErr.Browser)}}++// M6 regression: a target that exists but fails to resolve must surface an+// error — silently substituting the global config would run the request with+// the wrong binary/proxy/fingerprint.+func TestResolveEffectiveConfig_BrokenTargetErrorsInsteadOfGlobalFallback(t *testing.T) {+ // "Bad-Name" violates the target-name grammar (^[a-z][a-z0-9-]{0,31}$),+ // which loads with only a warning but fails explicit resolution.+ h := New(&mockBridge{}, &config.RuntimeConfig{+ Targets: config.BrowserTargetsConfig{+ "Bad-Name": {Provider: config.BrowserCloak, Binary: "/opt/cloak/bin"},+ },+ }, nil, nil, nil)++ cfg, err := h.resolveEffectiveConfig(config.BrowserCloak)+ if err == nil {+ t.Fatalf("expected resolution error for broken target, got cfg=%+v", cfg)+ }+ if !strings.Contains(err.Error(), "Bad-Name") {+ t.Fatalf("error should name the broken target: %v", err)+ }+}++// The legitimate fallbacks stay: no target configured for the provider means+// the global config, not an error.+func TestResolveEffectiveConfig_NoTargetForProviderFallsBack(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{+ Targets: config.BrowserTargetsConfig{+ "cloak-1": {Provider: config.BrowserCloak},+ },+ }, nil, nil, nil)++ cfg, err := h.resolveEffectiveConfig(config.BrowserChrome)+ if err != nil {+ t.Fatalf("no-target-for-provider should fall back, got error: %v", err)+ }+ if cfg != h.Config {+ t.Fatal("expected the global config on fallback")+ }+}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex b83f1b75..61673e82 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -17,7 +17,6 @@ import ("github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/idpi""github.com/pinchtab/pinchtab/internal/ids"- "github.com/pinchtab/pinchtab/internal/navguard""github.com/pinchtab/semantic""github.com/pinchtab/semantic/recovery")@@ -34,7 +33,6 @@ type Handlers struct {Recovery *recovery.RecoveryEngineIDPIGuard idpi.GuardContentGuard *contentguard.Scanner- NavGuard *navguard.ValidatorCurrentTabs *CurrentTabStoreVersion string // build version injected at startupclipboard clipboardStore@@ -71,11 +69,6 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,Guard: idpiGuard,WrapEnabled: cfg.IDPI.WrapContent,},- NavGuard: &navguard.Validator{- TrustedResolveCIDRs: navguard.ParseCIDRs(cfg.TrustedResolveCIDRs),- TrustedProxyCIDRs: navguard.BuildTrustedProxyCIDRs(cfg.TrustLoopbackProxy, cfg.TrustedProxyCIDRs),- IDPIDomainAllowed: idpiGuard.DomainAllowed,- },CurrentTabs: NewCurrentTabStore(),credentialStore: newCredentialStore(),recorder: &recorder{},@@ -238,6 +231,9 @@ func (h *Handlers) writeBridgeUnavailable(w http.ResponseWriter, err error) boolfunc (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("GET /health", h.HandleHealth)mux.HandleFunc("POST /ensure-browser", h.HandleEnsureBrowser)+ // Back-compat alias: older orchestrators retry lazy init via the+ // pre-rename path; without it a version-skewed pair 404s.+ mux.HandleFunc("POST /ensure-chrome", h.HandleEnsureBrowser)mux.HandleFunc("POST /browser/restart", h.HandleBrowserRestart)mux.HandleFunc("GET /tabs", h.HandleTabs)mux.HandleFunc("POST /tabs/{id}/navigate", h.HandleTabNavigate)diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex ad86e3f4..be873d0d 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -33,6 +33,14 @@ type mockBridge struct {autoCloseArmed []stringautoCloseCanceled []stringavailableActions []string+ navigateResult *bridge.NavigateResult+ navigateErr error+ closedTabs []string+ runningBrowser string++ staticFirstNavigate bool+ staticEscalate *bridge.StaticEscalateError+ navigateParams []bridge.NavigateParams}func (m *mockBridge) TabContext(tabID string) (*bridge.TabHandle, string, error) {@@ -73,6 +81,7 @@ func (m *mockBridge) CloseTab(tabID string) error {if tabID == "fail" {return fmt.Errorf("close failed")}+ m.closedTabs = append(m.closedTabs, tabID)return nil}@@ -96,6 +105,10 @@ func (m *mockBridge) EnsureBrowser(cfg *config.RuntimeConfig) error {return m.ensureBrowserErr}+func (m *mockBridge) RunningBrowser() (string, bool) {+ return m.runningBrowser, m.runningBrowser != ""+}+func (m *mockBridge) RestartBrowser(cfg *config.RuntimeConfig) error {return nil}@@ -104,10 +117,22 @@ func (m *mockBridge) GetRefCache(tabID string) *bridge.RefCache { returnfunc (m *mockBridge) SetRefCache(tabID string, cache *bridge.RefCache) {}func (m *mockBridge) DeleteRefCache(tabID string) {}-func (m *mockBridge) Navigate(_ context.Context, url string, _ bridge.NavigateParams) (*bridge.NavigateResult, error) {+func (m *mockBridge) Navigate(_ context.Context, url string, params bridge.NavigateParams) (*bridge.NavigateResult, error) {+ m.navigateParams = append(m.navigateParams, params)+ if params.NoEscalate && m.staticEscalate != nil {+ return nil, m.staticEscalate+ }+ if m.navigateErr != nil {+ return nil, m.navigateErr+ }+ if m.navigateResult != nil {+ return m.navigateResult, nil+ }return nil, fmt.Errorf("not implemented in test mock")}+func (m *mockBridge) StaticFirstNavigate() bool { return m.staticFirstNavigate }+func (m *mockBridge) Snapshot(_ context.Context, _ string, _ string, _ bridge.ContentParams) (*bridge.SnapshotResult, error) {return nil, fmt.Errorf("not implemented in test mock")}diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex 8c2a9428..7dace0ec 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -390,6 +390,8 @@ func (m *MockBridge) EnsureBrowser(cfg *config.RuntimeConfig) error {return nil}+func (m *MockBridge) RunningBrowser() (string, bool) { return "", false }+func (m *MockBridge) RestartBrowser(cfg *config.RuntimeConfig) error {if m.ensureBrowserErr != "" {return fmt.Errorf("%s", m.ensureBrowserErr)diff --git a/internal/handlers/middleware_ratelimit.go b/internal/handlers/middleware_ratelimit.goindex c2339a6e..ef6b5438 100644--- a/internal/handlers/middleware_ratelimit.go+++ b/internal/handlers/middleware_ratelimit.go@@ -16,10 +16,17 @@ import (const (maxConcurrentStreamRequestsPerHost = 8rateLimitWindow = 10 * time.Second- defaultRateLimitMaxReq = 3000- evictionInterval = 30 * time.Second+ // 3000/10s (~300 req/s per client IP): agent-driven workloads+ // (snapshot/action loops, the optimization suites) legitimately burst far+ // past the older 300 cap. Bearer-token auth and the loopback-only default+ // bind are the primary gates; this limiter is per-client defense-in-depth.+ // Operators exposing the port beyond localhost can lower it via+ // PINCHTAB_RATE_LIMIT_MAX (documented in docs/reference/config.md).+ defaultRateLimitMaxReq = 3000+ evictionInterval = 30 * time.Second)+// Operator tuning knob; children inherit it via the PINCHTAB_ env passthrough.var rateLimitMaxReq = func() int {if v, err := strconv.Atoi(os.Getenv("PINCHTAB_RATE_LIMIT_MAX")); err == nil && v > 0 {return vdiff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 2efed3b4..30c10801 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -100,8 +100,16 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {if sess, ok := session.FromRequest(r); ok && sess != nil {sessionBrowser = sess.Browser}+ if h.rejectBrowserConflictWithRunning(w, requestBrowser, sessionBrowser) {+ return+ }+ tabID := strings.TrimSpace(req.TabID)var instanceBrowser string- // Instance browser lookup is done later when we have a tabID (for existing tabs)+ if tabID != "" && h.Orchestrator != nil {+ if inst, ok := h.Orchestrator.FindInstanceByTab(tabID); ok && inst != nil && inst.Browser != "" {+ instanceBrowser = inst.Browser+ }+ }resolvedBrowser := config.ResolveBrowser(requestBrowser, sessionBrowser, instanceBrowser, h.Config.DefaultBrowser, h.Config.BrowsersAvailable)if resolvedBrowser != config.BrowserChrome {@@ -111,6 +119,10 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {}}+ // intentBrowser is the pre-downgrade resolution: the ownership conflict+ // check below must compare against what was asked for, not what the+ // DecisionSkip fallback executes on (ghost-chrome reads run on chrome).+ intentBrowser := resolvedBrowserhandleDecision, err := checkBrowserCanHandle(resolvedBrowser, browsers.RequestIntent{Shape: browsers.ShapeRenderedRead,})@@ -138,18 +150,18 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {return}- tabID := strings.TrimSpace(req.TabID)- if resolvedBrowser != "" && tabID != "" && h.Orchestrator != nil {+ // With instance browser feeding resolution above, this only fires when an+ // explicit request/session browser disagrees with the owning instance.+ if intentBrowser != "" && tabID != "" && h.Orchestrator != nil {if inst, ok := h.Orchestrator.FindInstanceByTab(tabID); ok && inst != nil {- if inst.Browser != "" && config.NormalizeBrowser(inst.Browser) != config.NormalizeBrowser(resolvedBrowser) {+ if inst.Browser != "" && config.NormalizeBrowser(inst.Browser) != config.NormalizeBrowser(intentBrowser) {httpx.ErrorCode(w, http.StatusConflict, "browser_conflict",fmt.Sprintf("tab %q is owned by instance with browser %q; cannot navigate with browser %q",- tabID, inst.Browser, resolvedBrowser),+ tabID, inst.Browser, intentBrowser),false, map[string]any{"tabId": tabID,"instanceBrowser": inst.Browser,- "requestedBrowser": resolvedBrowser,- "instanceProvider": inst.Browser,+ "requestedBrowser": intentBrowser,})return}@@ -191,10 +203,6 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {}h.recordActivity(r, activity.Update{Route: navRoute})- if !h.ensureBrowserOrRespond(w, effectiveCfg) {- return- }-explicitTabID := strings.TrimSpace(req.TabID) != ""scopedCurrentForNavigate := falseidentifiedCaller := !currentTabScopeFromRequest(r).IsGlobal()@@ -219,6 +227,59 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {req.NewTab = true}+ // Static-first phase: a ghost-chrome-capable bridge can serve a fresh+ // navigate from its static browser without launching Chrome at all+ // (parity with main's lite mode). Only new-tab navigates qualify —+ // existing tabs already imply a running browser. On escalation, the+ // Chrome path below runs with SkipStatic so the fetch isn't repeated.+ //+ // Timeout budget is PER PHASE, not shared: the static attempt gets+ // NavigateTimeout (default 30s), and on escalation the Chrome navigate+ // gets a fresh budget of its own — worst case a navigate takes up to+ // twice the configured timeout. Sharing one budget would let a slow+ // static fetch starve the Chrome attempt that exists to rescue it.+ skipStatic := false+ var staticEscRoute *browserops.RouteMetadata+ if sf, ok := h.Bridge.(staticFirstNavigator); ok && sf.StaticFirstNavigate() && req.NewTab {+ phase1Timeout := effectiveCfg.NavigateTimeout+ if phase1Timeout <= 0 {+ phase1Timeout = 30 * time.Second+ }+ phase1Ctx, phase1Cancel := context.WithTimeout(r.Context(), phase1Timeout)+ navResult, navErr := h.Bridge.Navigate(phase1Ctx, req.URL, bridge.NavigateParams{+ MaxRedirects: effectiveCfg.MaxRedirects,+ NoEscalate: true,+ })+ phase1Cancel()+ if navErr == nil && navResult != nil && navResult.TabID != "" {+ if navResult.Route != nil {+ navRoute = navResult.Route+ }+ h.setCurrentTabForRequest(r, navResult.TabID)+ h.recordResolvedURL(r, navResult.URL)+ httpx.JSON(w, 200, map[string]any{"tabId": navResult.TabID, "url": navResult.URL, "title": navResult.Title, "route": navRoute})+ return+ }+ skipStatic = true+ var esc *bridge.StaticEscalateError+ if errors.As(navErr, &esc) && esc.Route != nil {+ staticEscRoute = esc.Route+ }+ }++ if !h.ensureBrowserOrRespond(w, effectiveCfg) {+ return+ }++ if staticEscRoute != nil {+ // Merge the static attempt with the Chrome escalation, mirroring the+ // adapter's internal-escalation metadata shape.+ staticEscRoute.Escalated = true+ staticEscRoute.Attempts = append(staticEscRoute.Attempts,+ browserops.RouteAttempt{Browser: "chrome", Accepted: true, Reason: "escalated"})+ navRoute = staticEscRoute+ }+titleWait := time.Duration(0)if req.WaitTitle > 0 {if req.WaitTitle > 30 {@@ -275,6 +336,7 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {DismissBanners: req.DismissBanners,Route: navRoute,MaxRedirects: effectiveCfg.MaxRedirects,+ SkipStatic: skipStatic,})return}@@ -345,6 +407,18 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {h.Bridge.DeleteRefCache(resolvedTabID)h.clearTabFrameScope(resolvedTabID)+ // The ghost-chrome adapter may serve a navigate from a static tab instead+ // of the tab this handler drove; its result is authoritative. The static+ // document is fully loaded by construction, so waitFor/waitSelector are+ // already satisfied, and the remaining post-steps are Chrome-tab CDP ops+ // that would run against a tab that never navigated.+ if navResult != nil && navResult.TabID != "" && navResult.TabID != resolvedTabID {+ h.setCurrentTabForRequest(r, navResult.TabID)+ h.recordResolvedURL(r, navResult.URL)+ httpx.JSON(w, 200, map[string]any{"tabId": navResult.TabID, "url": navResult.URL, "title": navResult.Title, "route": navRoute})+ return+ }+if err := h.waitForNavigationState(tCtx, req.WaitFor, req.WaitSelector); err != nil {httpx.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)return@@ -373,6 +447,15 @@ type navigateBrowserOptions struct {DismissBanners boolRoute *browserops.RouteMetadataMaxRedirects int+ // SkipStatic: the handler already ran (and failed) the static-first+ // phase; the bridge must go straight to Chrome.+ SkipStatic bool+}++// staticFirstNavigator is probed on the bridge to enable the deferred-launch+// two-phase navigate (NoEscalate, then SkipStatic on escalation).+type staticFirstNavigator interface {+ StaticFirstNavigate() bool}func (h *Handlers) navigateNewTabBrowser(w http.ResponseWriter, r *http.Request, opts navigateBrowserOptions) {@@ -399,8 +482,12 @@ func (h *Handlers) navigateNewTabBrowser(w http.ResponseWriter, r *http.Request,navResult, navErr := h.Bridge.Navigate(tCtx, opts.URL, bridge.NavigateParams{MaxRedirects: opts.MaxRedirects,+ SkipStatic: opts.SkipStatic,})if navErr != nil {+ // The blank tab never carried the requested URL; keeping it around on+ // failure only burns a MaxTabs slot until eviction.+ _ = h.Bridge.CloseTab(newTabID)if navGuard != nil {if blockedErr := navGuard.blocked(); blockedErr != nil {httpx.Error(w, http.StatusForbidden, blockedErr)@@ -421,6 +508,22 @@ func (h *Handlers) navigateNewTabBrowser(w http.ResponseWriter, r *http.Request,opts.Route = navResult.Route}+ // Static-first path served the navigate from its own tab: respond with+ // that tab and drop the unused blank Chrome tab created above. See the+ // matching branch in HandleNavigate for why post-steps are skipped.+ if navResult != nil && navResult.TabID != "" && navResult.TabID != newTabID {+ _ = h.Bridge.CloseTab(newTabID)+ h.setCurrentTabForRequest(r, navResult.TabID)+ h.recordResolvedTab(r, navResult.TabID)+ h.recordResolvedURL(r, navResult.URL)+ resp := map[string]any{"tabId": navResult.TabID, "url": navResult.URL, "title": navResult.Title}+ if opts.Route != nil {+ resp["route"] = opts.Route+ }+ httpx.JSON(w, 200, resp)+ return+ }+if err := h.waitForNavigationState(tCtx, opts.WaitFor, opts.WaitSelector); err != nil {httpx.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)returndiff --git a/internal/handlers/navigation_browser_test.go b/internal/handlers/navigation_browser_test.goindex e88fe6cc..dec4ef21 100644--- a/internal/handlers/navigation_browser_test.go+++ b/internal/handlers/navigation_browser_test.go@@ -2,12 +2,17 @@ package handlersimport ("bytes"+ "context""encoding/json"+ "fmt"+ "net""net/http""net/http/httptest""strings""testing"+ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/browserops""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/session")@@ -76,6 +81,35 @@ func TestHandleNavigate_EnsuresResolvedBrowserTargetConfig(t *testing.T) {}}+// A failed navigate must not strand the blank tab created for the new-tab+// path: it never carried the requested URL and would only burn a MaxTabs+// slot until eviction.+func TestHandleNavigate_FailedNavigateClosesBlankTab(t *testing.T) {+ stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {+ return []net.IP{net.ParseIP("93.184.216.34")}, nil+ })++ m := &mockBridge{+ navigateErr: fmt.Errorf("net::ERR_CONNECTION_REFUSED"),+ }+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)++ body := []byte(`{"url":"https://example.com"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code < 400 {+ t.Fatalf("expected navigate failure status, got %d body=%s", w.Code, w.Body.String())+ }+ if len(m.createTabURLs) != 1 {+ t.Fatalf("expected one blank tab creation, got %v", m.createTabURLs)+ }+ if len(m.closedTabs) != 1 || m.closedTabs[0] != "tab_abc12345" {+ t.Fatalf("blank tab not closed on navigate failure; closedTabs = %v", m.closedTabs)+ }+}+func TestHandleNavigate_BrowserParam_Invalid_Returns400(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{BrowsersAvailable: []string{"chrome"},@@ -416,3 +450,267 @@ func TestHandleNavigate_RequestOverridesSessionAndDefault(t *testing.T) {t.Fatalf("expected request 'chrome' to override session and default 'fake-browser', but got 400 body=%s", w.Body.String())}}++// The ghost-chrome adapter can serve a navigate from its own static tab; the+// handler must respond with the adapter's tab instead of the tab it drove.+func TestHandleNavigate_AdapterServedTab_ExistingTab_ReturnsAdapterResult(t *testing.T) {+ m := &mockBridge{navigateResult: &bridge.NavigateResult{+ TabID: "lite-1",+ URL: "http://localhost:3000/",+ Title: "Static Page",+ }}+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000","tabId":"tab1"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp["tabId"] != "lite-1" {+ t.Fatalf("tabId = %v, want lite-1 (adapter-served tab)", resp["tabId"])+ }+ if resp["url"] != "http://localhost:3000/" {+ t.Fatalf("url = %v, want adapter URL", resp["url"])+ }+ if resp["title"] != "Static Page" {+ t.Fatalf("title = %v, want adapter title", resp["title"])+ }+}++func TestHandleNavigate_AdapterServedTab_NewTab_ClosesUnusedBlankTab(t *testing.T) {+ m := &mockBridge{navigateResult: &bridge.NavigateResult{+ TabID: "lite-1",+ URL: "http://localhost:3000/",+ Title: "Static Page",+ }}+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp["tabId"] != "lite-1" {+ t.Fatalf("tabId = %v, want lite-1 (adapter-served tab)", resp["tabId"])+ }+ if len(m.createTabURLs) == 0 {+ t.Fatal("expected the blank Chrome tab to have been created before Navigate")+ }+ if len(m.closedTabs) != 1 || m.closedTabs[0] != "tab_abc12345" {+ t.Fatalf("closedTabs = %v, want the unused blank tab [tab_abc12345]", m.closedTabs)+ }+}++// When the adapter's result identifies the same tab the handler drove (chrome,+// cloak, escalated ghost-chrome), the normal response path is unchanged.+func TestHandleNavigate_SameTabResult_NormalPathUnchanged(t *testing.T) {+ m := &mockBridge{navigateResult: &bridge.NavigateResult{+ TabID: "tab_abc12345",+ URL: "http://localhost:3000/",+ Title: "Chrome Page",+ }}+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp["tabId"] != "tab_abc12345" {+ t.Fatalf("tabId = %v, want tab_abc12345 (handler-driven tab)", resp["tabId"])+ }+ if len(m.closedTabs) != 0 {+ t.Fatalf("no tab should be closed on the same-tab path, closed %v", m.closedTabs)+ }+}++// --- explicit-browser vs running-browser conflict (H6) ---++func TestHandleNavigate_ExplicitBrowserConflictsWithRunning_409(t *testing.T) {+ m := &mockBridge{runningBrowser: config.BrowserChrome}+ h := New(m, &config.RuntimeConfig{+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak},+ }, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000","browser":"cloak"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusConflict {+ t.Fatalf("explicit cloak against running chrome should 409, got %d body=%s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "runningBrowser") {+ t.Fatalf("409 payload missing runningBrowser: %s", w.Body.String())+ }+}++func TestHandleNavigate_ImplicitBrowserIgnoresRunningMismatch(t *testing.T) {+ // Default chrome resolution against a running cloak server must not 409 —+ // only explicit intent conflicts.+ m := &mockBridge{+ runningBrowser: config.BrowserCloak,+ navigateResult: &bridge.NavigateResult{TabID: "tab_abc12345", URL: "http://localhost:3000/"},+ }+ h := New(m, &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak},+ }, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code == http.StatusConflict {+ t.Fatalf("implicit resolution must not 409 against the running browser: %s", w.Body.String())+ }+}++func TestHandleNavigate_ExplicitBrowserMatchesRunning_OK(t *testing.T) {+ m := &mockBridge{+ runningBrowser: config.BrowserCloak,+ navigateResult: &bridge.NavigateResult{TabID: "tab_abc12345", URL: "http://localhost:3000/"},+ }+ h := New(m, &config.RuntimeConfig{+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak},+ }, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000","browser":"cloak"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code == http.StatusConflict {+ t.Fatalf("matching explicit browser must not 409: %s", w.Body.String())+ }+}++func TestHandleNavigate_ExplicitBrowserNothingRunning_OK(t *testing.T) {+ // Before any browser is launched, an explicit param decides the launch.+ m := &mockBridge{+ navigateResult: &bridge.NavigateResult{TabID: "tab_abc12345", URL: "http://localhost:3000/"},+ }+ h := New(m, &config.RuntimeConfig{+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak},+ }, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000","browser":"cloak"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code == http.StatusConflict {+ t.Fatalf("explicit browser with nothing running must not 409: %s", w.Body.String())+ }+}++// --- deferred Chrome launch for static-first navigates (H1b) ---++// A static-accept on a fresh navigate must never launch Chrome.+func TestHandleNavigate_StaticFirstServesWithoutChromeLaunch(t *testing.T) {+ m := &mockBridge{+ staticFirstNavigate: true,+ navigateResult: &bridge.NavigateResult{+ TabID: "lite-1",+ URL: "http://localhost:3000/",+ Title: "Static",+ Route: &browserops.RouteMetadata{RequestedBrowser: "ghost-chrome", UsedBrowser: "ghost-chrome"},+ },+ }+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["tabId"] != "lite-1" {+ t.Fatalf("tabId = %v, want lite-1", resp["tabId"])+ }+ if m.ensureBrowserCall != 0 {+ t.Fatalf("Chrome was launched (%d ensure calls) for a static-served navigate", m.ensureBrowserCall)+ }+ if len(m.createTabURLs) != 0 {+ t.Fatalf("a Chrome tab was created for a static-served navigate: %v", m.createTabURLs)+ }+}++// On escalation the handler launches Chrome, retries with SkipStatic, and the+// route metadata reflects both attempts.+func TestHandleNavigate_StaticFirstEscalatesThroughHandler(t *testing.T) {+ m := &mockBridge{+ staticFirstNavigate: true,+ staticEscalate: &bridge.StaticEscalateError{+ Quality: 20,+ Reason: "thin content",+ Route: &browserops.RouteMetadata{+ RequestedBrowser: "ghost-chrome",+ UsedBrowser: "ghost-chrome",+ Quality: 20,+ Attempts: []browserops.RouteAttempt{+ {Browser: "ghost-chrome", Accepted: false, Reason: "thin content"},+ },+ },+ },+ navigateResult: &bridge.NavigateResult{TabID: "tab_abc12345", URL: "http://localhost:3000/"},+ }+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)++ body := []byte(`{"url":"http://localhost:3000"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ if m.ensureBrowserCall != 1 {+ t.Fatalf("ensure calls = %d, want 1 (escalation launches Chrome)", m.ensureBrowserCall)+ }+ if len(m.navigateParams) != 2 || !m.navigateParams[0].NoEscalate || !m.navigateParams[1].SkipStatic {+ t.Fatalf("expected NoEscalate then SkipStatic navigates, got %+v", m.navigateParams)+ }+ var resp struct {+ Route struct {+ Escalated bool `json:"escalated"`+ Attempts []struct {+ Browser string `json:"browser"`+ } `json:"attempts"`+ } `json:"route"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if !resp.Route.Escalated || len(resp.Route.Attempts) != 2 {+ t.Fatalf("route should show static + chrome attempts with escalated, got %s", w.Body.String())+ }+}diff --git a/internal/handlers/navigation_browsertarget_test.go b/internal/handlers/navigation_browsertarget_test.goindex 35d098e4..fa256252 100644--- a/internal/handlers/navigation_browsertarget_test.go+++ b/internal/handlers/navigation_browsertarget_test.go@@ -67,3 +67,55 @@ func TestHandleNavigate_BrowserTargetIgnored(t *testing.T) {t.Fatalf("expected browserTarget to be ignored (no 409), got 409 body=%s", w.Body.String())}}++// A plain tabId navigate against a tab owned by a non-default-browser instance+// must resolve to the instance's browser instead of 409ing (H5 regression).+func TestHandleNavigate_InstanceBrowserResolvedFromTab(t *testing.T) {+ orch := newOrchWithTab("tab1", &bridge.Instance{ID: "inst1", Browser: config.BrowserCloak})+ m := &mockBridge{navigateResult: &bridge.NavigateResult{+ TabID: "tab1",+ URL: "http://localhost:3000/",+ Title: "Cloak Page",+ }}+ h := New(m, &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak},+ }, nil, nil, orch)++ body := []byte(`{"tabId":"tab1","url":"http://localhost:3000"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code == http.StatusConflict {+ t.Fatalf("plain tabId navigate 409ed against its own instance browser: %s", w.Body.String())+ }+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+}++// An explicit browser param that disagrees with the owning instance still 409s,+// and the payload no longer duplicates instanceBrowser as instanceProvider.+func TestHandleNavigate_ExplicitBrowserConflictStill409(t *testing.T) {+ orch := newOrchWithTab("tab1", &bridge.Instance{ID: "inst1", Browser: config.BrowserCloak})+ h := New(&mockBridge{}, &config.RuntimeConfig{+ DefaultBrowser: config.BrowserChrome,+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak},+ }, nil, nil, orch)++ body := []byte(`{"tabId":"tab1","url":"http://localhost:3000","browser":"chrome"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusConflict {+ t.Fatalf("expected 409 for explicit conflicting browser, got %d body=%s", w.Code, w.Body.String())+ }+ if !bytes.Contains(w.Body.Bytes(), []byte("instanceBrowser")) {+ t.Fatalf("409 payload missing instanceBrowser: %s", w.Body.String())+ }+ if bytes.Contains(w.Body.Bytes(), []byte("instanceProvider")) {+ t.Fatalf("409 payload still contains duplicate instanceProvider key: %s", w.Body.String())+ }+}diff --git a/internal/handlers/navigation_policy.go b/internal/handlers/navigation_policy.goindex 81455db0..39675a9e 100644--- a/internal/handlers/navigation_policy.go+++ b/internal/handlers/navigation_policy.go@@ -92,6 +92,8 @@ func validateNavigateURL(raw string) error {}// validateNavigateTarget delegates to navguard's target validation logic.+// Per-call Validator construction is intentional: trusted CIDRs come from the+// per-request (target-scoped) effective config, not a static startup value.func validateNavigateTarget(raw string, allowExplicitInternal bool, trustedResolveCIDRs []*net.IPNet) (*navguard.ValidatedTarget, error) {v := &navguard.Validator{TrustedResolveCIDRs: trustedResolveCIDRs}return v.ValidateTarget(context.Background(), raw, allowExplicitInternal)diff --git a/internal/handlers/security_parity_test.go b/internal/handlers/security_parity_test.goindex 05965a48..f7b9bb89 100644--- a/internal/handlers/security_parity_test.go+++ b/internal/handlers/security_parity_test.go@@ -19,8 +19,9 @@ type providerSetup struct {Setup func(t *testing.T, cfg *config.RuntimeConfig) *Handlers}-// navigateProviders returns the four provider paths for /navigate tests.-// All four share the same navguard+IDPI code paths before any Browser or+// navigateProviders returns the provider paths for /navigate security tests+// (chrome and cloak — ghost-chrome has no parity coverage here yet, a known+// gap). Both share the same navguard+IDPI code paths before any Browser or// Chrome call is made, so the security checks are exercised uniformly.func navigateProviders() []providerSetup {return []providerSetup{@@ -164,13 +165,7 @@ func TestSecurityParity_Navigate_TrustedResolveCIDRBypassesPrivateIP(t *testing.return []net.IP{net.ParseIP("10.0.0.5")}, nil})- // Only test chrome/cloak providers here. Ghost-chrome providers pass the- // SSRF check (which is the point of this test) but then try to actually- // connect to the hostname via Browser, which times out since the- // host does not exist. Chrome/cloak use the mockBridge and return immediately.- chromeAndCloak := navigateProviders()[:2]-- for _, p := range chromeAndCloak {+ for _, p := range navigateProviders() {t.Run(p.Name, func(t *testing.T) {cfg := &config.RuntimeConfig{TrustedResolveCIDRs: []string{"10.0.0.0/8"},diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex 68b4a335..7248f0b8 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -71,6 +71,9 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if sess, ok := session.FromRequest(r); ok && sess != nil {sessionBrowser = sess.Browser}+ if h.rejectBrowserConflictWithRunning(w, requestBrowser, sessionBrowser) {+ return+ }var instanceBrowser stringtabID := r.URL.Query().Get("tabId")if tabID != "" && h.Orchestrator != nil {diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex e973852a..49c8b726 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -30,6 +30,9 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {if sess, ok := session.FromRequest(r); ok && sess != nil {sessionBrowser = sess.Browser}+ if h.rejectBrowserConflictWithRunning(w, requestBrowser, sessionBrowser) {+ return+ }var instanceBrowser stringtabID := r.URL.Query().Get("tabId")if tabID != "" && h.Orchestrator != nil {diff --git a/internal/navguard/guard_integration_test.go b/internal/navguard/guard_integration_test.goindex e7c9294e..1a039e4b 100644--- a/internal/navguard/guard_integration_test.go+++ b/internal/navguard/guard_integration_test.go@@ -47,17 +47,16 @@ func TestIntegration_FullPipeline_PrivateIPBlocked(t *testing.T) {return []net.IP{net.ParseIP("192.168.1.1")}, nil})- v := &Validator{- IDPIDomainAllowed: func(rawURL string) bool { return false },- }+ domainAllowed := func(rawURL string) bool { return false }+ v := &Validator{}rawURL := "https://internal-service.example.com/api"if err := v.ValidateURL(rawURL); err != nil {t.Fatalf("ValidateURL failed: %v", err)}- // Simulate the caller checking IDPIDomainAllowed to decide allowExplicitInternal- allowInternal := v.IDPIDomainAllowed(rawURL)+ // The caller computes allowExplicitInternal from its IDPI domain allowlist.+ allowInternal := domainAllowed(rawURL)_, err := v.ValidateTarget(context.Background(), rawURL, allowInternal)if err == nil {t.Fatal("expected ValidateTarget to block private IP when IDPIDomainAllowed=false")@@ -65,23 +64,22 @@ func TestIntegration_FullPipeline_PrivateIPBlocked(t *testing.T) {}func TestIntegration_FullPipeline_AllowedDomainPermitsPrivateIP(t *testing.T) {- // URL resolves to private IP BUT IDPIDomainAllowed returns true → allowed+ // URL resolves to private IP BUT the caller's domain allowlist permits it// This is the "allowed domain permits navigation" scenariostubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {return []net.IP{net.ParseIP("192.168.1.1")}, nil})- v := &Validator{- IDPIDomainAllowed: func(rawURL string) bool { return true },- }+ domainAllowed := func(rawURL string) bool { return true }+ v := &Validator{}rawURL := "https://trusted-internal.corp.example.com/dashboard"if err := v.ValidateURL(rawURL); err != nil {t.Fatalf("ValidateURL failed: %v", err)}- // Caller uses IDPIDomainAllowed to decide allowExplicitInternal- allowInternal := v.IDPIDomainAllowed(rawURL)+ // The caller computes allowExplicitInternal from its IDPI domain allowlist.+ allowInternal := domainAllowed(rawURL)target, err := v.ValidateTarget(context.Background(), rawURL, allowInternal)if err != nil {t.Fatalf("expected allowed domain to permit private IP, got %v", err)@@ -92,7 +90,7 @@ func TestIntegration_FullPipeline_AllowedDomainPermitsPrivateIP(t *testing.T) {// When allowExplicitInternal=true, TrustedResolvedIP is set but AllowInternal is NOT set// (AllowInternal is only set for localhost-class URLs)if target.AllowInternal {- t.Fatal("allowed domain via IDPIDomainAllowed should not set AllowInternal (only localhost does)")+ t.Fatal("allowed domain should not set AllowInternal (only localhost does)")}if len(target.TrustedResolvedIP) != 1 || target.TrustedResolvedIP[0] != netip.MustParseAddr("192.168.1.1") {t.Fatalf("expected TrustedResolvedIP=[192.168.1.1], got %v", target.TrustedResolvedIP)@@ -102,11 +100,7 @@ func TestIntegration_FullPipeline_AllowedDomainPermitsPrivateIP(t *testing.T) {func TestIntegration_FullPipeline_RemoteIPValidation(t *testing.T) {// After navigation starts, remote IP comes back as 10.0.0.1// No trusted CIDRs → ValidateRemoteIP blocks- v := &Validator{- TrustedProxyCIDRs: nil,- }-- err := v.ValidateRemoteIP("10.0.0.1", nil)+ err := ValidateRemoteIP("10.0.0.1", nil, nil)if err == nil {t.Fatal("expected ValidateRemoteIP to block private remote IP with no trusted CIDRs")}@@ -115,15 +109,15 @@ func TestIntegration_FullPipeline_RemoteIPValidation(t *testing.T) {func TestIntegration_FullPipeline_TrustedCIDRBypass(t *testing.T) {// URL resolves to 10.0.0.5// TrustedResolveCIDRs includes 10.0.0.0/24- // IDPIDomainAllowed returns false (no domain allowlist)+ // The caller's domain allowlist says no (no domain allowlist)// Should be allowed via CIDR bypassstubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {return []net.IP{net.ParseIP("10.0.0.5")}, nil})+ domainAllowed := func(rawURL string) bool { return false }v := &Validator{TrustedResolveCIDRs: ParseCIDRs([]string{"10.0.0.0/24"}),- IDPIDomainAllowed: func(rawURL string) bool { return false },}rawURL := "https://k8s-service.internal.example.com/health"@@ -131,8 +125,8 @@ func TestIntegration_FullPipeline_TrustedCIDRBypass(t *testing.T) {t.Fatalf("ValidateURL failed: %v", err)}- // Even though IDPIDomainAllowed returns false, TrustedResolveCIDRs should allow- allowInternal := v.IDPIDomainAllowed(rawURL) // false+ // Even though the domain allowlist says no, TrustedResolveCIDRs should allow+ allowInternal := domainAllowed(rawURL) // falsetarget, err := v.ValidateTarget(context.Background(), rawURL, allowInternal)if err != nil {t.Fatalf("expected TrustedResolveCIDRs to bypass private IP block, got %v", err)@@ -148,7 +142,7 @@ func TestIntegration_FullPipeline_TrustedCIDRBypass(t *testing.T) {}// Verify that the remote IP validation also passes for this trusted resolved IP- if err := v.ValidateRemoteIP("10.0.0.5", target.TrustedResolvedIP); err != nil {+ if err := ValidateRemoteIP("10.0.0.5", nil, target.TrustedResolvedIP); err != nil {t.Fatalf("expected runtime remote IP check to pass for trusted resolved IP, got %v", err)}}diff --git a/internal/navguard/navguard_test.go b/internal/navguard/navguard_test.goindex 2d6218e6..df5128ff 100644--- a/internal/navguard/navguard_test.go+++ b/internal/navguard/navguard_test.go@@ -280,20 +280,19 @@ func TestParseCIDRs_TreatsBareIPsAsSingleHosts(t *testing.T) {}}-// --- IDPIDomainAllowed + RemoteIP Scenario Tests ---+// --- Domain-allowed + RemoteIP Scenario Tests ---func TestValidateTarget_DomainAllowedCallbackPermitsPrivateIP(t *testing.T) {- // When IDPIDomainAllowed returns true for the URL,- // navigation to a private IP is permitted via allowExplicitInternal.+ // Callers compute allowExplicitInternal from the IDPI domain allowlist+ // (handlers use idpi Guard.DomainAllowed); modeled here as a local callback.stubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {return []net.IP{net.ParseIP("192.168.1.100")}, nil})- v := &Validator{- IDPIDomainAllowed: func(rawURL string) bool { return true },- }+ domainAllowed := func(rawURL string) bool { return true }+ v := &Validator{}rawURL := "https://allowed.corp.example.com/internal"- allowInternal := v.IDPIDomainAllowed(rawURL)+ allowInternal := domainAllowed(rawURL)target, err := v.ValidateTarget(context.Background(), rawURL, allowInternal)if err != nil {t.Fatalf("expected domain-allowed callback to permit private IP, got %v", err)@@ -311,20 +310,19 @@ func TestValidateTarget_DomainAllowedCallbackPermitsPrivateIP(t *testing.T) {}func TestValidateTarget_DomainNotAllowedBlocksPrivateIP(t *testing.T) {- // When IDPIDomainAllowed returns false for the URL AND no trusted CIDRs,+ // When the caller's domain allowlist says no AND no trusted CIDRs,// navigation to a private IP is blocked.stubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {return []net.IP{net.ParseIP("192.168.1.100")}, nil})- v := &Validator{- IDPIDomainAllowed: func(rawURL string) bool { return false },- }+ domainAllowed := func(rawURL string) bool { return false }+ v := &Validator{}rawURL := "https://untrusted.example.com/internal"- allowInternal := v.IDPIDomainAllowed(rawURL)+ allowInternal := domainAllowed(rawURL)_, err := v.ValidateTarget(context.Background(), rawURL, allowInternal)if err == nil {- t.Fatal("expected private IP to be blocked when IDPIDomainAllowed=false and no trusted CIDRs")+ t.Fatal("expected private IP to be blocked when the domain is not allowlisted and no trusted CIDRs")}}diff --git a/internal/navguard/remote_ip.go b/internal/navguard/remote_ip.goindex 16f60d8f..cb229364 100644--- a/internal/navguard/remote_ip.go+++ b/internal/navguard/remote_ip.go@@ -10,13 +10,7 @@ import ()// ValidateRemoteIP checks that the response RemoteIPAddress is a public IP or-// falls within trusted CIDRs / pre-resolved IPs. It uses the Validator's-// TrustedProxyCIDRs.-func (v *Validator) ValidateRemoteIP(raw string, trustedResolved []netip.Addr) error {- return ValidateRemoteIP(raw, v.TrustedProxyCIDRs, trustedResolved)-}--// ValidateRemoteIP is the standalone (non-method) remote IP validator.+// falls within trusted CIDRs / pre-resolved IPs.func ValidateRemoteIP(raw string, trustedCIDRs []*net.IPNet, trustedIPs []netip.Addr) error {normalized := netguard.NormalizeRemoteIP(raw)if err := netguard.ValidateRemoteIPAddress(raw); err != nil {diff --git a/internal/navguard/target.go b/internal/navguard/target.goindex 74acce94..4060514c 100644--- a/internal/navguard/target.go+++ b/internal/navguard/target.go@@ -14,8 +14,10 @@ import ()// ValidateTarget resolves a navigation URL's target host and enforces SSRF-// protections. It uses the Validator's TrustedResolveCIDRs and IDPIDomainAllowed.-// allowExplicitInternal overrides the private-IP block for explicitly allowed domains.+// protections using the Validator's TrustedResolveCIDRs. IDPI domain+// allowlisting happens upstream: callers compute allowExplicitInternal from+// the IDPI allowlist (handlers derive it via idpi Guard.DomainAllowed) and it+// overrides the private-IP block for explicitly allowed domains.func (v *Validator) ValidateTarget(ctx context.Context, raw string, allowExplicitInternal bool) (*ValidatedTarget, error) {return ValidateTarget(ctx, raw, allowExplicitInternal, v.TrustedResolveCIDRs)}diff --git a/internal/navguard/validator.go b/internal/navguard/validator.goindex e67216a6..960ab6ed 100644--- a/internal/navguard/validator.go+++ b/internal/navguard/validator.go@@ -5,13 +5,13 @@ import ("net/netip")-// Validator carries pre-parsed security configuration for navigation URL, target,-// and remote-IP validation. It is safe for concurrent use when fields are not mutated-// after construction.+// Validator carries pre-parsed security configuration for navigation target+// validation. Handlers construct one per call because trusted CIDRs come from+// the per-request (target-scoped) effective config; remote-IP validation uses+// the standalone ValidateRemoteIP function. It is safe for concurrent use when+// fields are not mutated after construction.type Validator struct {TrustedResolveCIDRs []*net.IPNet- TrustedProxyCIDRs []*net.IPNet- IDPIDomainAllowed func(rawURL string) bool // nil = no IDPI check}// ValidatedTarget is the result of ValidateTarget. It signals which runtimediff --git a/internal/netguard/netguard.go b/internal/netguard/netguard.goindex 00c6808b..2b0446e2 100644--- a/internal/netguard/netguard.go+++ b/internal/netguard/netguard.go@@ -140,6 +140,12 @@ func NormalizeRemoteIP(raw string) string {func ValidateRemoteIPAddress(raw string) error {raw = NormalizeRemoteIP(raw)if raw == "" {+ // Accepted by design: CDP reports no remote IP for cache- and+ // service-worker-served responses, so erroring here would break+ // legitimate cached navigations. This post-connect check is the last+ // of several layers (URL validation, resolve-time checks with pinned+ // IPs, dial-time enforcement on the static path); the residual+ // exposure is a cached/SW response for an already-validated target.return nil}ip := net.ParseIP(raw)