High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: forward the outer request id across every proxy hop so one request is traceable in both logs (PIN-138)
Luigi Agosti0ca06b7b3f1a
diff --git a/internal/httpx/proxyheaders.go b/internal/httpx/proxyheaders.goindex 3ffd9444..02e853d3 100644--- a/internal/httpx/proxyheaders.go+++ b/internal/httpx/proxyheaders.go@@ -60,6 +60,27 @@ func containsFold(names []string, key string) bool {return false}+// ForwardRequestID is the one mechanism that decides the request id an instance is told,+// and it is the request-side companion to CopyProxiedResponseHeaders below.+//+// A hop that tells the instance nothing is the reason a phantom id existed: the instance+// found no inbound id, minted its own, and returned it on a response that already carried+// the outer chain's, so a caller could be handed a string that appears in no log on disk.+// Forwarding the outer chain's resolved value instead makes ONE proxied request findable+// by ONE id in both logs.+//+// It is deliberately narrow — this header and no other. A hop that fixed traceability by+// widening into a wholesale request copy would carry the caller's cookie and network+// identity to the instance along with it, which is what the per-hop strip lists exist to+// prevent. Callers that strip this header from their blind copy call this AFTER the strip:+// the two are different permissions, since a copy forwards whatever arrived under that+// name while this forwards the one value the outer chain resolved for this request.+func ForwardRequestID(dst, src http.Header) {+ if rid := strings.TrimSpace(src.Get(HeaderRequestID)); rid != "" {+ dst.Set(HeaderRequestID, rid)+ }+}+// CopyProxiedResponseHeaders is the one response-header copy every proxy hop uses. The// outer middleware chain has already set its own X-Request-Id and security headers on this// response, so appending the upstream copies makes them multi-valued: a caller then seesdiff --git a/internal/instance/bridge_client.go b/internal/instance/bridge_client.goindex 3e0c37f1..e37af60c 100644--- a/internal/instance/bridge_client.go+++ b/internal/instance/bridge_client.go@@ -169,6 +169,11 @@ func (bc *BridgeClient) ProxyWithTabID(w http.ResponseWriter, r *http.Request, preturn}proxyReq.Header.Set("Content-Type", "application/json")+ // This hop re-encodes the body and so builds a fresh request rather than copying the+ // caller's, which means it tells the instance nothing unless asked to. The request id+ // is forwarded explicitly — and only the request id, so re-encoding does not become a+ // back door around the headers the copying hops deliberately strip.+ httpx.ForwardRequestID(proxyReq.Header, r.Header)resp, err := bc.client.Do(proxyReq)if err != nil {diff --git a/internal/instance/bridge_client_proxy_headers_test.go b/internal/instance/bridge_client_proxy_headers_test.goindex 76eda693..34a4991c 100644--- a/internal/instance/bridge_client_proxy_headers_test.go+++ b/internal/instance/bridge_client_proxy_headers_test.go@@ -110,3 +110,88 @@ func TestProxyToTabForwardsRequestHeadersButNotHopByHopOnes(t *testing.T) {t.Errorf("Te = %q, want the hop-by-hop header dropped on the proxy hop", got)}}++// Both bridge hops must tell the instance the outer chain's request id, or a caller+// quoting it can only be found in the outer log. They arrive at that from opposite+// directions and so are asserted together: ProxyToTab copies the caller's headers and+// carries the id along with them, while ProxyWithTabID re-encodes the body and builds a+// FRESH request, so it tells the instance nothing unless the id is forwarded explicitly.+// That asymmetry is why one hop having it says nothing about the other.+func TestBothBridgeHopsTellTheInstanceTheOuterChainsRequestID(t *testing.T) {+ for _, tc := range []struct {+ name string+ call func(client *BridgeClient, rec *httptest.ResponseRecorder, req *http.Request, port string)+ }{+ {+ name: "ProxyWithTabID re-encodes the body and builds a fresh request",+ call: func(client *BridgeClient, rec *httptest.ResponseRecorder, req *http.Request, port string) {+ client.ProxyWithTabID(rec, req, port, "tab-1", "/find")+ },+ },+ {+ name: "ProxyToTab copies the caller's headers",+ call: func(client *BridgeClient, rec *httptest.ResponseRecorder, req *http.Request, port string) {+ client.ProxyToTab(rec, req, port, "tab-1", "/text")+ },+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ var seen http.Header+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seen = r.Header.Clone()+ w.WriteHeader(200)+ }))+ defer srv.Close()++ parsed, err := url.Parse(srv.URL)+ if err != nil {+ t.Fatal(err)+ }++ req := httptest.NewRequest("POST", "/find", strings.NewReader(`{"text":"Buy"}`))+ req.Header.Set(httpx.HeaderRequestID, "outer-trace-key")++ tc.call(NewBridgeClient(), httptest.NewRecorder(), req, parsed.Port())++ if seen == nil {+ t.Fatal("the instance received no request; this test is measuring nothing")+ }+ if got := seen.Get(httpx.HeaderRequestID); got != "outer-trace-key" {+ t.Errorf("instance was told %q, want the outer chain's id — without it the instance mints its own and one request needs two ids to trace", got)+ }+ })+ }+}++// The narrowness guard for the fresh-request hop: it must forward the request id and+// nothing else. Re-encoding the body is not a licence to hand over the caller's cookie.+func TestProxyWithTabIDForwardsOnlyTheRequestID(t *testing.T) {+ var seen http.Header+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seen = r.Header.Clone()+ w.WriteHeader(200)+ }))+ defer srv.Close()++ parsed, err := url.Parse(srv.URL)+ if err != nil {+ t.Fatal(err)+ }++ req := httptest.NewRequest("POST", "/find", strings.NewReader(`{"text":"Buy"}`))+ req.Header.Set(httpx.HeaderRequestID, "outer-trace-key")+ req.Header.Set("Cookie", "pinchtab_auth_token=session-secret")+ req.Header.Set("X-Forwarded-For", "203.0.113.10")+ req.Header.Set("Authorization", "Bearer user-token")++ NewBridgeClient().ProxyWithTabID(httptest.NewRecorder(), req, parsed.Port(), "tab-1", "/find")++ if got := seen.Get(httpx.HeaderRequestID); got != "outer-trace-key" {+ t.Fatalf("request id = %q, want it forwarded — the rest of this test cannot tell a narrow forward from no forward without it", got)+ }+ for _, name := range []string{"Cookie", "X-Forwarded-For", "Authorization"} {+ if got := seen.Get(name); got != "" {+ t.Errorf("%s = %q reached the instance; this hop builds a fresh request precisely so the caller's headers do not travel, and forwarding the id widened it", name, got)+ }+ }+}diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.goindex c5c0011c..e3d53ccb 100644--- a/internal/proxy/proxy.go+++ b/internal/proxy/proxy.go@@ -32,6 +32,19 @@ type Options struct {OnResponse func(origReq *http.Request, body []byte)}+// strippedProxyRequestHeaders never reach the instance by being COPIED. Every member is+// dropped from the blind copy; x-request-id is then re-added deliberately by+// httpx.ForwardRequestID, which is what makes one proxied request traceable in both the+// outer and the instance log instead of only the outer one.+//+// It stays on this list rather than being deleted from it because the two are different+// permissions: pass-through would forward whatever arrived under that name from anywhere,+// while the re-add forwards the one value the outer chain resolved for this request.+// RequestIDMiddleware stamps that value onto the request, so what is forwarded is the id+// the outer server logs — including when the caller supplied it, which that middleware+// honours by design. The rest of this list protects genuinely different things and is+// untouched: cookie carries the session secret, and the forwarding trio plus x-real-ip+// carry client network identity the instance has no business learning.var strippedProxyRequestHeaders = map[string]struct{}{"cookie": {},"forwarded": {},@@ -77,6 +90,7 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Opreturn}copyRequestHeaders(outReq.Header, proxyReq.Header)+ httpx.ForwardRequestID(outReq.Header, proxyReq.Header)resp, err := client.Do(outReq)if err != nil {diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.goindex 311fe84f..be9583ac 100644--- a/internal/proxy/proxy_test.go+++ b/internal/proxy/proxy_test.go@@ -127,11 +127,22 @@ func TestHTTP_StripsSensitiveRequestHeaders(t *testing.T) {if resp["authorization"] != "Bearer user-token" {t.Fatalf("authorization = %v, want preserved bearer token", resp["authorization"])}- for _, field := range []string{"cookie", "xForwardedFor", "xForwardedHost", "xForwardedProto", "forwarded", "xRealIP", "xRequestID"} {+ for _, field := range []string{"cookie", "xForwardedFor", "xForwardedHost", "xForwardedProto", "forwarded", "xRealIP"} {if got := resp[field]; got != "" {t.Fatalf("%s should have been stripped, got %v", field, got)}}++ // X-Request-Id is the deliberate exception to this strip list, and it is asserted in+ // the same test as the members that stay stripped so the two cannot drift apart.+ // Forwarding it is what makes one proxied request findable in the instance log as well+ // as the outer one; without it the instance mints an id of its own that appears in no+ // log a caller could be pointed at. The value is client-influenced here on purpose —+ // RequestIDMiddleware honours an inbound id by design and the outer server already+ // logs it, so the instance learns nothing the outer log does not already contain.+ if got := resp["xRequestID"]; got != "req-123" {+ t.Fatalf("xRequestID = %v, want the outer id req-123 forwarded so both logs carry it", got)+ }}func TestHTTP_UsesSharedClient(t *testing.T) {diff --git a/internal/proxy/proxy_ws.go b/internal/proxy/proxy_ws.goindex 30281baa..bdea29fe 100644--- a/internal/proxy/proxy_ws.go+++ b/internal/proxy/proxy_ws.go@@ -104,6 +104,11 @@ func filterProxyWSHeaders(headers http.Header) http.Header {copied := append([]string(nil), values...)filtered[textproto.CanonicalMIMEHeaderKey(name)] = copied}+ // Deliberately after the allow-list rather than inside it: a WebSocket hop is traced+ // like any other, and the id forwarded is the outer chain's resolved value rather than+ // whatever arrived under that name. Same owner as the HTTP hop, so the two cannot+ // disagree about what an instance is told.+ httpx.ForwardRequestID(filtered, headers)return filtered}diff --git a/internal/proxy/proxy_ws_test.go b/internal/proxy/proxy_ws_test.goindex babef419..a081393f 100644--- a/internal/proxy/proxy_ws_test.go+++ b/internal/proxy/proxy_ws_test.go@@ -21,11 +21,18 @@ func TestFilterProxyWSHeaders_StripsSensitiveHeaders(t *testing.T) {filtered := filterProxyWSHeaders(headers)- for _, forbidden := range []string{"Authorization", "Cookie", "X-Forwarded-For", "X-Request-Id"} {+ for _, forbidden := range []string{"Authorization", "Cookie", "X-Forwarded-For"} {if got := filtered.Get(forbidden); got != "" {t.Fatalf("%s should have been stripped, got %q", forbidden, got)}}++ // A WebSocket hop is traced like any other, so the request id is forwarded here too,+ // through the same owner the HTTP hop uses. Asserted beside the headers that stay+ // stripped: the allow-list still refuses it, and the forward re-adds it after.+ if got := filtered.Get("X-Request-Id"); got != "request-123" {+ t.Fatalf("X-Request-Id = %q, want the outer id forwarded so the instance logs the same one", got)+ }for _, allowed := range []string{"Connection", "Upgrade", "Sec-WebSocket-Key", "Sec-WebSocket-Version", "Sec-WebSocket-Protocol", "Sec-WebSocket-Extensions"} {if got := filtered.Get(allowed); got == "" {t.Fatalf("%s should have been forwarded", allowed)diff --git a/internal/proxy/request_id_hop_test.go b/internal/proxy/request_id_hop_test.gonew file mode 100644index 00000000..d3ab299b--- /dev/null+++ b/internal/proxy/request_id_hop_test.go@@ -0,0 +1,237 @@+package proxy++import (+ "context"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "sync"+ "testing"++ "github.com/pinchtab/pinchtab/internal/handlers"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++// requestIDLogCapture reads the requestId attribute off the access-log records+// LoggingMiddleware emits, so a test can assert what a hop actually LOGGED rather than+// inferring it from what the hop was sent. That distinction is the whole criterion here:+// the id has to be findable on disk, and the access log is where an operator looks.+type requestIDLogCapture struct {+ mu sync.Mutex+ ids []string+}++func (c *requestIDLogCapture) Enabled(context.Context, slog.Level) bool { return true }++func (c *requestIDLogCapture) WithAttrs([]slog.Attr) slog.Handler { return c }++func (c *requestIDLogCapture) WithGroup(string) slog.Handler { return c }++func (c *requestIDLogCapture) Handle(_ context.Context, record slog.Record) error {+ record.Attrs(func(attr slog.Attr) bool {+ if attr.Key == "requestId" {+ c.mu.Lock()+ c.ids = append(c.ids, attr.Value.String())+ c.mu.Unlock()+ }+ return true+ })+ return nil+}++func (c *requestIDLogCapture) logged() []string {+ c.mu.Lock()+ defer c.mu.Unlock()+ return append([]string(nil), c.ids...)+}++func captureAccessLog(t *testing.T) *requestIDLogCapture {+ t.Helper()++ capture := &requestIDLogCapture{}+ previous := slog.Default()+ slog.SetDefault(slog.New(capture))+ t.Cleanup(func() { slog.SetDefault(previous) })+ return capture+}++// The criterion literally: ONE proxied request, and the SAME id in BOTH access logs. Both+// hops run the real RequestIDMiddleware and the real LoggingMiddleware, and the assertion+// reads the emitted log records — so this fails if the instance logs an id of its own,+// which is exactly the state that made a quoted id unfindable.+func TestTheSameRequestIDIsLoggedByBothTheOuterServerAndTheInstance(t *testing.T) {+ capture := captureAccessLog(t)++ instance := httptest.NewServer(handlers.RequestIDMiddleware(handlers.LoggingMiddleware(+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }))))+ t.Cleanup(instance.Close)++ targetURL, err := url.Parse(instance.URL)+ if err != nil {+ t.Fatal(err)+ }+ front := handlers.RequestIDMiddleware(handlers.LoggingMiddleware(+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ Forward(w, r, targetURL, Options{})+ })))+ front.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/tabs", nil))++ logged := capture.logged()+ if len(logged) != 2 {+ t.Fatalf("access log produced %d requestId entries (%v), want one from each hop; this test is measuring nothing otherwise", len(logged), logged)+ }+ if logged[0] == "" || logged[1] == "" {+ t.Fatalf("an access-log entry carried no requestId: %v", logged)+ }+ if logged[0] != logged[1] {+ t.Errorf("instance logged %q and the outer server logged %q — one request wrote two ids, so a caller quoting either can be found in only one log", logged[0], logged[1])+ }+}++// instanceEchoingItsOwnRequestID stands in for the instance: it runs the SAME+// RequestIDMiddleware the outer server does, which is the whole point — that middleware+// honours an inbound id and mints one only when there is none, so what it resolves is+// exactly what the instance would write in its own log. The resolved id is echoed in the+// body so a test can read what the instance logged, not merely what it was sent.+func instanceEchoingItsOwnRequestID(t *testing.T) *httptest.Server {+ t.Helper()++ srv := httptest.NewServer(handlers.RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(r.Header.Get(httpx.HeaderRequestID)))+ })))+ t.Cleanup(srv.Close)+ return srv+}++func proxyThroughOuterChain(t *testing.T, upstream *httptest.Server, inbound string) (outerID string, instanceID string, response *httptest.ResponseRecorder) {+ t.Helper()++ targetURL, err := url.Parse(upstream.URL)+ if err != nil {+ t.Fatal(err)+ }++ rec := httptest.NewRecorder()+ front := handlers.RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // What the outer chain resolved for this request: RequestIDMiddleware stamps it+ // onto the request, and it is the value msg=request logs.+ outerID = r.Header.Get(httpx.HeaderRequestID)+ Forward(w, r, targetURL, Options{})+ }))++ req := httptest.NewRequest("GET", "/tabs", nil)+ if inbound != "" {+ req.Header.Set(httpx.HeaderRequestID, inbound)+ }+ front.ServeHTTP(rec, req)+ return outerID, rec.Body.String(), rec+}++// The traceability half, and the criterion that defines done: ONE proxied request must be+// findable by ONE id in both logs. Before the forward the instance was told nothing, minted+// its own id and returned it, so a caller could be handed a string that appears in no log+// on disk.+//+// Both halves are asserted together on purpose. Filtering alone leaves the response+// single-valued but the instance still logging a different id; forwarding alone makes the+// two ids equal but the header still multi-valued. Neither substitutes for the other, so a+// build that did one and not the other must fail here.+func TestOneProxiedRequestIsTraceableByOneIDInBothLogs(t *testing.T) {+ for _, tc := range []struct {+ name string+ inbound string+ }{+ {name: "the outer chain mints the id", inbound: ""},+ {name: "a caller supplies its own trace key", inbound: "caller-chosen-trace-key"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ outerID, instanceID, rec := proxyThroughOuterChain(t, instanceEchoingItsOwnRequestID(t), tc.inbound)++ if outerID == "" {+ t.Fatal("the outer chain resolved no request id; this test is measuring nothing")+ }+ if tc.inbound != "" && outerID != tc.inbound {+ t.Errorf("outer id = %q, want the caller's own %q honoured", outerID, tc.inbound)+ }++ // The forwarding half.+ if instanceID != outerID {+ t.Errorf("instance logged %q but the outer chain logged %q — a caller quoting one id can only be found in one of the two logs", instanceID, outerID)+ }++ // The doubling half, on the same response.+ values := rec.Header().Values(httpx.HeaderRequestID)+ if len(values) != 1 {+ t.Fatalf("%s = %v, want exactly one value; a caller cannot tell which of two ids their HTTP library will show them", httpx.HeaderRequestID, values)+ }+ if values[0] != outerID {+ t.Errorf("response carries %q but the outer chain logged %q, so the value a caller reads is not the one on disk", values[0], outerID)+ }+ })+ }+}++// The forward must not become a wholesale request-header copy. This is the guard-rail the+// gate asked for: the rest of the strip list protects things the instance has no business+// learning, and widening the forward to fix traceability would quietly hand them over.+func TestForwardingTheRequestIDDoesNotWidenIntoAWholesaleCopy(t *testing.T) {+ var received http.Header+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ received = r.Header.Clone()+ }))+ t.Cleanup(upstream.Close)++ targetURL, err := url.Parse(upstream.URL)+ if err != nil {+ t.Fatal(err)+ }++ req := httptest.NewRequest("GET", "/tabs", nil)+ for name, value := range map[string]string{+ "Cookie": "pinchtab_auth_token=session-secret",+ "Forwarded": "for=203.0.113.10",+ "X-Forwarded-For": "203.0.113.10",+ "X-Forwarded-Host": "app.example",+ "X-Forwarded-Proto": "https",+ "X-Real-Ip": "203.0.113.10",+ } {+ req.Header.Set(name, value)+ }+ req.Header.Set(httpx.HeaderRequestID, "traced")++ front := handlers.RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ Forward(w, r, targetURL, Options{})+ }))+ front.ServeHTTP(httptest.NewRecorder(), req)++ if received == nil {+ t.Fatal("upstream received no request; this test is measuring nothing")+ }+ if got := received.Get(httpx.HeaderRequestID); got != "traced" {+ t.Fatalf("request id = %q, want it forwarded — without that the rest of this test cannot distinguish a narrow forward from no forward at all", got)+ }+ for _, name := range []string{"Cookie", "Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "X-Real-Ip"} {+ if got := received.Get(name); got != "" {+ t.Errorf("%s = %q reached the instance; forwarding the request id widened into a wholesale copy and carried a stripped header with it", name, got)+ }+ }+}++// The strip list and the forward are two different permissions over one header name, and+// the census keeps them from collapsing into each other: x-request-id must stay ON the+// strip list (so a copied value never passes) while the forward re-adds the resolved one.+// Deleting it from the list would also forward it, and every behavioural test above would+// stay green — this is the only check that tells the two implementations apart.+func TestTheRequestIDIsForwardedByReAddingItRatherThanByLeavingTheStripList(t *testing.T) {+ if _, stripped := strippedProxyRequestHeaders[strings.ToLower(httpx.HeaderRequestID)]; !stripped {+ t.Error("x-request-id left strippedProxyRequestHeaders; it must stay stripped from the blind copy and be re-added by httpx.ForwardRequestID, or an arbitrary inbound value passes through on any path that skipped the outer middleware")+ }++ copied := http.Header{}+ copyRequestHeaders(copied, http.Header{httpx.HeaderRequestID: {"from-the-blind-copy"}})+ if got := copied.Get(httpx.HeaderRequestID); got != "" {+ t.Errorf("the blind copy carried the request id as %q; the re-add is meant to be the only way it travels", got)+ }+}