High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(orchestrator): front-door tab routing walks the UI-filtered /tabs list, so a tab on about:blank, file:// or the instance's own port cannot be navigated or closed through the server; fetch the unfiltered set for owner lookup (PIN-429)
Luigi Agostid368565fb03c
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.goindex 9ed8b5e7..287cbbf6 100644--- a/internal/handlers/health_tabs.go+++ b/internal/handlers/health_tabs.go@@ -19,6 +19,12 @@ type currentTabReader interface {var _ currentTabReader = (*bridge.Bridge)(nil)+const IncludeTransientTabsQuery = "includeTransient"++func includeTransientTabs(r *http.Request) bool {+ return r.URL.Query().Get(IncludeTransientTabsQuery) == "1"+}+func (h *Handlers) listedCurrentTabID(r *http.Request, targets []bridge.TabTarget) string {if !currentTabScopeFromRequest(r).IsGlobal() {tabID, _ := h.scopedCurrentTabForRequest(r)@@ -183,10 +189,11 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {}currentTabID := h.listedCurrentTabID(r, targets)+ keepTransient := includeTransientTabs(r)tabs := make([]map[string]any, 0, len(targets))appendTab := func(t bridge.TabTarget) {- if bridge.IsTransientURL(t.URL, h.Config.Port) {+ if !keepTransient && bridge.IsTransientURL(t.URL, h.Config.Port) {return}tabID := t.TargetIDdiff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex f682901b..bac5ba9f 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -172,6 +172,52 @@ func TestHandleTabs_Success(t *testing.T) {}}+func TestHandleTabs_TransientTabsListedOnlyWhenFlagged(t *testing.T) {+ targets := []bridge.TabTarget{+ {TargetID: "real", URL: "https://example.com/", Type: "page"},+ {TargetID: "blank", URL: "about:blank", Type: "page"},+ {TargetID: "file", URL: "file:///tmp/page.html", Type: "page"},+ {TargetID: "own-port", URL: "http://localhost:9867/dashboard", Type: "page"},+ }+ cases := []struct {+ name string+ query string+ want []string+ }{+ {name: "default", query: "", want: []string{"real"}},+ {name: "flagged", query: "?" + IncludeTransientTabsQuery + "=1", want: []string{"real", "blank", "file", "own-port"}},+ {name: "flag off", query: "?" + IncludeTransientTabsQuery + "=0", want: []string{"real"}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ h := &Handlers{+ Bridge: &MockBridge{targets: targets, currentTabID: "real"},+ Config: &config.RuntimeConfig{Port: "9867"},+ }+ w := httptest.NewRecorder()+ h.HandleTabs(w, httptest.NewRequest("GET", "/tabs"+tc.query, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())+ }+ var resp struct {+ Tabs []struct {+ ID string `json:"id"`+ } `json:"tabs"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ got := make([]string, 0, len(resp.Tabs))+ for _, tab := range resp.Tabs {+ got = append(got, tab.ID)+ }+ if fmt.Sprint(got) != fmt.Sprint(tc.want) {+ t.Fatalf("tabs = %v, want %v", got, tc.want)+ }+ })+ }+}+func TestHandleTabs_EnsureBrowserFailureStopsBeforeEnumeration(t *testing.T) {mockBridge := &MockBridge{ensureBrowserErr: "attach failed"}h := &Handlers{Bridge: mockBridge, Config: &config.RuntimeConfig{}}diff --git a/internal/orchestrator/health_transport.go b/internal/orchestrator/health_transport.goindex eaae3c7b..b2c125ef 100644--- a/internal/orchestrator/health_transport.go+++ b/internal/orchestrator/health_transport.go@@ -11,6 +11,7 @@ import ("github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/handlers""github.com/pinchtab/pinchtab/internal/sanitize")@@ -38,11 +39,15 @@ type memoryMetrics struct {}func (o *Orchestrator) instanceGet(ctx context.Context, inst *InstanceInternal, path string) (*http.Response, error) {- return o.instanceRequest(ctx, http.MethodGet, inst, path, nil)+ return o.instanceQueryRequest(ctx, http.MethodGet, inst, path, "", nil)}func (o *Orchestrator) instanceRequest(ctx context.Context, method string, inst *InstanceInternal, path string, header http.Header) (*http.Response, error) {- target, err := o.instancePathURL(inst, path, "")+ return o.instanceQueryRequest(ctx, method, inst, path, "", header)+}++func (o *Orchestrator) instanceQueryRequest(ctx context.Context, method string, inst *InstanceInternal, path, rawQuery string, header http.Header) (*http.Response, error) {+ target, err := o.instancePathURL(inst, path, rawQuery)if err != nil {return nil, err}@@ -59,7 +64,15 @@ func (o *Orchestrator) instanceRequest(ctx context.Context, method string, inst}func (o *Orchestrator) fetchTabs(inst *InstanceInternal) ([]remoteTab, error) {- resp, err := o.instanceGet(context.Background(), inst, "/tabs")+ return o.fetchTabList(inst, "")+}++func (o *Orchestrator) fetchOwnedTabs(inst *InstanceInternal) ([]remoteTab, error) {+ return o.fetchTabList(inst, handlers.IncludeTransientTabsQuery+"=1")+}++func (o *Orchestrator) fetchTabList(inst *InstanceInternal, rawQuery string) ([]remoteTab, error) {+ resp, err := o.instanceQueryRequest(context.Background(), http.MethodGet, inst, "/tabs", rawQuery, nil)if err != nil {return nil, err}diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex 56940d2d..55e8cfe7 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -185,12 +185,12 @@ func (o *Orchestrator) findRunningInstanceByTabID(tabID string) (*InstanceInterno.mu.RUnlock()for _, inst := range instances {- tabs, err := o.fetchTabs(inst)+ tabs, err := o.fetchOwnedTabs(inst)if err != nil {continue}for _, tab := range tabs {- if tab.ID == tabID || o.idMgr.TabIDFromCDPTarget(tab.ID) == tabID {+ if tab.ID == tabID {return inst, nil}}diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.goindex 12d77981..e4e69446 100644--- a/internal/orchestrator/proxy_test.go+++ b/internal/orchestrator/proxy_test.go@@ -1,6 +1,7 @@package orchestratorimport (+ "encoding/json""fmt""io""net"@@ -15,9 +16,64 @@ import ("github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/handlers""github.com/pinchtab/pinchtab/internal/session")+func TestFindRunningInstanceByTabID_SeesTransientTabs(t *testing.T) {+ cases := []struct {+ name string+ url func(port string) string+ }{+ {name: "about:blank", url: func(string) string { return "about:blank" }},+ {name: "file", url: func(string) string { return "file:///tmp/page.html" }},+ {name: "own port", url: func(port string) string { return "http://localhost:" + port + "/dashboard" }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ orig := processAliveFunc+ processAliveFunc = func(int) bool { return true }+ defer func() { processAliveFunc = orig }()++ o := NewOrchestrator(t.TempDir())+ addInstance := func(id string, tabURL func(port string) string) {+ var port atomic.Value+ backend, p := startLocalHTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/tabs" {+ http.NotFound(w, r)+ return+ }+ own, _ := port.Load().(string)+ u := tabURL(own)+ tabs := []map[string]string{}+ if r.URL.Query().Get(handlers.IncludeTransientTabsQuery) == "1" || !bridge.IsTransientURL(u, own) {+ tabs = append(tabs, map[string]string{"id": id + "-tab", "url": u})+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"tabs": tabs})+ }))+ t.Cleanup(backend.Close)+ port.Store(p)+ o.instances[id] = &InstanceInternal{+ Instance: bridge.Instance{ID: id, Status: "running", Port: p},+ URL: "http://localhost:" + p,+ cmd: &mockCmd{pid: 1234, isAlive: true},+ }+ }+ addInstance("inst_real", func(string) string { return "https://example.com/" })+ addInstance("inst_transient", tc.url)++ inst, err := o.findRunningInstanceByTabID("inst_transient-tab")+ if err != nil {+ t.Fatalf("findRunningInstanceByTabID: %v", err)+ }+ if inst.ID != "inst_transient" {+ t.Fatalf("owner = %q, want inst_transient", inst.ID)+ }+ })+ }+}+func TestProxyResponseTracksOnlySuccessfullyCreatedSessionTabs(t *testing.T) {o := NewOrchestrator(t.TempDir())diff --git a/internal/strategy/proxy_flow.go b/internal/strategy/proxy_flow.goindex 6c2de083..3c5bb0ea 100644--- a/internal/strategy/proxy_flow.go+++ b/internal/strategy/proxy_flow.go@@ -5,6 +5,7 @@ import ("net/http""github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/handlers""github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/orchestrator")@@ -44,5 +45,16 @@ func ProxyTabsToFirst(o *orchestrator.Orchestrator, w http.ResponseWriter, r *hthttpx.JSON(w, 200, map[string]any{"tabs": []any{}})return}- o.ProxyToTarget(w, r, target+"/tabs")+ o.ProxyToTarget(w, withoutIncludeTransientTabs(r), target+"/tabs")+}++func withoutIncludeTransientTabs(r *http.Request) *http.Request {+ query := r.URL.Query()+ if !query.Has(handlers.IncludeTransientTabsQuery) {+ return r+ }+ query.Del(handlers.IncludeTransientTabsQuery)+ stripped := r.Clone(r.Context())+ stripped.URL.RawQuery = query.Encode()+ return stripped}diff --git a/internal/strategy/proxy_flow_test.go b/internal/strategy/proxy_flow_test.goindex c64f3859..529ce98c 100644--- a/internal/strategy/proxy_flow_test.go+++ b/internal/strategy/proxy_flow_test.go@@ -9,7 +9,9 @@ import ("strings""testing"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/handlers""github.com/pinchtab/pinchtab/internal/orchestrator""github.com/pinchtab/pinchtab/internal/strategy")@@ -113,3 +115,44 @@ func TestProxyTabsToFirst_UnknownBrowser_ReturnsResolveError(t *testing.T) {t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String())}}++func TestProxyTabsToFirst_DropsIncludeTransientBeforeTheInstanceHop(t *testing.T) {+ queries := make(chan string, 8)+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/tabs" && r.Header.Get(activity.HeaderPTSource) != activity.SourceOrchestrator {+ queries <- r.URL.RawQuery+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"tabs":[]}`)+ }))+ defer backend.Close()++ orch := orchestrator.NewOrchestratorWithRunner(t.TempDir(), proxyFlowRunner{})+ orch.ApplyRuntimeConfig(&config.RuntimeConfig{+ AttachEnabled: true,+ AttachAllowHosts: []string{"127.0.0.1"},+ AttachAllowSchemes: []string{"http"},+ })+ if _, _, err := orch.AttachBridge("default", backend.URL, ""); err != nil {+ t.Fatalf("AttachBridge: %v", err)+ }++ cases := []struct {+ query string+ want string+ }{+ {query: "?" + handlers.IncludeTransientTabsQuery + "=1", want: ""},+ {query: "?" + handlers.IncludeTransientTabsQuery + "=1&other=2", want: "other=2"},+ {query: "?other=2", want: "other=2"},+ }+ for _, tc := range cases {+ rec := httptest.NewRecorder()+ strategy.ProxyTabsToFirst(orch, rec, httptest.NewRequest(http.MethodGet, "/tabs"+tc.query, nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("%s: status = %d, want 200: %s", tc.query, rec.Code, rec.Body.String())+ }+ if got := <-queries; got != tc.want {+ t.Fatalf("%s: instance saw query %q, want %q", tc.query, got, tc.want)+ }+ }+}diff --git a/tests/e2e/scenarios/infra/orchestrator-extended.sh b/tests/e2e/scenarios/infra/orchestrator-extended.shindex 23ee9e33..c1282c7c 100644--- a/tests/e2e/scenarios/infra/orchestrator-extended.sh+++ b/tests/e2e/scenarios/infra/orchestrator-extended.sh@@ -86,6 +86,76 @@ assert_ok "stop attached bridge instance"end_test+# ─────────────────────────────────────────────────────────────────+start_test "orchestrator: front door routes about:blank tabs on a second instance"++pt_post /instances/start '{"mode":"headless"}'+assert_ok "start a second instance"+TRANSIENT_INST_ID=$(echo "$RESULT" | jq -r '.id // empty')+wait_for_orchestrator_instance_status "${E2E_SERVER}" "${TRANSIENT_INST_ID}" "running" 60+pt_get /health+TRANSIENT_DEFAULT_ID=$(echo "$RESULT" | jq -r '.defaultInstance.id // empty')+if [ -n "$TRANSIENT_INST_ID" ] && [ -n "$TRANSIENT_DEFAULT_ID" ] && [ "$TRANSIENT_INST_ID" != "$TRANSIENT_DEFAULT_ID" ]; then+ pass_assert "two instances: default ${TRANSIENT_DEFAULT_ID}, second ${TRANSIENT_INST_ID}"+else+ fail_assert "two distinct instances (default '${TRANSIENT_DEFAULT_ID}', second '${TRANSIENT_INST_ID}')"+fi++pt_post "/instances/${TRANSIENT_INST_ID}/tabs/open" '{"url":"about:blank"}'+assert_ok "open about:blank tab to navigate"+assert_tab_id "about:blank tab to navigate returned tabId"+BLANK_NAV_TAB="${TAB_ID}"++pt_post "/instances/${TRANSIENT_INST_ID}/tabs/open" '{"url":"about:blank"}'+assert_ok "open about:blank tab to close"+assert_tab_id "about:blank tab to close returned tabId"+BLANK_CLOSE_TAB="${TAB_ID}"++pt_get "/instances/${TRANSIENT_INST_ID}/tabs"+assert_ok "list second instance tabs"+if echo "$RESULT" | jq -e --arg a "$BLANK_NAV_TAB" --arg b "$BLANK_CLOSE_TAB" 'map(select(.id == $a or .id == $b)) | length == 0' >/dev/null 2>&1; then+ pass_assert "GET /instances/{id}/tabs omits the about:blank tabs"+else+ fail_assert "GET /instances/{id}/tabs omits the about:blank tabs (got $RESULT)"+fi++pt_post "/tabs/${BLANK_NAV_TAB}/navigate" "{\"url\":\"${FIXTURES_URL}/buttons.html\"}"+assert_ok "front-door navigate of an about:blank tab on the second instance"+assert_contains "$RESULT" "buttons.html" "navigate landed on the fixture"++pt_post "/tabs/${BLANK_CLOSE_TAB}/close" '{}'+assert_ok "front-door close of an about:blank tab on the second instance"++pt_get "/screencast/tabs?tabId=${BLANK_NAV_TAB}"+if echo "$RESULT" | jq -e --arg id "$BLANK_CLOSE_TAB" 'type == "array" and (map(select(.id == $id)) | length == 0)' >/dev/null 2>&1; then+ pass_assert "the closed tab is gone from the second instance's Chrome"+else+ fail_assert "the closed tab is gone from the second instance's Chrome (got $RESULT)"+fi+pt_post "/tabs/${BLANK_NAV_TAB}/close" '{}'+assert_ok "close the navigated tab"++pt_post "/instances/${TRANSIENT_DEFAULT_ID}/tabs/open" '{"url":"about:blank"}'+assert_ok "open about:blank tab on the default instance"+assert_tab_id "default-instance about:blank tab returned tabId"+DEFAULT_BLANK_TAB="${TAB_ID}"+for TABS_QUERY in "" "?includeTransient=1"; do+ pt_get "/tabs${TABS_QUERY}"+ assert_ok "public GET /tabs${TABS_QUERY}"+ if echo "$RESULT" | jq -e --arg id "$DEFAULT_BLANK_TAB" '(.tabs | type == "array") and (.tabs | map(select(.id == $id)) | length == 0)' >/dev/null 2>&1; then+ pass_assert "public GET /tabs${TABS_QUERY} omits the about:blank tab"+ else+ fail_assert "public GET /tabs${TABS_QUERY} omits the about:blank tab (got $RESULT)"+ fi+done+pt_post "/tabs/${DEFAULT_BLANK_TAB}/close" '{}'+assert_ok "front-door close of an about:blank tab on the default instance"++pt_post "/instances/${TRANSIENT_INST_ID}/stop" '{}'+assert_ok "stop the second instance"++end_test+# ─────────────────────────────────────────────────────────────────start_test "orchestrator: health shows dashboard mode"