Skip to content

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

fix: scheduler routes hop auth through the orchestrator so its actions record as 'scheduler' through real ingress (PIN-384)

Luigi Agosti4a7bd6039dd6
diff --git a/internal/api/types/headers_census_test.go b/internal/api/types/headers_census_test.go
index 1a846b5e..b85b42d0 100644
--- a/internal/api/types/headers_census_test.go
+++ b/internal/api/types/headers_census_test.go
@@ -191,14 +191,12 @@ var publicClientPackages = map[string]string{
var publicClientExemptHeaders = map[string]map[string]string{
"internal/cli/apiclient": {"x-pinchtab-source": "harmless: bearer credential fallback records the same 'client' label"},
"cmd/pinchtab": {"x-pinchtab-source": "harmless: same as the CLI apiclient — bearer fallback yields 'client'"},
- // PENDING (PIN-384, blocked): the scheduler's Source/Tab-Id are stripped today, so it
- // records as 'client'. The fix is to send the trusted internal token via the
- // orchestrator's hop-auth owner (applyInstanceAuth) — which lives outside this card's
- // footprint (orchestrator/scheduler interface/server wiring). Remove these two entries
- // when that lands and the executor routes through the authorizer.
+ // The scheduler's action executor routes hop auth through the orchestrator
+ // (AuthorizeTabRequest), which marks internal/scheduler authorized below, so its
+ // Source/Tab-Id survive ingress and need no exemption. The webhook headers stay exempt:
+ // they go to an EXTERNAL receiver, not a PinchTab listener, and would be flagged if the
+ // executor ever stopped routing through the authorizer.
"internal/scheduler": {
- "x-pinchtab-source": "PENDING PIN-384: needs the orchestrator internal-token hop-auth; stripped until then",
- "x-pinchtab-tab-id": "PENDING PIN-384: needs the orchestrator internal-token hop-auth; stripped until then",
"x-pinchtab-event": "webhook.go: outbound event-webhook to an EXTERNAL receiver that reads these; not a PinchTab listener behind the strip layer",
"x-pinchtab-task-id": "webhook.go: outbound event-webhook to an EXTERNAL receiver that reads these; not a PinchTab listener behind the strip layer",
},
@@ -244,7 +242,17 @@ func pinchtabRequestHeaderSets(t *testing.T, files []srccensus.SourceFile) (sets
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok || sel.Sel.Name != "Set" {
+ if !ok {
+ return true
+ }
+ // A package that routes a request through the orchestrator's hop-auth owner is
+ // authorized the same as one that sets the internal token itself: the token is
+ // applied there, not here.
+ if sel.Sel.Name == "AuthorizeTabRequest" {
+ tokenPkgs[pkg] = true
+ return true
+ }
+ if sel.Sel.Name != "Set" {
return true
}
inner, ok := sel.X.(*ast.SelectorExpr)
@@ -319,6 +327,19 @@ func TestStrippedHeaderCensusAllowsATrustedHopThatSendsTheToken(t *testing.T) {
}
}
+// A package that routes its request through the orchestrator's hop-auth owner
+// (AuthorizeTabRequest) is authorized the same as one that sends the token directly, so its
+// X-PinchTab-* sets are not flagged.
+func TestStrippedHeaderCensusAllowsAPackageThatRoutesThroughTheAuthorizer(t *testing.T) {
+ planted := []srccensus.SourceFile{
+ {Name: "internal/scheduler/x.go", Text: "package scheduler\nimport \"net/http\"\nfunc f(a interface{ AuthorizeTabRequest(string, *http.Request) error }, req *http.Request) {\n\t_ = a.AuthorizeTabRequest(\"t\", req)\n\treq.Header.Set(\"X-PinchTab-Source\", \"scheduler\")\n}\n"},
+ }
+ sets, tokenPkgs := pinchtabRequestHeaderSets(t, planted)
+ if len(strippedHeaderViolations(sets, tokenPkgs)) != 0 {
+ t.Fatal("a package that routes through AuthorizeTabRequest was flagged; its headers survive ingress via hop auth")
+ }
+}
+
// A response-side write (w.Header().Set) is not a request header the strip layer can drop.
func TestStrippedHeaderCensusIgnoresResponseWrites(t *testing.T) {
planted := []srccensus.SourceFile{
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index f88d947d..aa879670 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -344,6 +344,36 @@ func (o *Orchestrator) hopIsTrusted(inst *InstanceInternal) bool {
return inst.authToken == "" && o.internalToken != ""
}
+// ResolveTabInstance returns the localhost port of the instance that owns tabID, so the
+// scheduler can use the orchestrator as its InstanceResolver and get port resolution and hop
+// auth from one owner.
+func (o *Orchestrator) ResolveTabInstance(tabID string) (string, error) {
+ inst, err := o.instanceMgr.FindInstanceByTabID(tabID)
+ if err != nil {
+ return "", fmt.Errorf("tab %q not found: %w", tabID, err)
+ }
+ return inst.Port, nil
+}
+
+// AuthorizeTabRequest applies the same per-instance hop auth the proxy uses (bearer token,
+// plus the internal token on trusted child hops) to a request the scheduler sends directly to
+// the instance that owns tabID. It is the one owner of that decision; callers must not
+// re-derive it or read the token from the environment.
+func (o *Orchestrator) AuthorizeTabRequest(tabID string, req *http.Request) error {
+ inst, err := o.instanceMgr.FindInstanceByTabID(tabID)
+ if err != nil {
+ return fmt.Errorf("tab %q not found: %w", tabID, err)
+ }
+ o.mu.RLock()
+ internal := o.instances[inst.ID]
+ o.mu.RUnlock()
+ if internal == nil {
+ return fmt.Errorf("instance %q for tab %q is no longer tracked", inst.ID, tabID)
+ }
+ o.applyInstanceAuth(req, internal)
+ return nil
+}
+
func classifyLaunchError(err error) int {
msg := err.Error()
if strings.Contains(msg, "cannot contain") || strings.Contains(msg, "cannot be empty") {
diff --git a/internal/orchestrator/scheduler_hop_auth_test.go b/internal/orchestrator/scheduler_hop_auth_test.go
new file mode 100644
index 00000000..739f2563
--- /dev/null
+++ b/internal/orchestrator/scheduler_hop_auth_test.go
@@ -0,0 +1,97 @@
+package orchestrator
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "sync"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/handlers"
+ "github.com/pinchtab/pinchtab/internal/instance"
+ "github.com/pinchtab/pinchtab/internal/scheduler"
+)
+
+type recordingRecorder struct {
+ mu sync.Mutex
+ events []activity.Event
+}
+
+func (r *recordingRecorder) Enabled() bool { return true }
+func (r *recordingRecorder) Record(e activity.Event) error {
+ r.mu.Lock()
+ r.events = append(r.events, e)
+ r.mu.Unlock()
+ return nil
+}
+func (r *recordingRecorder) Query(activity.Filter) ([]activity.Event, error) { return nil, nil }
+func (r *recordingRecorder) last() (activity.Event, bool) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if len(r.events) == 0 {
+ return activity.Event{}, false
+ }
+ return r.events[len(r.events)-1], true
+}
+
+// A scheduler-executed action must record as 'scheduler', not 'client': the executor routes
+// hop auth through the orchestrator (AuthorizeTabRequest → applyInstanceAuth), which sends the
+// internal token on a trusted child hop, so the X-PinchTab-Source/Tab-Id survive the instance's
+// real TrustedInternalProxyStripMiddleware. Built the way server.go builds it — an
+// orchestrator-generated token, no PINCHTAB_INTERNAL_TOKEN in the environment. Removing the
+// authorizer call (the executor's e.resolver.(RequestAuthorizer) branch) strips the headers and
+// records 'client', which is the pre-fix behavior this proves is gone.
+func TestSchedulerActionRecordsAsSchedulerThroughRealIngress(t *testing.T) {
+ rec := &recordingRecorder{}
+ var gotSource, gotTabID string
+ final := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotSource = r.Header.Get(activity.HeaderPTSource)
+ gotTabID = r.Header.Get(activity.HeaderPTTabID)
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"ok":true}`))
+ })
+
+ o := &Orchestrator{
+ internalToken: "orch-generated-token",
+ instances: map[string]*InstanceInternal{},
+ instanceMgr: instance.NewManager(nil, nil),
+ }
+ srv := httptest.NewServer(
+ handlers.TrustedInternalProxyStripMiddleware(o.internalToken)(
+ activity.Middleware(rec, "fallback", final)))
+ defer srv.Close()
+
+ parsed, err := url.Parse(srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst := &bridge.Instance{ID: "inst-1", Port: parsed.Port(), Status: "running"}
+ o.instanceMgr.Repo.Add(inst)
+ o.instanceMgr.Locator.Register("tab-42", "inst-1")
+ o.instances["inst-1"] = &InstanceInternal{Instance: *inst}
+
+ exec := scheduler.NewActionExecutor(o)
+ if _, err := exec.Execute(context.Background(), &scheduler.Task{Action: "click", Ref: "e5", TabID: "tab-42"}); err != nil {
+ t.Fatalf("Execute: %v", err)
+ }
+
+ if gotSource != "scheduler" {
+ t.Errorf("inbound X-PinchTab-Source = %q, want scheduler (hop auth must let it survive real ingress)", gotSource)
+ }
+ if gotTabID != "tab-42" {
+ t.Errorf("inbound X-PinchTab-Tab-Id = %q, want tab-42 (the tab id header must survive ingress)", gotTabID)
+ }
+ evt, ok := rec.last()
+ if !ok {
+ t.Fatal("no activity event recorded")
+ }
+ if evt.Source != "scheduler" {
+ t.Errorf("recorded activity source = %q, want scheduler", evt.Source)
+ }
+ if evt.TabID != "tab-42" {
+ t.Errorf("recorded activity tab id = %q, want tab-42", evt.TabID)
+ }
+}
diff --git a/internal/scheduler/executor.go b/internal/scheduler/executor.go
index 625954d9..c89003d5 100644
--- a/internal/scheduler/executor.go
+++ b/internal/scheduler/executor.go
@@ -89,6 +89,14 @@ func (e *actionEndpointExecutor) Execute(ctx context.Context, t *Task) (any, err
if t.AgentID != "" {
req.Header.Set(activity.HeaderAgentID, t.AgentID)
}
+ // Route hop auth through the single owner (the orchestrator): only a trusted hop keeps
+ // the X-PinchTab-* identity headers above through ingress, so without this the source and
+ // tab id are stripped and the action records as "client".
+ if authorizer, ok := e.resolver.(RequestAuthorizer); ok {
+ if err := authorizer.AuthorizeTabRequest(t.TabID, req); err != nil {
+ return nil, fmt.Errorf("authorize scheduler request for tab %q: %w", t.TabID, err)
+ }
+ }
resp, err := e.client.Do(req)
if err != nil {
diff --git a/internal/scheduler/resolver.go b/internal/scheduler/resolver.go
deleted file mode 100644
index d5d02fd8..00000000
--- a/internal/scheduler/resolver.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package scheduler
-
-import (
- "fmt"
-
- "github.com/pinchtab/pinchtab/internal/instance"
-)
-
-// ManagerResolver adapts instance.Manager to the InstanceResolver interface.
-type ManagerResolver struct {
- Mgr *instance.Manager
-}
-
-func (r *ManagerResolver) ResolveTabInstance(tabID string) (string, error) {
- inst, err := r.Mgr.FindInstanceByTabID(tabID)
- if err != nil {
- return "", fmt.Errorf("tab %q not found: %w", tabID, err)
- }
- return inst.Port, nil
-}
diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.go
index 1ccb54f9..b07e6d02 100644
--- a/internal/scheduler/scheduler.go
+++ b/internal/scheduler/scheduler.go
@@ -16,6 +16,22 @@ type InstanceResolver interface {
ResolveTabInstance(tabID string) (port string, err error)
}
+// RequestAuthorizer applies per-instance hop auth (bearer token, plus the internal token on
+// trusted child hops) to a request bound for the instance that owns tabID, so the instance
+// honors the X-PinchTab-* identity headers instead of stripping them at ingress. The
+// orchestrator implements it; the scheduler must not read the token itself. A resolver that
+// does not implement it leaves the request unauthorized and the action records as "client".
+type RequestAuthorizer interface {
+ AuthorizeTabRequest(tabID string, req *http.Request) error
+}
+
+// NewActionExecutor builds the executor that dispatches a task to an instance's action
+// endpoint, using resolver for port resolution and, when it also implements RequestAuthorizer,
+// for hop auth. Exposed so a test can drive a scheduler-executed action with a real resolver.
+func NewActionExecutor(resolver InstanceResolver) TaskExecutor {
+ return &actionEndpointExecutor{resolver: resolver, client: &http.Client{Timeout: 60 * time.Second}}
+}
+
// Config holds scheduler tuning knobs.
type Config struct {
Enabled bool `json:"enabled"`
diff --git a/internal/server/server.go b/internal/server/server.go
index f35ceabf..9bbd457c 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -275,8 +275,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
if cfg.Scheduler.Enabled {
schedCfg := scheduler.ConfigFromRuntime(cfg.Scheduler)
- resolver := &scheduler.ManagerResolver{Mgr: orch.InstanceManager()}
- sched = scheduler.New(schedCfg, resolver)
+ sched = scheduler.New(schedCfg, orch)
sched.RegisterHandlers(mux)
slog.Info("scheduler enabled (on-demand)", "strategy", schedCfg.Strategy, "workers", schedCfg.WorkerCount)
}