Skip to content

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

fix(instance): present the instance credential when discovering its tabs

Luigi Agosti66c3b2dc606d
diff --git a/internal/instance/bridge_client.go b/internal/instance/bridge_client.go
index 8f797269..965db85e 100644
--- a/internal/instance/bridge_client.go
+++ b/internal/instance/bridge_client.go
@@ -16,18 +16,47 @@ import (
// Each method targets a specific bridge endpoint.
type BridgeClient struct {
client *http.Client
+
+ // authorize stamps the credential a bridge instance requires. A spawned
+ // instance runs the same auth middleware as its parent, so an unauthenticated
+ // call to it is answered 401 — and the one caller of FetchTabs swallows that
+ // at debug level, so the tab→instance discovery it feeds simply found nothing
+ // and said so nowhere. Nil means "no credential", which is what a test stub
+ // and an unauthenticated bridge want.
+ authorize func(*http.Request)
}
-// NewBridgeClient creates a BridgeClient.
+// NewBridgeClient creates a BridgeClient that sends no credential.
func NewBridgeClient() *BridgeClient {
+ return NewBridgeClientWithAuth(nil)
+}
+
+// NewBridgeClientWithAuth creates a BridgeClient that runs authorize over every
+// request it builds. The orchestrator supplies one that resolves the target
+// instance and applies that instance's own token, since an attached external
+// bridge does not share the server's.
+func NewBridgeClientWithAuth(authorize func(*http.Request)) *BridgeClient {
return &BridgeClient{
- client: &http.Client{Timeout: httpx.MaxNavigationHTTPDuration},
+ client: &http.Client{Timeout: httpx.MaxNavigationHTTPDuration},
+ authorize: authorize,
+ }
+}
+
+// authorized applies the configured credential to a request the client built.
+func (bc *BridgeClient) authorized(req *http.Request) *http.Request {
+ if bc.authorize != nil {
+ bc.authorize(req)
}
+ return req
}
// FetchTabs implements TabFetcher by querying a bridge's /tabs endpoint.
func (bc *BridgeClient) FetchTabs(instanceURL string) ([]bridge.InstanceTab, error) {
- resp, err := bc.client.Get(instanceURL + "/tabs")
+ req, err := http.NewRequest(http.MethodGet, instanceURL+"/tabs", nil)
+ if err != nil {
+ return nil, fmt.Errorf("fetch tabs request: %w", err)
+ }
+ resp, err := bc.client.Do(bc.authorized(req))
if err != nil {
return nil, fmt.Errorf("fetch tabs: %w", err)
}
@@ -57,7 +86,7 @@ func (bc *BridgeClient) CreateTab(ctx context.Context, port, url string) (string
}
req.Header.Set("Content-Type", "application/json")
- resp, err := bc.client.Do(req)
+ resp, err := bc.client.Do(bc.authorized(req))
if err != nil {
return "", fmt.Errorf("create tab: %w", err)
}
@@ -92,7 +121,7 @@ func (bc *BridgeClient) NavigateTab(ctx context.Context, port, tabID, url string
}
req.Header.Set("Content-Type", "application/json")
- resp, err := bc.client.Do(req)
+ resp, err := bc.client.Do(bc.authorized(req))
if err != nil {
return fmt.Errorf("navigate: %w", err)
}
@@ -114,7 +143,7 @@ func (bc *BridgeClient) CloseTab(ctx context.Context, port, tabID string) error
}
req.Header.Set("Content-Type", "application/json")
- resp, err := bc.client.Do(req)
+ resp, err := bc.client.Do(bc.authorized(req))
if err != nil {
return fmt.Errorf("close tab: %w", err)
}
@@ -134,7 +163,7 @@ func (bc *BridgeClient) SnapshotTab(ctx context.Context, port, tabID string) {
if err != nil {
return
}
- resp, err := bc.client.Do(req)
+ resp, err := bc.client.Do(bc.authorized(req))
if err != nil {
return
}
diff --git a/internal/instance/bridge_client_auth_test.go b/internal/instance/bridge_client_auth_test.go
new file mode 100644
index 00000000..227b58c3
--- /dev/null
+++ b/internal/instance/bridge_client_auth_test.go
@@ -0,0 +1,121 @@
+package instance
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+)
+
+// recordingBridge answers /tabs only when a credential is presented, which is
+// what a spawned instance does: it runs the same auth middleware as the process
+// that launched it.
+func recordingBridge(t *testing.T, wantToken string) (*httptest.Server, *string) {
+ t.Helper()
+ var seen string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ seen = r.Header.Get("Authorization")
+ if wantToken != "" && seen != "Bearer "+wantToken {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"tabs":[{"id":"tab-1"}]}`))
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &seen
+}
+
+// FetchTabs is the only production entry point into this client, and it feeds the
+// locator's tab→instance discovery. It sent no credential at all, so against a
+// token-protected instance it was answered 401 — and both of its callers swallow
+// that at debug level, so the discovery found nothing and said so nowhere.
+func TestFetchTabsPresentsTheInstanceCredential(t *testing.T) {
+ srv, seen := recordingBridge(t, "instance-token")
+
+ client := NewBridgeClientWithAuth(func(req *http.Request) {
+ req.Header.Set("Authorization", "Bearer instance-token")
+ })
+
+ tabs, err := client.FetchTabs(srv.URL)
+ if err != nil {
+ t.Fatalf("FetchTabs against a token-protected instance: %v", err)
+ }
+ if len(tabs) != 1 || tabs[0].ID != "tab-1" {
+ t.Errorf("tabs = %+v, want the one the instance reported", tabs)
+ }
+ if *seen != "Bearer instance-token" {
+ t.Errorf("instance saw Authorization %q, want the credential the authorizer set", *seen)
+ }
+}
+
+// The authorizer is optional: a bridge that wants no credential must still be
+// reachable, which is what every stub in this package relies on.
+func TestFetchTabsWithoutAnAuthorizerStillWorks(t *testing.T) {
+ srv, seen := recordingBridge(t, "")
+
+ if _, err := NewBridgeClient().FetchTabs(srv.URL); err != nil {
+ t.Fatalf("FetchTabs against an open instance: %v", err)
+ }
+ if *seen != "" {
+ t.Errorf("an unauthenticated client sent Authorization %q, want none", *seen)
+ }
+}
+
+// Every request this client BUILDS must carry the credential, not just the one
+// call that happened to be reported. A unit test cannot say that about a method
+// nobody calls yet, so the rule is pinned over the source: each bc.client.Do goes
+// through bc.authorized.
+//
+// The two proxy methods are excluded with their reason rather than silently: they
+// forward a caller's request instead of building one, and each already has its own
+// header rule — ProxyToTab copies the caller's Authorization, ProxyWithTabID
+// deliberately forwards the request id and nothing else.
+func TestEveryRequestThisClientBuildsIsAuthorized(t *testing.T) {
+ exempt := map[string]string{
+ "proxyReq": "forwards a caller's request, which carries its own header rule",
+ }
+
+ source, err := os.ReadFile("bridge_client.go")
+ if err != nil {
+ t.Fatalf("read the source this rule is about: %v", err)
+ }
+
+ dispatches, authorized := 0, 0
+ for _, line := range strings.Split(string(source), "\n") {
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, "//") || !strings.Contains(trimmed, "bc.client.Do(") {
+ continue
+ }
+ dispatches++
+ switch {
+ case strings.Contains(trimmed, "bc.authorized("):
+ authorized++
+ case exemptedDispatch(trimmed, exempt):
+ default:
+ t.Errorf("%s dispatches without bc.authorized(); a request this client builds must carry the instance credential", trimmed)
+ }
+ }
+
+ if dispatches < len(exempt)+1 {
+ t.Fatalf("found %d dispatch site(s) against %d exemption(s); the scan matched almost nothing and would pass vacuously", dispatches, len(exempt))
+ }
+ if authorized == 0 {
+ t.Error("no dispatch site is authorized, so this rule is guarding nothing")
+ }
+ for name, reason := range exempt {
+ if !strings.Contains(string(source), "bc.client.Do("+name+")") {
+ t.Errorf("%s is exempt (%s) but no longer dispatches, so the exemption is stale", name, reason)
+ }
+ }
+}
+
+func exemptedDispatch(line string, exempt map[string]string) bool {
+ for name := range exempt {
+ if strings.Contains(line, "bc.client.Do("+name+")") {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index cabe6aaf..d68af554 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -193,13 +193,29 @@ func (o *Orchestrator) registerInstanceCleanupHook() {
}
func (o *Orchestrator) initInstanceManager() {
- bridgeClient := instance.NewBridgeClient()
+ bridgeClient := instance.NewBridgeClientWithAuth(o.authorizeInstanceRequest)
o.instanceMgr = instance.NewManager(
&orchestratorLauncher{orch: o},
bridgeClient,
)
}
+// authorizeInstanceRequest stamps the target instance's own credential on a
+// request the instance manager built for it. A spawned instance runs the same
+// auth middleware as this process, so a bare call to its /tabs is answered 401 —
+// which the locator's discovery swallowed at debug level, leaving the tab→instance
+// cache to be filled only by lookups that had already succeeded some other way.
+//
+// Resolved per request rather than closed over one token because an attached
+// external bridge authenticates with its own, which applyInstanceAuth knows and a
+// captured server token would not.
+func (o *Orchestrator) authorizeInstanceRequest(req *http.Request) {
+ if o == nil || req == nil {
+ return
+ }
+ o.applyInstanceAuth(req, o.proxyTargetInstance(req.URL))
+}
+
func (o *Orchestrator) RunMaintenance(ctx context.Context) {
if o == nil {
return