Skip to content

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

8.0 KB
Raw Blame
package proxy

import (
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/pinchtab/pinchtab/internal/httpx"
)

func fakeBridge(t *testing.T) *httptest.Server {
	t.Helper()
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{
			"proxied": true,
			"path":    r.URL.Path,
			"query":   r.URL.RawQuery,
		})
	}))
}

func TestHTTP_ForwardsRequest(t *testing.T) {
	srv := fakeBridge(t)
	defer srv.Close()

	req := httptest.NewRequest("GET", "/snapshot", nil)
	rec := httptest.NewRecorder()
	HTTP(rec, req, srv.URL+"/snapshot")

	if rec.Code != 200 {
		t.Errorf("expected 200, got %d: %s", rec.Code, rec.Body.String())
	}

	var resp map[string]any
	_ = json.Unmarshal(rec.Body.Bytes(), &resp)
	if resp["path"] != "/snapshot" {
		t.Errorf("expected path /snapshot, got %v", resp["path"])
	}
}

func TestHTTP_ForwardsQueryParams(t *testing.T) {
	srv := fakeBridge(t)
	defer srv.Close()

	req := httptest.NewRequest("GET", "/screenshot?raw=true", nil)
	rec := httptest.NewRecorder()
	HTTP(rec, req, srv.URL+"/screenshot")

	if rec.Code != 200 {
		t.Errorf("expected 200, got %d", rec.Code)
	}

	var resp map[string]any
	_ = json.Unmarshal(rec.Body.Bytes(), &resp)
	if resp["query"] != "raw=true" {
		t.Errorf("expected query raw=true, got %v", resp["query"])
	}
}

func TestHTTP_UnreachableReturns502(t *testing.T) {
	req := httptest.NewRequest("GET", "/snapshot", nil)
	rec := httptest.NewRecorder()
	HTTP(rec, req, "http://localhost:1/snapshot")

	if rec.Code != 502 {
		t.Errorf("expected 502, got %d", rec.Code)
	}
}

func TestHTTP_CopiesResponseHeaders(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Custom", "test-value")
		w.WriteHeader(201)
	}))
	defer srv.Close()

	req := httptest.NewRequest("GET", "/test", nil)
	rec := httptest.NewRecorder()
	HTTP(rec, req, srv.URL+"/test")

	if rec.Code != 201 {
		t.Errorf("expected 201, got %d", rec.Code)
	}
	if rec.Header().Get("X-Custom") != "test-value" {
		t.Errorf("expected X-Custom header, got %q", rec.Header().Get("X-Custom"))
	}
}

func TestHTTP_StripsSensitiveRequestHeaders(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_ = json.NewEncoder(w).Encode(map[string]any{
			"authorization":   r.Header.Get("Authorization"),
			"cookie":          r.Header.Get("Cookie"),
			"xForwardedFor":   r.Header.Get("X-Forwarded-For"),
			"xForwardedHost":  r.Header.Get("X-Forwarded-Host"),
			"xForwardedProto": r.Header.Get("X-Forwarded-Proto"),
			"forwarded":       r.Header.Get("Forwarded"),
			"xRealIP":         r.Header.Get("X-Real-Ip"),
			"xRequestID":      r.Header.Get("X-Request-Id"),
		})
	}))
	defer srv.Close()

	req := httptest.NewRequest("GET", "/snapshot", nil)
	req.Header.Set("Authorization", "Bearer user-token")
	req.Header.Set("Cookie", "pinchtab_auth_token=session-secret")
	req.Header.Set("X-Forwarded-For", "203.0.113.10")
	req.Header.Set("X-Forwarded-Host", "app.example")
	req.Header.Set("X-Forwarded-Proto", "https")
	req.Header.Set("Forwarded", `for=203.0.113.10;host=app.example;proto=https`)
	req.Header.Set("X-Real-Ip", "203.0.113.10")
	req.Header.Set("X-Request-Id", "req-123")

	rec := httptest.NewRecorder()
	HTTP(rec, req, srv.URL+"/snapshot")

	if rec.Code != 200 {
		t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
	}

	var resp map[string]any
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	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"} {
		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) {
	if DefaultClient == nil {
		t.Fatal("DefaultClient should not be nil")
	}
	if DefaultClient.Timeout != httpx.MaxNavigationHTTPDuration {
		t.Errorf("timeout = %s, want %s", DefaultClient.Timeout, httpx.MaxNavigationHTTPDuration)
	}
}

func TestIsWebSocketUpgrade(t *testing.T) {
	tests := []struct {
		name   string
		header http.Header
		want   bool
	}{
		{"no upgrade", http.Header{}, false},
		{"websocket", http.Header{"Upgrade": {"websocket"}}, true},
		{"WebSocket", http.Header{"Upgrade": {"WebSocket"}}, true},
		{"other", http.Header{"Upgrade": {"h2c"}}, false},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			r := httptest.NewRequest("GET", "/", nil)
			r.Header = tt.header
			if got := isWebSocketUpgrade(r); got != tt.want {
				t.Errorf("isWebSocketUpgrade() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestHTTP_DoesNotDoubleTheOuterChainsResponseHeaders(t *testing.T) {
	owned := httpx.OuterChainResponseHeaders()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		for _, name := range owned {
			w.Header().Set(name, "instance-"+name)
		}
		w.WriteHeader(200)
	}))
	defer srv.Close()

	req := httptest.NewRequest("GET", "/tabs", nil)
	rec := httptest.NewRecorder()
	for _, name := range owned {
		rec.Header().Set(name, "outer-"+name)
	}

	HTTP(rec, req, srv.URL+"/tabs")

	if rec.Code != 200 {
		t.Fatalf("expected 200, got %d", rec.Code)
	}
	for _, name := range owned {
		got := rec.Header().Values(name)
		if len(got) != 1 {
			t.Errorf("%s = %v, want exactly one value — the second is minted by the instance and appears in no log the outer process writes", name, got)
			continue
		}
		if got[0] != "outer-"+name {
			t.Errorf("%s = %q, want the outer chain's value, which is the one it logged", name, got[0])
		}
	}
}

type receivedBody struct {
	contentLength    int64
	transferEncoding []string
	body             string
}

func bodyEchoBridge(t *testing.T, got *receivedBody) *httptest.Server {
	t.Helper()
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		raw, _ := io.ReadAll(r.Body)
		*got = receivedBody{contentLength: r.ContentLength, transferEncoding: r.TransferEncoding, body: string(raw)}
	}))
	t.Cleanup(srv.Close)
	return srv
}

func TestHTTP_ForwardsABodyWithItsLength(t *testing.T) {
	var got receivedBody
	srv := bodyEchoBridge(t, &got)
	const body = `{"pattern":"api"}`

	req := httptest.NewRequest(http.MethodDelete, "/network/route", strings.NewReader(body))
	HTTP(httptest.NewRecorder(), req, srv.URL+"/network/route")

	if got.contentLength != int64(len(body)) || got.body != body || len(got.transferEncoding) != 0 {
		t.Fatalf("instance received length %d, encoding %v, body %q; want length %d, no chunking, %q", got.contentLength, got.transferEncoding, got.body, len(body), body)
	}
}

func TestHTTP_ForwardsAnEmptyBodyUnchunked(t *testing.T) {
	var got receivedBody
	srv := bodyEchoBridge(t, &got)

	req := httptest.NewRequest(http.MethodPost, "/close", strings.NewReader(""))
	HTTP(httptest.NewRecorder(), req, srv.URL+"/close")

	if got.contentLength != 0 || len(got.transferEncoding) != 0 || got.body != "" {
		t.Fatalf("instance received length %d, encoding %v, body %q; want an empty unchunked request", got.contentLength, got.transferEncoding, got.body)
	}
}