Skip to content

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

fix(tabs): enforce hash-based tab IDs, reject raw CDP IDs

Mario43034b82d1aa
diff --git a/docs/references/tabs-api.md b/docs/references/tabs-api.md
index 08f7390a..18a14036 100644
--- a/docs/references/tabs-api.md
+++ b/docs/references/tabs-api.md
@@ -77,6 +77,39 @@ curl -X POST http://localhost:9867/tabs/tab_abc123/close
---
+## Tab ID Format
+
+Tab IDs use a hash-based format: `tab_XXXXXXXX` (12 characters total).
+
+```
+tab_abc12345
+└─┬─┘└──┬───┘
+ │ └── 8-character hash (derived from internal Chrome target ID)
+ └──────── Prefix identifying resource type
+```
+
+### Why Hash IDs?
+
+1. **Security**: Raw Chrome DevTools Protocol (CDP) target IDs are never exposed. This prevents:
+ - Guessing/brute-forcing tab identifiers
+ - Cross-instance tab access in multi-instance setups
+ - Information leakage about Chrome internals
+
+2. **Consistency**: All PinchTab resources use the same format:
+ - Profiles: `prof_XXXXXXXX`
+ - Instances: `inst_XXXXXXXX`
+ - Tabs: `tab_XXXXXXXX`
+
+3. **Stability**: Hash IDs remain stable for the tab's lifetime
+
+### Important
+
+- Only hash-format IDs are accepted by the API
+- Raw CDP target IDs (32-character hex strings) are **rejected with 404**
+- Tab IDs are scoped to the instance that created them
+
+---
+
## Complete API Reference
### 1. Open Tab
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index dc724e28..ee9f4afe 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -14,11 +14,11 @@ type BridgeAPI interface {
BrowserContext() context.Context
TabContext(tabID string) (ctx context.Context, resolvedID string, err error)
ListTargets() ([]*target.Info, error)
- CreateTab(url string) (tabID string, ctx context.Context, cancel context.CancelFunc, err error)
+ // CreateTab creates a new browser tab and returns a hash-based tab ID (e.g., "tab_XXXXXXXX").
+ // The raw CDP target ID is stored internally and used for CDP operations.
+ CreateTab(url string) (hashTabID string, ctx context.Context, cancel context.CancelFunc, err error)
CloseTab(tabID string) error
- RegisterHashTab(hashID, rawCDPID string, ctx context.Context, cancel context.CancelFunc)
-
GetRefCache(tabID string) *RefCache
SetRefCache(tabID string, cache *RefCache)
DeleteRefCache(tabID string)
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index 682cab09..0d038f16 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -10,6 +10,7 @@ import (
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/idutil"
"github.com/pinchtab/pinchtab/internal/uameta"
)
@@ -31,6 +32,7 @@ type Bridge struct {
BrowserCtx context.Context
BrowserCancel context.CancelFunc
Config *config.RuntimeConfig
+ IdMgr *idutil.Manager
*TabManager
StealthScript string
Actions map[string]ActionFunc
@@ -42,14 +44,16 @@ type Bridge struct {
}
func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridge {
+ idMgr := idutil.NewManager()
b := &Bridge{
AllocCtx: allocCtx,
BrowserCtx: browserCtx,
Config: cfg,
+ IdMgr: idMgr,
}
// Only initialize TabManager if browserCtx is provided (not lazy-init case)
if cfg != nil && browserCtx != nil {
- b.TabManager = NewTabManager(browserCtx, cfg, b.tabSetup)
+ b.TabManager = NewTabManager(browserCtx, cfg, idMgr, b.tabSetup)
}
b.Locks = NewLockManager()
b.InitActionRegistry()
@@ -122,7 +126,10 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {
// Initialize TabManager now that browser is ready
if b.Config != nil && b.TabManager == nil {
- b.TabManager = NewTabManager(browserCtx, b.Config, b.tabSetup)
+ if b.IdMgr == nil {
+ b.IdMgr = idutil.NewManager()
+ }
+ b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)
}
// Ensure action registry is populated (idempotent)
@@ -145,7 +152,10 @@ func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel contex
// Now initialize TabManager with the browser context
if b.Config != nil && b.TabManager == nil {
- b.TabManager = NewTabManager(browserCtx, b.Config, b.tabSetup)
+ if b.IdMgr == nil {
+ b.IdMgr = idutil.NewManager()
+ }
+ b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)
}
}
diff --git a/internal/bridge/bridge_test.go b/internal/bridge/bridge_test.go
index f153367e..2961198d 100644
--- a/internal/bridge/bridge_test.go
+++ b/internal/bridge/bridge_test.go
@@ -78,7 +78,7 @@ func TestTabManagerRemoteAllocatorInitialization(t *testing.T) {
// Use context.TODO() instead of nil to avoid lint warnings
ctx := context.TODO()
- tm := NewTabManager(ctx, cfg, nil)
+ tm := NewTabManager(ctx, cfg, nil, nil)
if tm == nil {
t.Error("TabManager should be created")
}
@@ -89,3 +89,80 @@ func TestTabManagerRemoteAllocatorInitialization(t *testing.T) {
t.Error("CreateTab should fail when browserCtx is invalid")
}
}
+
+func TestTabContext_RejectsUnknownTabID(t *testing.T) {
+ // TabContext should reject tab IDs that aren't tracked
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+
+ // Try to get context for a non-existent tab
+ _, _, err := tm.TabContext("tab_nonexistent")
+ if err == nil {
+ t.Error("TabContext should reject unknown tab IDs")
+ }
+ if err.Error() != "tab tab_nonexistent not found" {
+ t.Errorf("unexpected error message: %s", err.Error())
+ }
+}
+
+func TestTabContext_RejectsRawCDPID(t *testing.T) {
+ // TabContext should reject raw CDP target IDs (32-char hex)
+ // These should never be accepted - only hash-format IDs work
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+
+ // Simulate a raw CDP target ID format
+ rawCDPID := "A25658CE1BA82659EBE9C93C46CEE63A"
+
+ _, _, err := tm.TabContext(rawCDPID)
+ if err == nil {
+ t.Error("TabContext should reject raw CDP target IDs")
+ }
+}
+
+func TestCreateTab_ReturnsHashFormat(t *testing.T) {
+ // Verify CreateTab returns hash-format IDs (tab_XXXXXXXX)
+ // Note: This test can't actually create tabs without Chrome,
+ // but we can test the ID format logic directly
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+
+ // CreateTab will fail (no browser), but we can test the idMgr
+ if tm.idMgr == nil {
+ t.Error("TabManager should have idMgr initialized")
+ }
+
+ // Test the ID generation format
+ hashID := tm.idMgr.TabIDFromCDPTarget("A25658CE1BA82659EBE9C93C46CEE63A")
+ if len(hashID) < 4 || hashID[:4] != "tab_" {
+ t.Errorf("expected hash ID to start with 'tab_', got %s", hashID)
+ }
+ if len(hashID) != 12 { // tab_ + 8 hex chars
+ t.Errorf("expected hash ID length 12, got %d (%s)", len(hashID), hashID)
+ }
+}
+
+func TestTabContext_AcceptsRegisteredHashID(t *testing.T) {
+ // TabContext should accept hash IDs that are properly registered
+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{}, nil, nil)
+
+ // Manually register a tab entry (simulating what CreateTab does internally)
+ hashID := "tab_abc12345"
+ rawCDPID := "RAWCDPID123456789012345678901234"
+ ctx := context.Background()
+
+ tm.tabs[hashID] = &TabEntry{
+ Ctx: ctx,
+ CDPID: rawCDPID,
+ }
+
+ // TabContext should find and return it
+ returnedCtx, resolvedID, err := tm.TabContext(hashID)
+ if err != nil {
+ t.Errorf("TabContext should accept registered hash ID: %v", err)
+ }
+ if returnedCtx != ctx {
+ t.Error("TabContext should return the registered context")
+ }
+ // resolvedID should be the raw CDP ID for internal consistency
+ if resolvedID != rawCDPID {
+ t.Errorf("resolvedID should be raw CDP ID, got %s", resolvedID)
+ }
+}
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index a5ef71da..50afaf1a 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -11,6 +11,7 @@ import (
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/idutil"
)
type TabSetupFunc func(ctx context.Context)
@@ -18,6 +19,7 @@ type TabSetupFunc func(ctx context.Context)
type TabManager struct {
browserCtx context.Context
config *config.RuntimeConfig
+ idMgr *idutil.Manager
tabs map[string]*TabEntry
accessed map[string]bool
snapshots map[string]*RefCache
@@ -25,10 +27,14 @@ type TabManager struct {
mu sync.RWMutex
}
-func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, onTabSetup TabSetupFunc) *TabManager {
+func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr *idutil.Manager, onTabSetup TabSetupFunc) *TabManager {
+ if idMgr == nil {
+ idMgr = idutil.NewManager()
+ }
return &TabManager{
browserCtx: browserCtx,
config: cfg,
+ idMgr: idMgr,
tabs: make(map[string]*TabEntry),
accessed: make(map[string]bool),
snapshots: make(map[string]*RefCache),
@@ -55,6 +61,7 @@ func (tm *TabManager) AccessedTabIDs() map[string]bool {
func (tm *TabManager) TabContext(tabID string) (context.Context, string, error) {
if tabID == "" {
+ // Auto-select first tab when no ID provided
targets, err := tm.ListTargets()
if err != nil {
return nil, "", fmt.Errorf("list targets: %w", err)
@@ -62,50 +69,32 @@ func (tm *TabManager) TabContext(tabID string) (context.Context, string, error)
if len(targets) == 0 {
return nil, "", fmt.Errorf("no tabs open")
}
- tabID = string(targets[0].TargetID)
+ // Convert raw CDP ID to hash and look it up
+ rawID := string(targets[0].TargetID)
+ tabID = tm.idMgr.TabIDFromCDPTarget(rawID)
}
tm.mu.RLock()
- if entry, ok := tm.tabs[tabID]; ok && entry.Ctx != nil {
- tm.mu.RUnlock()
- tm.markAccessed(tabID)
- // When this entry is a hash alias, return the canonical raw CDP ID so that
- // operations like ref-cache lookups are consistent regardless of which ID
- // form was used to call TabContext.
- resolvedID := tabID
- if entry.CDPID != "" {
- resolvedID = entry.CDPID
- }
- return entry.Ctx, resolvedID, nil
- }
+ entry, ok := tm.tabs[tabID]
tm.mu.RUnlock()
- tm.mu.Lock()
- defer tm.mu.Unlock()
-
- if entry, ok := tm.tabs[tabID]; ok && entry.Ctx != nil {
- tm.accessed[tabID] = true
- return entry.Ctx, tabID, nil
+ if !ok {
+ return nil, "", fmt.Errorf("tab %s not found", tabID)
}
- if tm.browserCtx == nil {
- return nil, "", fmt.Errorf("no browser connection")
+ if entry.Ctx == nil {
+ return nil, "", fmt.Errorf("tab %s has no active context", tabID)
}
- ctx, cancel := chromedp.NewContext(tm.browserCtx,
- chromedp.WithTargetID(target.ID(tabID)),
- )
- if err := chromedp.Run(ctx); err != nil {
- cancel()
- return nil, "", fmt.Errorf("tab %s not found: %w", tabID, err)
- }
+ tm.markAccessed(tabID)
- if tm.onTabSetup != nil {
- tm.onTabSetup(ctx)
+ // Return the canonical raw CDP ID so that operations like ref-cache
+ // lookups are consistent regardless of which ID form was used.
+ resolvedID := tabID
+ if entry.CDPID != "" {
+ resolvedID = entry.CDPID
}
-
- tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel}
- return ctx, tabID, nil
+ return entry.Ctx, resolvedID, nil
}
func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
@@ -173,13 +162,17 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
_ = SetResourceBlocking(ctx, blockPatterns)
}
- newTargetID := string(targetID)
+ // Compute hash-based tab ID and store only that entry.
+ // Raw CDP ID is kept internal in the CDPID field.
+ rawCDPID := string(targetID)
+ hashTabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)
+
tm.mu.Lock()
- tm.tabs[newTargetID] = &TabEntry{Ctx: ctx, Cancel: cancel}
- tm.accessed[newTargetID] = true
+ tm.tabs[hashTabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID}
+ tm.accessed[hashTabID] = true
tm.mu.Unlock()
- return newTargetID, ctx, cancel, nil
+ return hashTabID, ctx, cancel, nil
}
func (tm *TabManager) CloseTab(tabID string) error {
diff --git a/internal/handlers/handler_test.go b/internal/handlers/handler_test.go
index 7b36e69a..6510fb64 100644
--- a/internal/handlers/handler_test.go
+++ b/internal/handlers/handler_test.go
@@ -41,12 +41,9 @@ func (m *mockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.
return map[string]any{"success": true}, nil
}
-func (m *mockBridge) RegisterHashTab(hashID, rawCDPID string, ctx context.Context, cancel context.CancelFunc) {
-}
-
func (m *mockBridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
ctx, cancel := chromedp.NewContext(context.Background())
- return "new-tab", ctx, cancel, nil
+ return "tab_abc12345", ctx, cancel, nil
}
func (m *mockBridge) CloseTab(tabID string) error {
diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.go
index b40cbd08..8992f395 100644
--- a/internal/handlers/health_tabs_test.go
+++ b/internal/handlers/health_tabs_test.go
@@ -306,9 +306,6 @@ func (m *MockBridge) SetRefCache(tabID string, cache *bridge.RefCache) {
func (m *MockBridge) DeleteRefCache(tabID string) {
}
-func (m *MockBridge) RegisterHashTab(hashID, rawCDPID string, ctx context.Context, cancel context.CancelFunc) {
-}
-
func (m *MockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {
return nil, nil
}
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
index 820ad37f..74d80e9e 100644
--- a/internal/handlers/navigation.go
+++ b/internal/handlers/navigation.go
@@ -134,7 +134,8 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
return
}
}
- newTargetID, newCtx, newCtxCancel, err := h.Bridge.CreateTab(req.URL)
+ // CreateTab returns hash-based tab ID directly (e.g., "tab_XXXXXXXX")
+ hashTabID, newCtx, _, err := h.Bridge.CreateTab(req.URL)
if err != nil {
web.Error(w, 500, fmt.Errorf("new tab: %w", err))
return
@@ -162,18 +163,6 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
_ = chromedp.Run(tCtx, chromedp.Location(&url))
title := bridge.WaitForTitle(tCtx, titleWait)
- targetID := ""
- if c := chromedp.FromContext(newCtx); c != nil && c.Target != nil {
- targetID = string(c.Target.TargetID)
- } else {
- targetID = newTargetID
- }
-
- // Convert CDP target ID to hash-based tab ID and register the alias so
- // subsequent operations (action, snapshot, close) can resolve it.
- hashTabID := h.IdMgr.TabIDFromCDPTarget(targetID)
- h.Bridge.RegisterHashTab(hashTabID, targetID, newCtx, newCtxCancel)
-
web.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": url, "title": title})
return
}
@@ -355,7 +344,8 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
switch req.Action {
case tabActionNew:
- newTargetID, ctx, cancel, err := h.Bridge.CreateTab(req.URL)
+ // CreateTab returns hash-based tab ID directly (e.g., "tab_XXXXXXXX")
+ hashTabID, ctx, _, err := h.Bridge.CreateTab(req.URL)
if err != nil {
web.Error(w, 500, err)
return
@@ -365,7 +355,7 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
tCtx, tCancel := context.WithTimeout(ctx, h.Config.NavigateTimeout)
defer tCancel()
if err := bridge.NavigatePage(tCtx, req.URL); err != nil {
- _ = h.Bridge.CloseTab(newTargetID)
+ _ = h.Bridge.CloseTab(hashTabID)
web.Error(w, 500, fmt.Errorf("navigate: %w", err))
return
}
@@ -374,10 +364,6 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
var curURL, title string
_ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))
- // Convert CDP target ID to hash-based tab ID and register the alias.
- hashTabID := h.IdMgr.TabIDFromCDPTarget(newTargetID)
- h.Bridge.RegisterHashTab(hashTabID, newTargetID, ctx, cancel)
-
web.JSON(w, 200, map[string]any{"tabId": hashTabID, "url": curURL, "title": title})
case tabActionClose:
diff --git a/tests/integration/tabs_test.go b/tests/integration/tabs_test.go
index 35c0fb53..5244aa2b 100644
--- a/tests/integration/tabs_test.go
+++ b/tests/integration/tabs_test.go
@@ -146,3 +146,59 @@ func TestTabs_MaxTabs(t *testing.T) {
})
}
}
+
+// TB7: Tab ID format validation - only hash IDs accepted
+func TestTabs_IDFormat(t *testing.T) {
+ // Create a new tab and verify it returns hash format
+ code, body := httpPost(t, "/tab", map[string]string{
+ "action": "new",
+ "url": "about:blank",
+ })
+ if code != 200 {
+ t.Fatalf("expected 200, got %d (body: %s)", code, body)
+ }
+
+ var newTab map[string]any
+ _ = json.Unmarshal(body, &newTab)
+ tabID, ok := newTab["tabId"].(string)
+ if !ok || tabID == "" {
+ t.Fatal("expected tabId in response")
+ }
+
+ // Verify hash format: tab_XXXXXXXX (12 chars total)
+ if len(tabID) != 12 || tabID[:4] != "tab_" {
+ t.Errorf("expected hash format tab_XXXXXXXX, got %s", tabID)
+ }
+
+ // Clean up
+ _, _ = httpPost(t, "/tab", map[string]string{"action": "close", "tabId": tabID})
+}
+
+// TB8: Raw CDP ID rejection - security test
+func TestTabs_RejectsRawCDPID(t *testing.T) {
+ // Raw CDP target IDs (32-char hex) should be rejected
+ rawCDPID := "A25658CE1BA82659EBE9C93C46CEE63A"
+
+ // Try to navigate using raw CDP ID - should fail with 404
+ code, _ := httpPost(t, "/tabs/"+rawCDPID+"/navigate", map[string]string{
+ "url": "https://example.com",
+ })
+ if code != 404 {
+ t.Errorf("expected 404 for raw CDP ID, got %d", code)
+ }
+
+ // Try to get snapshot using raw CDP ID - should fail with 404
+ code, _ = httpGet(t, "/tabs/"+rawCDPID+"/snapshot")
+ if code != 404 {
+ t.Errorf("expected 404 for raw CDP ID snapshot, got %d", code)
+ }
+
+ // Try action using raw CDP ID - should fail with 404
+ code, _ = httpPost(t, "/tabs/"+rawCDPID+"/action", map[string]string{
+ "kind": "click",
+ "ref": "e0",
+ })
+ if code != 404 {
+ t.Errorf("expected 404 for raw CDP ID action, got %d", code)
+ }
+}