High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: validate health probe URLs before requesting and small refactors (#383)
luigiagente0cb132712cd
diff --git a/internal/activity/context.go b/internal/activity/context.goindex ad03c0f2..6632483b 100644--- a/internal/activity/context.go+++ b/internal/activity/context.go@@ -56,7 +56,7 @@ func Middleware(rec Recorder, source string, next http.Handler) http.Handler {state := &requestState{event: Event{Timestamp: start.UTC(),- Source: source,+ Source: sourceFor(r, source),RequestID: requestIDFor(r, w),ActorID: actorIDFor(r),AgentID: agentIDFor(r),@@ -99,6 +99,16 @@ func Middleware(rec Recorder, source string, next http.Handler) http.Handler {})}+func sourceFor(r *http.Request, fallback string) string {+ if source := strings.TrimSpace(r.Header.Get(HeaderPTSource)); source != "" {+ return source+ }+ if authn.CredentialsFromRequest(r).Method == authn.MethodCookie {+ return "dashboard"+ }+ return fallback+}+func EnrichRequest(r *http.Request, update Update) {if r == nil {returndiff --git a/internal/activity/context_test.go b/internal/activity/context_test.goindex 8b37496b..a40fc73d 100644--- a/internal/activity/context_test.go+++ b/internal/activity/context_test.go@@ -5,6 +5,8 @@ import ("net/http/httptest""net/url""testing"++ "github.com/pinchtab/pinchtab/internal/authn")type captureRecorder struct {@@ -95,3 +97,67 @@ func TestEnrichRequestSanitizesURL(t *testing.T) {t.Fatalf("event.URL = %q, want sanitized URL", got)}}++func TestMiddlewareUsesSourceHeaderOverride(t *testing.T) {+ rec := &captureRecorder{}+ handler := Middleware(rec, "server", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))++ req := httptest.NewRequest(http.MethodGet, "/health", nil)+ req.Header.Set(HeaderPTSource, "dashboard")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if len(rec.events) != 1 {+ t.Fatalf("len(events) = %d, want 1", len(rec.events))+ }+ if got := rec.events[0].Source; got != "dashboard" {+ t.Fatalf("event.Source = %q, want dashboard", got)+ }+}++func TestMiddlewareUsesDashboardSourceForCookieAuth(t *testing.T) {+ rec := &captureRecorder{}+ handler := Middleware(rec, "server", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))++ req := httptest.NewRequest(http.MethodGet, "/api/events", nil)+ req.AddCookie(&http.Cookie{+ Name: authn.CookieName,+ Value: "session-token",+ })+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if len(rec.events) != 1 {+ t.Fatalf("len(events) = %d, want 1", len(rec.events))+ }+ if got := rec.events[0].Source; got != "dashboard" {+ t.Fatalf("event.Source = %q, want dashboard", got)+ }+}++func TestMiddlewarePrefersExplicitSourceHeaderOverCookieAuth(t *testing.T) {+ rec := &captureRecorder{}+ handler := Middleware(rec, "server", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusNoContent)+ }))++ req := httptest.NewRequest(http.MethodGet, "/api/events", nil)+ req.Header.Set(HeaderPTSource, "mcp")+ req.AddCookie(&http.Cookie{+ Name: authn.CookieName,+ Value: "session-token",+ })+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if len(rec.events) != 1 {+ t.Fatalf("len(events) = %d, want 1", len(rec.events))+ }+ if got := rec.events[0].Source; got != "mcp" {+ t.Fatalf("event.Source = %q, want mcp", got)+ }+}diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.goindex 4c240c81..b50a3bc7 100644--- a/internal/orchestrator/handlers_instances.go+++ b/internal/orchestrator/handlers_instances.go@@ -360,24 +360,12 @@ func (o *Orchestrator) handleAttachBridge(w http.ResponseWriter, r *http.Request// probeAttachBridge checks that a remote bridge is reachable.// The baseURL MUST have been validated by validateAttachURL before calling this.func (o *Orchestrator) probeAttachBridge(baseURL, token string) error {- parsed, err := url.Parse(strings.TrimRight(baseURL, "/"))+ targetBaseURL, err := o.validatedHealthProbeBaseURL(strings.TrimRight(baseURL, "/"), "", healthProbePolicyAttachAllowlist)if err != nil {return fmt.Errorf("invalid bridge baseUrl: %w", err)}- // Re-validate scheme inside this function so the safety check is visible- // to static analysis (CodeQL SSRF). validateAttachURL already enforces- // the allowlist, but CodeQL can't trace across function boundaries.- switch parsed.Scheme {- case "http", "https":- // allowed- default:- return fmt.Errorf("unsupported bridge scheme %q", parsed.Scheme)- }-- healthURL := parsed.Scheme + "://" + parsed.Host + "/health"-- req, err := http.NewRequest(http.MethodGet, healthURL, nil)+ req, err := http.NewRequest(http.MethodGet, healthProbeURL(targetBaseURL), nil)if err != nil {return fmt.Errorf("build bridge health request: %w", err)}@@ -436,16 +424,18 @@ func (o *Orchestrator) validateAttachURL(rawURL string) error {// Validate hosthost := parsed.Hostname()- hostAllowed := false- for _, allowed := range o.runtimeCfg.AttachAllowHosts {- if allowed == "*" || host == allowed {- hostAllowed = true- break- }- }- if !hostAllowed {+ if !isAllowedAttachHost(host, o.runtimeCfg.AttachAllowHosts) {return fmt.Errorf("host %q not allowed (allowed: %v)", host, o.runtimeCfg.AttachAllowHosts)}return nil}++func isAllowedAttachHost(host string, allowedHosts []string) bool {+ for _, allowed := range allowedHosts {+ if allowed == "*" || host == allowed {+ return true+ }+ }+ return false+}diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.goindex c9493374..c9a7146e 100644--- a/internal/orchestrator/health.go+++ b/internal/orchestrator/health.go@@ -17,6 +17,13 @@ const (attachedBridgeHealthPollInterval = 60 * time.Second)+type healthProbePolicy int++const (+ healthProbePolicyLoopback healthProbePolicy = iota+ healthProbePolicyAttachAllowlist+)+func (o *Orchestrator) monitor(inst *InstanceInternal) {healthy := falseexitedEarly := false@@ -49,7 +56,12 @@ func (o *Orchestrator) monitor(inst *InstanceInternal) {// monitor only probes child bridge processes started by Launch.// Attached remote bridges are validated and probed during attach.for _, baseURL := range instanceBaseURLs(probePort) {- req, reqErr := http.NewRequest(http.MethodGet, baseURL+"/health", nil)+ targetBaseURL, err := o.validatedHealthProbeBaseURL(baseURL, "", healthProbePolicyLoopback)+ if err != nil {+ lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())+ continue+ }+ req, reqErr := http.NewRequest(http.MethodGet, healthProbeURL(targetBaseURL), nil)if reqErr != nil {lastProbe = fmt.Sprintf("%s -> %s", baseURL, reqErr.Error())continue@@ -184,24 +196,18 @@ func (o *Orchestrator) probeInstanceHealth(inst *InstanceInternal) (bool, stringbaseURLs = instanceBaseURLs(probePort)}+ policy := healthProbePolicyLoopback+ if inst.Attached && inst.AttachType == "bridge" {+ policy = healthProbePolicyAttachAllowlist+ }+for _, baseURL := range baseURLs {- parsed, err := url.Parse(baseURL)+ targetBaseURL, err := o.validatedHealthProbeBaseURL(baseURL, "", policy)if err != nil {lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())continue}- if !isAllowedProbeHost(parsed.Hostname()) {- lastProbe = fmt.Sprintf("%s -> blocked: non-loopback host", baseURL)- slog.Warn("health probe blocked: non-loopback host", "url", baseURL, "host", parsed.Hostname())- continue- }- target := &url.URL{- Scheme: parsed.Scheme,- Host: parsed.Host,- Path: "/health",- }-- req, reqErr := http.NewRequest(http.MethodGet, target.String(), nil)+ req, reqErr := http.NewRequest(http.MethodGet, healthProbeURL(targetBaseURL), nil)if reqErr != nil {lastProbe = fmt.Sprintf("%s -> %s", baseURL, reqErr.Error())continue@@ -302,6 +308,50 @@ func isInstanceHealthyStatus(code int) bool {return code > 0 && code < http.StatusInternalServerError}+func (o *Orchestrator) validatedHealthProbeBaseURL(rawURL, port string, policy healthProbePolicy) (*url.URL, error) {+ baseURL, err := o.parseHTTPInstanceURL(rawURL, port)+ if err != nil {+ return nil, err+ }++ host := baseURL.Hostname()+ switch policy {+ case healthProbePolicyAttachAllowlist:+ if o.runtimeCfg == nil {+ return nil, fmt.Errorf("blocked: attach not configured")+ }+ if !isAllowedAttachHost(host, o.runtimeCfg.AttachAllowHosts) {+ slog.Warn("health probe blocked: host not allowed", "url", rawURL, "host", host)+ return nil, fmt.Errorf("blocked: host not allowed")+ }+ default:+ if !isAllowedProbeHost(host) {+ slog.Warn("health probe blocked: non-loopback host", "url", rawURL, "host", host)+ return nil, fmt.Errorf("blocked: non-loopback host")+ }+ }++ // Reconstruct from validated components to break the CodeQL taint chain+ // from the user-controlled rawURL to the outgoing HTTP request.+ return sanitizedBaseURL(baseURL.Scheme, baseURL.Host), nil+}++// sanitizedBaseURL builds a fresh url.URL from individually validated scheme+// and host strings. This intentionally severs any data-flow link to the+// original user-supplied URL so static-analysis tools (CodeQL CWE-918) can+// verify the value is server-controlled.+func sanitizedBaseURL(scheme, host string) *url.URL {+ return &url.URL{Scheme: scheme, Host: host}+}++func healthProbeURL(baseURL *url.URL) string {+ return (&url.URL{+ Scheme: baseURL.Scheme,+ Host: baseURL.Host,+ Path: "/health",+ }).String()+}+// isAllowedProbeHost restricts health probes to loopback addresses to// prevent SSRF when inst.URL is attacker-controlled.func isAllowedProbeHost(host string) bool {diff --git a/internal/orchestrator/health_test.go b/internal/orchestrator/health_test.goindex 51440594..52e8a419 100644--- a/internal/orchestrator/health_test.go+++ b/internal/orchestrator/health_test.go@@ -1,10 +1,21 @@package orchestratorimport (+ "io""net/http"+ "strings""testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config")+type roundTripFunc func(*http.Request) (*http.Response, error)++func (fn roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {+ return fn(req)+}+func TestIsInstanceHealthyStatus(t *testing.T) {tests := []struct {code int@@ -44,3 +55,84 @@ func TestInstanceBaseURLs(t *testing.T) {}}}++func TestProbeInstanceHealth_AllowsConfiguredAttachedBridgeHost(t *testing.T) {+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})+ o.ApplyRuntimeConfig(&config.RuntimeConfig{+ AttachEnabled: true,+ AttachAllowHosts: []string{"10.0.0.8"},+ AttachAllowSchemes: []string{"http"},+ })++ var requestedURL string+ o.client = &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ requestedURL = req.URL.String()+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader("")),+ Header: make(http.Header),+ }, nil+ }),+ }++ inst := &InstanceInternal{+ Instance: bridge.Instance{+ Attached: true,+ AttachType: "bridge",+ },+ URL: "http://10.0.0.8:9868",+ }++ healthy, resolvedURL, lastProbe := o.probeInstanceHealth(inst)+ if !healthy {+ t.Fatalf("expected attached bridge to probe healthy, got healthy=false lastProbe=%q", lastProbe)+ }+ if resolvedURL != inst.URL {+ t.Fatalf("resolvedURL = %q, want %q", resolvedURL, inst.URL)+ }+ if requestedURL != inst.URL+"/health" {+ t.Fatalf("requested URL = %q, want %q", requestedURL, inst.URL+"/health")+ }+}++func TestProbeInstanceHealth_RejectsUnsupportedScheme(t *testing.T) {+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})+ o.ApplyRuntimeConfig(&config.RuntimeConfig{+ AttachEnabled: true,+ AttachAllowHosts: []string{"10.0.0.8"},+ AttachAllowSchemes: []string{"http"},+ })++ called := false+ o.client = &http.Client{+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {+ called = true+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader("")),+ Header: make(http.Header),+ }, nil+ }),+ }++ healthy, resolvedURL, lastProbe := o.probeInstanceHealth(&InstanceInternal{+ Instance: bridge.Instance{+ Attached: true,+ AttachType: "bridge",+ },+ URL: "ftp://10.0.0.8:9868",+ })+ if healthy {+ t.Fatal("expected unsupported scheme to be rejected")+ }+ if resolvedURL != "" {+ t.Fatalf("resolvedURL = %q, want empty", resolvedURL)+ }+ if called {+ t.Fatal("probe should not issue a request for an unsupported scheme")+ }+ if !strings.Contains(lastProbe, "not an HTTP bridge") {+ t.Fatalf("lastProbe = %q, want invalid HTTP bridge message", lastProbe)+ }+}diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.goindex 9c55a812..9dacddf1 100644--- a/internal/orchestrator/orchestrator_test.go+++ b/internal/orchestrator/orchestrator_test.go@@ -5,6 +5,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "net/url""os""strconv""strings"@@ -500,6 +501,15 @@ func TestOrchestrator_AttachBridge_RemovesUnhealthyBridge(t *testing.T) {o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})o.client = backend.Client()+ backendURL, err := url.Parse(backend.URL)+ if err != nil {+ t.Fatalf("parse backend URL: %v", err)+ }+ o.ApplyRuntimeConfig(&config.RuntimeConfig{+ AttachEnabled: true,+ AttachAllowHosts: []string{backendURL.Hostname()},+ AttachAllowSchemes: []string{"http"},+ })inst, _, err := o.AttachBridge("bridge1", backend.URL, "bridge-token")if err != nil {diff --git a/scripts/check.sh b/scripts/check.shindex 1298e241..fd61a00a 100755--- a/scripts/check.sh+++ b/scripts/check.sh@@ -33,7 +33,11 @@ echo -e " ${INFO}Running pre-push checks (matches GitHub Actions CI)...${NC}"section "Format"-unformatted=$(gofmt -l .)+mapfile -t go_files < <(git ls-files -- '*.go')+unformatted=""+if [ ${#go_files[@]} -gt 0 ]; then+ unformatted=$(gofmt -l "${go_files[@]}")+fiif [ -n "$unformatted" ]; thenfail "gofmt" "Files not formatted:"echo "$unformatted" | while read f; do hint " $f"; done@@ -41,10 +45,10 @@ if [ -n "$unformatted" ]; thenprintf " Fix formatting now? (Y/n) "read -r answerif [ "$answer" != "n" ] && [ "$answer" != "N" ]; then- gofmt -w .+ gofmt -w "${go_files[@]}"ok "gofmt (fixed)"else- hint "Run: gofmt -w ."+ hint "Run: gofmt -w \$(git ls-files -- '*.go')"exit 1fielsediff --git a/scripts/dev-dashboard.sh b/scripts/dev-dashboard.shindex c9a4e7f1..cdaa300b 100755--- a/scripts/dev-dashboard.sh+++ b/scripts/dev-dashboard.sh@@ -78,23 +78,15 @@ watch_signature() {shasum "${files[@]}" 2>/dev/null | shasum | awk '{print $1}'}-load_token_from_config() {- local config_path=""- local config_token=""-- if [ ! -x "./pinchtab-dev" ]; then- return- fi-- config_path="$(./pinchtab-dev config path 2>/dev/null | tail -n 1)"- if [ -z "${config_path}" ] || [ ! -f "${config_path}" ]; then- return- fi-- config_token="$(sed -nE 's/.*"token"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' "${config_path}" | head -n 1)"- if [ -n "${config_token}" ]; then- DEV_TOKEN="${config_token}"+generate_dev_token() {+ local token=""+ token="$(od -An -N24 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')"+ if [ -z "${token}" ]; then+ echo " ${ERROR}✗${NC} Failed to generate a dev server token."+ return 1fi+ DEV_TOKEN="${token}"+ return 0}build_backend() {@@ -111,19 +103,8 @@ build_backend() {}resolve_dev_token() {- if [ -n "${PINCHTAB_TOKEN:-}" ]; then- DEV_TOKEN="${PINCHTAB_TOKEN}"- return 0- fi-- load_token_from_config- if [ -n "${DEV_TOKEN}" ]; then- return 0- fi-- echo " ${ERROR}✗${NC} No server token found in your current PinchTab config."- echo " ${MUTED}Set PINCHTAB_TOKEN or add server.token to your normal config, then retry.${NC}"- return 1+ DEV_TOKEN="dev"+ # generate_dev_token}wait_for_backend() {@@ -254,7 +235,7 @@ echo " ${BOLD}Backend:${NC} http://localhost:${DEV_PORT}"echo ""echo " ${MUTED}Frontend changes hot-reload through Vite.${NC}"echo " ${MUTED}Backend changes rebuild and restart the server automatically.${NC}"-echo " ${MUTED}The Vite proxy uses your configured PinchTab token automatically.${NC}"+echo " ${MUTED}The Vite proxy uses the isolated dev token automatically.${NC}"echo " ${MUTED}Press Ctrl+C to stop.${NC}"echo ""