Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

12.3 KB
Raw Blame
package handlers

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/pinchtab/pinchtab/internal/activity"
	"github.com/pinchtab/pinchtab/internal/bridge"
	"github.com/pinchtab/pinchtab/internal/config"
	"github.com/pinchtab/pinchtab/internal/session"
)

type scopedCurrentTabBridge struct {
	bridge.BridgeAPI
	tabs       map[string]context.Context
	requested  []string
	created    []string
	closed     []string
	globalTab  string
	ensureCall int
}

func newScopedCurrentTabBridge() *scopedCurrentTabBridge {
	return &scopedCurrentTabBridge{
		tabs: map[string]context.Context{
			"global":       context.Background(),
			"tab-agent":    context.Background(),
			"tab-session":  context.Background(),
			"tab-explicit": context.Background(),
		},
		globalTab: "global",
	}
}

func (b *scopedCurrentTabBridge) GetDialogManager() *bridge.DialogManager { return nil }

func (b *scopedCurrentTabBridge) TabContext(tabID string) (*bridge.TabHandle, string, error) {
	if tabID == "" {
		tabID = b.globalTab
	}
	b.requested = append(b.requested, tabID)
	ctx, ok := b.tabs[tabID]
	if !ok {
		return nil, "", fmt.Errorf("tab not found")
	}
	return bridge.NewTabHandle(ctx), tabID, nil
}

func (b *scopedCurrentTabBridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
	b.created = append(b.created, url)
	tabID := fmt.Sprintf("tab-created-%d", len(b.created))
	ctx := context.Background()
	b.tabs[tabID] = ctx
	return tabID, ctx, func() {}, nil
}

func (b *scopedCurrentTabBridge) CloseTab(tabID string) error {
	b.closed = append(b.closed, tabID)
	delete(b.tabs, tabID)
	return nil
}

func (b *scopedCurrentTabBridge) FocusTab(tabID string) error {
	if _, ok := b.tabs[tabID]; !ok {
		return fmt.Errorf("tab not found")
	}
	return nil
}

func (b *scopedCurrentTabBridge) EnsureBrowser(*config.RuntimeConfig) error {
	b.ensureCall++
	return nil
}

func (b *scopedCurrentTabBridge) RestartBrowser(*config.RuntimeConfig) error { return nil }

func (b *scopedCurrentTabBridge) ListTargets() ([]bridge.TabTarget, error) {
	return []bridge.TabTarget{
		{TargetID: "global", Type: "page"},
		{TargetID: "tab-agent", Type: "page"},
		{TargetID: "tab-session", Type: "page"},
		{TargetID: "tab-explicit", Type: "page"},
	}, nil
}

func (b *scopedCurrentTabBridge) Evaluate(ctx context.Context, expression string, result any, opts bridge.EvalOpts) error {
	return nil
}
func (b *scopedCurrentTabBridge) AvailableActions() []string             { return nil }
func (b *scopedCurrentTabBridge) TabLockInfo(string) *bridge.LockInfo    { return nil }
func (b *scopedCurrentTabBridge) DeleteRefCache(string)                  {}
func (b *scopedCurrentTabBridge) NetworkMonitor() *bridge.NetworkMonitor { return nil }

func (b *scopedCurrentTabBridge) CallFunctionOnNode(ctx context.Context, backendNodeID int64, functionDecl string, args []map[string]any, result any) error {
	return fmt.Errorf("not implemented")
}

func (b *scopedCurrentTabBridge) EvaluateInFrame(ctx context.Context, frameID string, expression string, result any, opts bridge.EvalOpts) error {
	return fmt.Errorf("not implemented")
}

func (b *scopedCurrentTabBridge) DescribeNode(ctx context.Context, backendNodeID int64) (*bridge.NodeInfo, error) {
	return nil, fmt.Errorf("not implemented")
}

func (b *scopedCurrentTabBridge) Navigate(ctx context.Context, url string, params bridge.NavigateParams) (*bridge.NavigateResult, error) {
	return nil, fmt.Errorf("not implemented in test mock")
}

func newScopedCurrentTabHandler() (*Handlers, *scopedCurrentTabBridge) {
	b := newScopedCurrentTabBridge()
	return New(b, &config.RuntimeConfig{}, nil, nil, nil), b
}

func TestScopedCurrentTabSessionBeatsAgentID(t *testing.T) {
	h, _ := newScopedCurrentTabHandler()

	agentReq := httptest.NewRequest("GET", "/text", nil)
	agentReq.Header.Set(activity.HeaderAgentID, "agent-1")
	h.setCurrentTabForRequest(agentReq, "tab-agent")

	sessionReq := httptest.NewRequest("GET", "/text", nil)
	sessionReq.Header.Set(activity.HeaderAgentID, "agent-1")
	sessionReq = session.WithSession(sessionReq, &session.Session{ID: "ses_1", AgentID: "agent-1"})
	h.setCurrentTabForRequest(sessionReq, "tab-session")

	_, got, err := h.tabContext(sessionReq, "")
	if err != nil {
		t.Fatalf("session tabContext error = %v", err)
	}
	if got != "tab-session" {
		t.Fatalf("session scoped tab = %q, want tab-session", got)
	}

	_, got, err = h.tabContext(agentReq, "")
	if err != nil {
		t.Fatalf("agent tabContext error = %v", err)
	}
	if got != "tab-agent" {
		t.Fatalf("agent scoped tab = %q, want tab-agent", got)
	}
}

func TestScopedCurrentTabDoesNotFallBackToGlobal(t *testing.T) {
	h, b := newScopedCurrentTabHandler()

	req := httptest.NewRequest("GET", "/text", nil)
	req.Header.Set(activity.HeaderAgentID, "agent-without-current")

	if _, _, err := h.tabContext(req, ""); err == nil {
		t.Fatal("expected missing scoped current tab to fail")
	}
	if len(b.requested) != 0 {
		t.Fatalf("bridge should not be asked for global tab, got requests %v", b.requested)
	}
}

// trustedSessionRequest builds a request that mimics a trusted-internal-proxy
// hop carrying a session id header. Public callers cannot fabricate this;
// the marker is set on the orchestrator → instance hop after auth.
func trustedSessionRequest(method, path, sessionID string, body []byte) *http.Request {
	var req *http.Request
	if body != nil {
		req = httptest.NewRequest(method, path, bytes.NewReader(body))
	} else {
		req = httptest.NewRequest(method, path, nil)
	}
	req.Header.Set(activity.HeaderPTSessionID, sessionID)
	return req.WithContext(MarkTrustedInternalProxy(req.Context()))
}

func TestExplicitTabUpdatesScopedCurrentTab(t *testing.T) {
	h, _ := newScopedCurrentTabHandler()

	req := trustedSessionRequest("GET", "/text", "ses_header", nil)

	if _, got, err := h.tabContext(req, "tab-explicit"); err != nil || got != "tab-explicit" {
		t.Fatalf("explicit tabContext = %q, %v; want tab-explicit, nil", got, err)
	}

	if _, got, err := h.tabContext(req, ""); err != nil || got != "tab-explicit" {
		t.Fatalf("scoped current after explicit = %q, %v; want tab-explicit, nil", got, err)
	}
}

func TestClearCurrentTabReferencesClearsAllScopesForTab(t *testing.T) {
	h, _ := newScopedCurrentTabHandler()

	sessionReq := trustedSessionRequest("GET", "/text", "ses_1", nil)
	agentReq := httptest.NewRequest("GET", "/text", nil)
	agentReq.Header.Set(activity.HeaderAgentID, "agent-1")

	h.setCurrentTabForRequest(sessionReq, "tab-explicit")
	h.setCurrentTabForRequest(agentReq, "tab-explicit")
	h.clearCurrentTabReferences("tab-explicit")

	if _, _, err := h.tabContext(sessionReq, ""); err == nil {
		t.Fatal("expected cleared session current tab to fail")
	}
	if _, _, err := h.tabContext(agentReq, ""); err == nil {
		t.Fatal("expected cleared agent current tab to fail")
	}
}

func TestNavigateUsesScopedCurrentTabWhenPresent(t *testing.T) {
	h, b := newScopedCurrentTabHandler()

	req := trustedSessionRequest("POST", "/navigate", "ses_1", []byte(`{"url":"about:blank"}`))
	h.setCurrentTabForRequest(req, "tab-session")

	w := httptest.NewRecorder()
	h.HandleNavigate(w, req)

	if len(b.created) != 0 {
		t.Fatalf("navigate should reuse scoped current tab, created tabs %v", b.created)
	}
	if len(b.requested) == 0 || b.requested[0] != "tab-session" {
		t.Fatalf("navigate requested tabs = %v, want first tab-session", b.requested)
	}
}

func TestNavigateCreatesTabWhenIdentifiedCallerHasNoCurrentTab(t *testing.T) {
	h, b := newScopedCurrentTabHandler()

	req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{"url":"about:blank"}`)))
	req.Header.Set(activity.HeaderAgentID, "agent-without-current")

	w := httptest.NewRecorder()
	h.HandleNavigate(w, req)

	if len(b.created) != 1 {
		t.Fatalf("navigate should create a tab when scoped current is absent, created %v", b.created)
	}
}

func TestCurrentTabStore_LRUCapEvictsOldest(t *testing.T) {
	store := NewCurrentTabStore()
	store.SetCap(2)

	scopes := []currentTabScope{
		scopedCurrentTab(currentTabScopeAgent, "a"),
		scopedCurrentTab(currentTabScopeAgent, "b"),
		scopedCurrentTab(currentTabScopeAgent, "c"),
	}
	for i, sc := range scopes {
		store.Set(sc, fmt.Sprintf("tab-%d", i))
	}

	// First entry must be evicted; last two survive.
	if _, ok := store.Get(scopes[0]); ok {
		t.Fatal("oldest entry should have been evicted by LRU cap")
	}
	if _, ok := store.Get(scopes[1]); !ok {
		t.Fatal("middle entry should remain")
	}
	if _, ok := store.Get(scopes[2]); !ok {
		t.Fatal("newest entry should remain")
	}
}

func TestCurrentTabStore_GetBumpsRecency(t *testing.T) {
	store := NewCurrentTabStore()
	store.SetCap(2)

	a := scopedCurrentTab(currentTabScopeAgent, "a")
	b := scopedCurrentTab(currentTabScopeAgent, "b")
	c := scopedCurrentTab(currentTabScopeAgent, "c")

	store.Set(a, "tab-a")
	store.Set(b, "tab-b")
	// Touch 'a' so it's now the most recently used; b is the LRU.
	if _, ok := store.Get(a); !ok {
		t.Fatal("a should still be present")
	}
	store.Set(c, "tab-c") // forces eviction of LRU = b

	if _, ok := store.Get(b); ok {
		t.Fatal("b should have been evicted, not a")
	}
	if _, ok := store.Get(a); !ok {
		t.Fatal("a should have survived because Get bumped recency")
	}
	if _, ok := store.Get(c); !ok {
		t.Fatal("c should be present")
	}
}

// TestUntrustedSessionHeaderIgnored guards the spoof case: a public client
// who manages to set X-PinchTab-Session-Id without the trusted-internal
// marker must NOT have the header honored as identity.
func TestUntrustedSessionHeaderIgnored(t *testing.T) {
	h, _ := newScopedCurrentTabHandler()

	trusted := trustedSessionRequest("GET", "/text", "ses_owner", nil)
	h.setCurrentTabForRequest(trusted, "tab-explicit")

	// Untrusted request claims the same session id but lacks the marker.
	spoofed := httptest.NewRequest("GET", "/text", nil)
	spoofed.Header.Set(activity.HeaderPTSessionID, "ses_owner")

	if got, ok := h.scopedCurrentTabForRequest(spoofed); ok {
		t.Fatalf("untrusted header must not resolve to %q", got)
	}
}

// TestCurrentTabStore_EvictsInTouchOrderWithoutSleeping pins the invariant the
// wall-clock recency signal could not hold: eviction order must follow the
// order entries were touched, not how fast they were touched.
//
// The old signal was time.Now(). Every touch here lands inside a single clock
// tick — ~15.6ms on Windows, wide enough for far more traffic than this — so
// every entry compared equal, no entry was Before any other, and eviction fell
// through to Go's randomized map iteration. Entries survived or died at random
// while the store still claimed to be an LRU.
//
// No sleeps: a test that has to pause to let a clock advance is measuring the
// clock, and the store must not need one.
func TestCurrentTabStore_EvictsInTouchOrderWithoutSleeping(t *testing.T) {
	const (
		capacity = 10
		total    = 50
	)
	store := NewCurrentTabStore()
	store.SetCap(capacity)

	scopes := make([]currentTabScope, total)
	for i := range scopes {
		scopes[i] = scopedCurrentTab(currentTabScopeAgent, fmt.Sprintf("agent-%02d", i))
		store.Set(scopes[i], fmt.Sprintf("tab-%02d", i))
	}

	// Exactly the last `capacity` writes survive; everything older is gone.
	for i := 0; i < total-capacity; i++ {
		if _, ok := store.Get(scopes[i]); ok {
			t.Fatalf("scope %d should have been evicted; only the newest %d survive", i, capacity)
		}
	}
	for i := total - capacity; i < total; i++ {
		if _, ok := store.Get(scopes[i]); !ok {
			t.Fatalf("scope %d should have survived; only the oldest %d are evicted", i, total-capacity)
		}
	}
}

// Get is a touch, so reading an entry has to move it out of eviction's way even
// when every read happens within one clock tick.
func TestCurrentTabStore_GetBumpsRecencyWithoutSleeping(t *testing.T) {
	const capacity = 4
	store := NewCurrentTabStore()
	store.SetCap(capacity)

	scopes := make([]currentTabScope, capacity)
	for i := range scopes {
		scopes[i] = scopedCurrentTab(currentTabScopeAgent, fmt.Sprintf("agent-%d", i))
		store.Set(scopes[i], fmt.Sprintf("tab-%d", i))
	}

	// Touch the oldest entry, then push the cap. The entry just read must
	// outlive the one that has not been touched since it was written.
	if _, ok := store.Get(scopes[0]); !ok {
		t.Fatal("scope 0 should still be present before the bump")
	}
	store.Set(scopedCurrentTab(currentTabScopeAgent, "agent-new"), "tab-new")

	if _, ok := store.Get(scopes[0]); !ok {
		t.Error("the entry Get touched was evicted; Get did not bump recency")
	}
	if _, ok := store.Get(scopes[1]); ok {
		t.Error("scope 1 was the least recently used and should have been evicted")
	}
}