Skip to content

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

fix(proxy): honour the whole rewritten request and re-gate a moved target

Luigi Agosti6e77ac0066a0
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 19328aa7..5cdae984 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -61,17 +61,33 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op
return
}
+ // The hook gets its OWN url. Handing it targetURL made the two the same
+ // object, so a hook that touched req.URL edited the value AllowedURL had
+ // already approved — and the caller's, which it does not own. Re-gating an
+ // aliased url is also unable to see the change: the orchestrator's gate asks
+ // whether the url is same-origin with targetURL, and an alias always is.
+ routedURL := *targetURL
+
proxyReq := r.Clone(r.Context())
- proxyReq.URL = targetURL
- proxyReq.Host = targetURL.Host
+ proxyReq.URL = &routedURL
+ proxyReq.Host = routedURL.Host
proxyReq.Header = r.Header.Clone()
activity.PropagateHeaders(r.Context(), proxyReq)
+ hostBeforeRewrite := proxyReq.Host
if opts.RewriteRequest != nil {
opts.RewriteRequest(proxyReq)
}
+ // A rewrite that moved the target has to pass the same gate the original did,
+ // or the hook is a way around it. Only re-asked when the target actually
+ // changed, so the common path costs nothing.
+ if opts.AllowedURL != nil && proxyReq.URL.String() != targetURL.String() && !opts.AllowedURL(proxyReq.URL) {
+ httpx.Error(w, 400, fmt.Errorf("invalid proxy target"))
+ return
+ }
+
if isWebSocketUpgrade(proxyReq) {
- ProxyWebSocket(w, proxyReq, targetURL.String())
+ ProxyWebSocket(w, proxyReq, proxyReq.URL.String())
return
}
@@ -80,11 +96,27 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op
client = DefaultClient
}
- outReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL.String(), r.Body)
+ // Built from proxyReq, not from r: RewriteRequest is handed a whole
+ // *http.Request and the WebSocket path below honours the whole of it, so
+ // re-deriving the method, target and body from the original request made a
+ // hook that rewrote any of them work over WebSocket and be silently ignored
+ // over HTTP. Nothing in the module rewrites more than headers today, so this
+ // changes no traffic — it makes the hook's own signature true before someone
+ // takes it at its word.
+ //
+ // proxyReq cannot be sent as-is: it is a server request and carries
+ // RequestURI, which a client request may not set.
+ outReq, err := http.NewRequestWithContext(r.Context(), proxyReq.Method, proxyReq.URL.String(), proxyReq.Body)
if err != nil {
httpx.Error(w, 502, fmt.Errorf("proxy error: %w", err))
return
}
+ // Only a rewrite propagates a Host. Left alone, the transport derives the
+ // Host header from the URL as before, which spells a default port the way
+ // the wire expects rather than the way targetURL.Host holds it.
+ if proxyReq.Host != hostBeforeRewrite {
+ outReq.Host = proxyReq.Host
+ }
copyRequestHeaders(outReq.Header, proxyReq.Header)
httpx.ForwardRequestID(outReq.Header, proxyReq.Header)
diff --git a/internal/proxy/rewrite_request_hop_test.go b/internal/proxy/rewrite_request_hop_test.go
new file mode 100644
index 00000000..4822ce2d
--- /dev/null
+++ b/internal/proxy/rewrite_request_hop_test.go
@@ -0,0 +1,212 @@
+package proxy
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+)
+
+// upstreamEcho records what the upstream actually received.
+type upstreamEcho struct {
+ mu sync.Mutex
+ method string
+ path string
+ query string
+ host string
+ body string
+ header http.Header
+}
+
+func newUpstream(t *testing.T) (*httptest.Server, *upstreamEcho) {
+ t.Helper()
+ seen := &upstreamEcho{}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ seen.mu.Lock()
+ seen.method, seen.path, seen.query = r.Method, r.URL.Path, r.URL.RawQuery
+ seen.host, seen.body, seen.header = r.Host, string(body), r.Header.Clone()
+ seen.mu.Unlock()
+ w.WriteHeader(204)
+ }))
+ t.Cleanup(srv.Close)
+ return srv, seen
+}
+
+func forwardTo(t *testing.T, srv *httptest.Server, inbound *http.Request, rewrite func(*http.Request)) {
+ t.Helper()
+ target, err := url.Parse(srv.URL + "/upstream")
+ if err != nil {
+ t.Fatalf("parse target: %v", err)
+ }
+ Forward(httptest.NewRecorder(), inbound, target, Options{RewriteRequest: rewrite})
+}
+
+// RewriteRequest is handed a whole *http.Request, and the WebSocket branch of
+// Forward honours the whole of it. The HTTP branch re-derived the method, the
+// target and the body from the ORIGINAL request, so a hook that rewrote any of
+// them took effect on one transport and was silently dropped on the other.
+func TestRewriteRequestReachesTheUpstreamOnTheHTTPPath(t *testing.T) {
+ srv, seen := newUpstream(t)
+
+ inbound := httptest.NewRequest("POST", "/original", strings.NewReader("original-body"))
+ forwardTo(t, srv, inbound, func(req *http.Request) {
+ req.Method = "PUT"
+ req.URL.Path = "/rewritten"
+ req.URL.RawQuery = "rewritten=1"
+ req.Body = io.NopCloser(strings.NewReader("rewritten-body"))
+ })
+
+ seen.mu.Lock()
+ defer seen.mu.Unlock()
+ if seen.method != "PUT" {
+ t.Errorf("upstream saw method %q, want the rewritten PUT", seen.method)
+ }
+ if seen.path != "/rewritten" {
+ t.Errorf("upstream saw path %q, want the rewritten path", seen.path)
+ }
+ if seen.query != "rewritten=1" {
+ t.Errorf("upstream saw query %q, want the rewritten query", seen.query)
+ }
+ if seen.body != "rewritten-body" {
+ t.Errorf("upstream saw body %q, want the rewritten body", seen.body)
+ }
+}
+
+// A rewriter that sets Host must reach the wire; the Host header is how a shared
+// upstream tells virtual hosts apart.
+func TestRewriteRequestCanSetTheHostHeader(t *testing.T) {
+ srv, seen := newUpstream(t)
+
+ inbound := httptest.NewRequest("GET", "/original", nil)
+ forwardTo(t, srv, inbound, func(req *http.Request) {
+ req.Host = "rewritten.example"
+ })
+
+ seen.mu.Lock()
+ defer seen.mu.Unlock()
+ if seen.host != "rewritten.example" {
+ t.Errorf("upstream saw Host %q, want the rewritten host", seen.host)
+ }
+}
+
+// Header rewriting is what every hook in the module does today, and it must keep
+// arriving unchanged.
+func TestRewriteRequestHeadersStillReachTheUpstream(t *testing.T) {
+ srv, seen := newUpstream(t)
+
+ inbound := httptest.NewRequest("GET", "/original", nil)
+ forwardTo(t, srv, inbound, func(req *http.Request) {
+ req.Header.Set("X-Rewritten", "yes")
+ })
+
+ seen.mu.Lock()
+ defer seen.mu.Unlock()
+ if got := seen.header.Get("X-Rewritten"); got != "yes" {
+ t.Errorf("upstream saw X-Rewritten %q, want yes", got)
+ }
+}
+
+// With no rewriter, every field must still be taken from the inbound request and
+// the target URL exactly as before — including the Host, which the transport
+// derives from the URL rather than from targetURL.Host.
+func TestForwardWithoutARewriterIsUnchanged(t *testing.T) {
+ srv, seen := newUpstream(t)
+ upstreamHost := strings.TrimPrefix(srv.URL, "http://")
+
+ inbound := httptest.NewRequest("POST", "/original?keep=1", strings.NewReader("inbound-body"))
+ forwardTo(t, srv, inbound, nil)
+
+ seen.mu.Lock()
+ defer seen.mu.Unlock()
+ if seen.method != "POST" {
+ t.Errorf("method = %q, want POST", seen.method)
+ }
+ if seen.path != "/upstream" {
+ t.Errorf("path = %q, want the target's path", seen.path)
+ }
+ if seen.body != "inbound-body" {
+ t.Errorf("body = %q, want the inbound body", seen.body)
+ }
+ if seen.host != upstreamHost {
+ t.Errorf("Host = %q, want the target host %q the transport derives from the URL", seen.host, upstreamHost)
+ }
+}
+
+// AllowedURL gates the target before the hook runs, and the hook can move the
+// target. Sharing one *url.URL between the two meant the gate approved an object
+// the hook then edited — and a gate that asks "is this still the same origin?"
+// cannot notice, because an alias always is.
+func TestARewriteThatMovesTheTargetIsGatedAgain(t *testing.T) {
+ srv, seen := newUpstream(t)
+ elsewhere, elsewhereSeen := newUpstream(t)
+
+ approved := 0
+ target, err := url.Parse(srv.URL + "/upstream")
+ if err != nil {
+ t.Fatalf("parse target: %v", err)
+ }
+ original := target.String()
+
+ w := httptest.NewRecorder()
+ Forward(w, httptest.NewRequest("GET", "/original", nil), target, Options{
+ AllowedURL: func(u *url.URL) bool {
+ approved++
+ return u.String() == original
+ },
+ RewriteRequest: func(req *http.Request) {
+ moved, parseErr := url.Parse(elsewhere.URL + "/elsewhere")
+ if parseErr != nil {
+ t.Errorf("parse moved target: %v", parseErr)
+ return
+ }
+ *req.URL = *moved
+ },
+ })
+
+ if approved < 2 {
+ t.Errorf("AllowedURL was consulted %d time(s); a moved target must be re-gated", approved)
+ }
+ if w.Code != 400 {
+ t.Errorf("status = %d, want 400; the rewritten target was not approved", w.Code)
+ }
+ elsewhereSeen.mu.Lock()
+ reached := elsewhereSeen.path
+ elsewhereSeen.mu.Unlock()
+ if reached != "" {
+ t.Errorf("the request reached %q despite failing the gate", reached)
+ }
+ if target.String() != original {
+ t.Errorf("the caller's target URL was mutated to %q; Forward must not edit what it was handed", target)
+ }
+ seen.mu.Lock()
+ defer seen.mu.Unlock()
+ if seen.path != "" {
+ t.Errorf("the original upstream was contacted at %q after a refused rewrite", seen.path)
+ }
+}
+
+// A rewrite that stays on the approved target must not pay for a second gate
+// call — the common path, and the one the orchestrator would answer by
+// re-scanning its instance table.
+func TestARewriteThatKeepsTheTargetIsNotGatedTwice(t *testing.T) {
+ srv, _ := newUpstream(t)
+
+ approved := 0
+ target, err := url.Parse(srv.URL + "/upstream")
+ if err != nil {
+ t.Fatalf("parse target: %v", err)
+ }
+
+ Forward(httptest.NewRecorder(), httptest.NewRequest("GET", "/original", nil), target, Options{
+ AllowedURL: func(*url.URL) bool { approved++; return true },
+ RewriteRequest: func(req *http.Request) { req.Header.Set("X-Rewritten", "yes") },
+ })
+
+ if approved != 1 {
+ t.Errorf("AllowedURL was consulted %d times for an unmoved target, want 1", approved)
+ }
+}