High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: the front door records that a proxied request failed and drops why — the instance's reason now crosses the hop in headers the public boundary strips (PIN-243)
Luigi Agostida89a66523e3
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex ab079074..7b60da5a 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -50,7 +50,7 @@ func requestLogLevel(status int) slog.Level {func LoggingMiddleware(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {start := time.Now()- sw := &httpx.StatusWriter{ResponseWriter: w, Code: 200}+ sw := &httpx.StatusWriter{ResponseWriter: w, Code: 200, StripFailureHeaders: !IsTrustedInternalProxy(r)}next.ServeHTTP(sw, r)ms := uint64(time.Since(start).Milliseconds())atomic.AddUint64(&metricRequestsTotal, 1)diff --git a/internal/httpx/httpx.go b/internal/httpx/httpx.goindex b2b3677b..facc7808 100644--- a/internal/httpx/httpx.go+++ b/internal/httpx/httpx.go@@ -197,10 +197,26 @@ type ReasonRecorder interface {RecordFailureReason(code, message string)}-// RecordFailureReason gives w the code and the SANITIZED message that were just written,-// and is a no-op for a plain ResponseWriter. Producers call it; nothing re-reads the-// response body to recover what the producer already held.+// FailureCodeHeader and FailureMessageHeader carry the reason across a proxy hop: the+// producing instance stamps them, the front door reads them back into+// RecordFailureReason, and the public boundary strips them (StatusWriter, below). The+// X-Pinchtab- prefix keeps them inside the internal-header trust rules on the request+// side too.+const (+ FailureCodeHeader = "X-Pinchtab-Failure-Code"+ FailureMessageHeader = "X-Pinchtab-Failure-Message"+)++// RecordFailureReason gives w the code and the SANITIZED message that were just written.+// It stamps the hop headers so the reason survives a proxy boundary, and walks the+// recorder chain for the in-process sinks; nothing re-reads the response body to recover+// what the producer already held.func RecordFailureReason(w http.ResponseWriter, code, message string) {+ if code == "" && message == "" {+ return+ }+ w.Header().Set(FailureCodeHeader, code)+ w.Header().Set(FailureMessageHeader, message)if recorder, ok := w.(ReasonRecorder); ok {recorder.RecordFailureReason(code, message)}@@ -212,6 +228,12 @@ type StatusWriter struct {FailureCode stringFailureMessage string++ // StripFailureHeaders removes the hop headers at flush: set on the public+ // boundary, left false for a trusted internal hop so the front door can read+ // them. The header map is shared along the wrapper chain, so the innermost+ // writer's decision is the one that acts.+ StripFailureHeaders bool}// RecordFailureReason keeps the reason and passes it OUTWARD along the wrapper chain: the@@ -229,6 +251,10 @@ func (w *StatusWriter) Unwrap() http.ResponseWriter {func (w *StatusWriter) WriteHeader(code int) {w.Code = code+ if w.StripFailureHeaders {+ w.Header().Del(FailureCodeHeader)+ w.Header().Del(FailureMessageHeader)+ }w.ResponseWriter.WriteHeader(code)}diff --git a/internal/httpx/proxyheaders.go b/internal/httpx/proxyheaders.goindex db3869ab..3ffd9444 100644--- a/internal/httpx/proxyheaders.go+++ b/internal/httpx/proxyheaders.go@@ -31,6 +31,12 @@ var hopByHopHeaders = []string{"Transfer-Encoding","Upgrade","Host",+ // The failure-reason pair is consumed per hop: the proxy reads it into+ // RecordFailureReason, which re-stamps it on its own response for any+ // further hop, so a copied-through duplicate would be the one value no+ // recorder produced.+ FailureCodeHeader,+ FailureMessageHeader,}func OuterChainResponseHeaders() []string {diff --git a/internal/proxy/failure_reason_hop_test.go b/internal/proxy/failure_reason_hop_test.gonew file mode 100644index 00000000..55d27517--- /dev/null+++ b/internal/proxy/failure_reason_hop_test.go@@ -0,0 +1,73 @@+package proxy++import (+ "net/http"+ "net/http/httptest"+ "net/url"+ "testing"++ "github.com/pinchtab/pinchtab/internal/handlers"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++const hopSecret = "hop-secret"++func instanceAnsweringA500(t *testing.T) *httptest.Server {+ t.Helper()+ chain := handlers.TrustedInternalProxyStripMiddleware(hopSecret)(+ handlers.LoggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ httpx.ErrorCode(w, 500, "action_failed", "action click: ref e99 not found", true, nil)+ })))+ srv := httptest.NewServer(chain)+ t.Cleanup(srv.Close)+ return srv+}++func forwardThroughFrontDoor(t *testing.T, upstream *httptest.Server, internalToken string) (*httpx.StatusWriter, *httptest.ResponseRecorder) {+ t.Helper()+ targetURL, err := url.Parse(upstream.URL)+ if err != nil {+ t.Fatal(err)+ }++ rec := httptest.NewRecorder()+ front := handlers.LoggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ Forward(w, r, targetURL, Options{+ RewriteRequest: func(req *http.Request) {+ if internalToken != "" {+ req.Header.Set(handlers.InternalTokenHeader, internalToken)+ }+ },+ })+ }))+ outer := &httpx.StatusWriter{ResponseWriter: rec, Code: 200}+ front.ServeHTTP(outer, httptest.NewRequest("POST", "/tabs/tab1/action", nil))+ return outer, rec+}++func TestAProxiedFailureCarriesItsReasonAcrossTheHop(t *testing.T) {+ outer, rec := forwardThroughFrontDoor(t, instanceAnsweringA500(t), hopSecret)++ if outer.Code != 500 {+ t.Fatalf("front door answered %d, want the proxied 500", outer.Code)+ }+ if outer.FailureCode != "action_failed" || outer.FailureMessage != "action click: ref e99 not found" {+ t.Errorf("front-door sinks got code=%q message=%q; the instance produced the reason and the hop dropped it — the front door copies bytes it did not serialise, so only the headers can carry it", outer.FailureCode, outer.FailureMessage)+ }+ for _, h := range []string{httpx.FailureCodeHeader, httpx.FailureMessageHeader} {+ if rec.Header().Get(h) != "" {+ t.Errorf("the public response leaked the internal hop header %s=%q", h, rec.Header().Get(h))+ }+ }+}++func TestAnUntrustedHopStripsTheReasonAtTheInstanceBoundary(t *testing.T) {+ outer, _ := forwardThroughFrontDoor(t, instanceAnsweringA500(t), "")++ if outer.FailureCode != "" {+ t.Errorf("an instance that did not trust the caller still emitted the hop headers (code=%q); attached external bridges have their own auth domain and must not carry internal metadata to them", outer.FailureCode)+ }+ if outer.Code != 500 {+ t.Fatalf("the 500 itself must still proxy, got %d", outer.Code)+ }+}diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.goindex 498dd223..c5c0011c 100644--- a/internal/proxy/proxy.go+++ b/internal/proxy/proxy.go@@ -86,6 +86,7 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Opdefer func() { _ = resp.Body.Close() }()httpx.CopyProxiedResponseHeaders(w.Header(), resp.Header)+ recordProxiedFailureReason(w, resp)// Enrich activity from response headers (always available, regardless of body size).enrichActivityFromHeaders(r, resp.Header)@@ -147,6 +148,20 @@ func HTTP(w http.ResponseWriter, r *http.Request, targetURL string) {// enrichActivityFromHeaders extracts tab ID from upstream response headers// and enriches the activity event. This works for all response sizes,// unlike body-based enrichment which is limited to small JSON responses.+// recordProxiedFailureReason carries the reason across the hop: the instance's error+// producer stamped these headers on the response it serialised, so reading them here+// keeps the reason coming from the producer — never from re-parsing the body.+func recordProxiedFailureReason(w http.ResponseWriter, resp *http.Response) {+ if resp.StatusCode < 400 {+ return+ }+ code := strings.TrimSpace(resp.Header.Get(httpx.FailureCodeHeader))+ if code == "" {+ return+ }+ httpx.RecordFailureReason(w, code, resp.Header.Get(httpx.FailureMessageHeader))+}+func enrichActivityFromHeaders(origReq *http.Request, respHeaders http.Header) {tabID := strings.TrimSpace(respHeaders.Get(activity.HeaderPTTabID))if tabID != "" {