package main import ( "bufio" "bytes" "compress/gzip" "crypto/sha1" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/pem" "fmt" "io" "net" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strconv" "strings" "sync/atomic" "testing" "time" "github.com/andybalholm/brotli" "ublproxy/internal/blocklist" "ublproxy/internal/ca" "ublproxy/internal/store" ) // testEnv holds everything needed to run a proxy e2e test. type testEnv struct { proxyURL string httpURL string httpsURL string caPool *x509.CertPool upstreamPool *x509.CertPool handler *proxyHandler } // startTestEnv spins up an upstream HTTP server, an upstream HTTPS server, and // the proxy itself. The CA is generated in-memory — no disk I/O. // Pass nil for rules to create a proxy without blocking. func startTestEnv(t *testing.T, upstreamHandler http.Handler, rules *blocklist.RuleSet) *testEnv { t.Helper() // Upstream servers httpServer := httptest.NewServer(upstreamHandler) httpsServer := httptest.NewTLSServer(upstreamHandler) // In-memory CA caCert, caKey, err := ca.Generate() if err != nil { t.Fatalf("ca.Generate: %v", err) } certs := ca.NewCache(caCert, caKey) caCertPEM := ca.EncodeCertPEM(caCert) handler := newProxyHandler(certs, caCertPEM) if rules != nil { handler.baselineRules.Store(rules) } // Trust the test HTTPS server's certificate so the proxy can validate // upstream TLS connections (proxy validates upstream certs in production) upstreamCAPool := x509.NewCertPool() upstreamCAPool.AddCert(httpsServer.Certificate()) handler.transport.TLSClientConfig = &tls.Config{ RootCAs: upstreamCAPool, } // The proxy needs a real http.Server (not httptest) so that Hijack works // on the ResponseWriter. httptest.NewServer wraps net/http.Server, which // does support Hijack, so this is fine. proxyServer := httptest.NewServer(handler) // Build a CertPool that trusts our test CA so the HTTP client validates // the MITM certificates the proxy presents. caPool := x509.NewCertPool() caPool.AddCert(caCert) t.Cleanup(func() { proxyServer.Close() httpServer.Close() httpsServer.Close() }) return &testEnv{ proxyURL: proxyServer.URL, httpURL: httpServer.URL, httpsURL: httpsServer.URL, caPool: caPool, upstreamPool: upstreamCAPool, handler: handler, } } // httpsHost returns the host:port of the HTTPS upstream server. func (e *testEnv) httpsHost() string { u, _ := url.Parse(e.httpsURL) return u.Host } // httpClient returns an *http.Client configured to route through the proxy. // For HTTPS requests, it trusts the test CA (MITM certs). func (e *testEnv) httpClient(t *testing.T) *http.Client { t.Helper() proxyURL, err := url.Parse(e.proxyURL) if err != nil { t.Fatalf("parse proxy URL: %v", err) } return &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyURL(proxyURL), TLSClientConfig: &tls.Config{ RootCAs: e.caPool, }, }, } } // passthroughClient returns an *http.Client configured to route through the // proxy but trusting the upstream server's TLS cert (not the proxy CA). // Used for testing passthrough tunnels where no MITM occurs. func (e *testEnv) passthroughClient(t *testing.T) *http.Client { t.Helper() proxyURL, err := url.Parse(e.proxyURL) if err != nil { t.Fatalf("parse proxy URL: %v", err) } return &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyURL(proxyURL), TLSClientConfig: &tls.Config{ RootCAs: e.upstreamPool, }, }, } } func TestHTTPProxy(t *testing.T) { env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("hello from upstream")) }), nil) client := env.httpClient(t) resp, err := client.Get(env.httpURL + "/test") if err != nil { t.Fatalf("GET: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK) } body, _ := io.ReadAll(resp.Body) if string(body) != "hello from upstream" { t.Errorf("body = %q, want %q", body, "hello from upstream") } } func TestHTTPProxyHeaders(t *testing.T) { var receivedHeaders http.Header env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { receivedHeaders = r.Header.Clone() w.Header().Set("X-Upstream-Header", "present") w.WriteHeader(http.StatusOK) }), nil) client := env.httpClient(t) req, err := http.NewRequest("GET", env.httpURL+"/headers", nil) if err != nil { t.Fatalf("new request: %v", err) } req.Header.Set("X-Custom-Header", "test-value") req.Header.Set("Connection", "keep-alive") resp, err := client.Do(req) if err != nil { t.Fatalf("GET: %v", err) } defer resp.Body.Close() // Custom header should be forwarded to upstream if got := receivedHeaders.Get("X-Custom-Header"); got != "test-value" { t.Errorf("upstream X-Custom-Header = %q, want %q", got, "test-value") } // Hop-by-hop headers should be stripped before forwarding if got := receivedHeaders.Get("Connection"); got != "" { t.Errorf("upstream Connection header = %q, want it stripped", got) } // Response headers from upstream should be forwarded to client if got := resp.Header.Get("X-Upstream-Header"); got != "present" { t.Errorf("response X-Upstream-Header = %q, want %q", got, "present") } } func TestHTTPSProxy(t *testing.T) { env := startTestEnv(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte("hello from tls upstream")) }), nil) client := env.httpClient(t) resp, err := client.Get(env.httpsURL + "/secure") if err != nil { t.Fatalf("GET: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusOK) } body, _ := io.ReadAll(resp.Body) if string(body) != "hello from tls upstream" { t.Errorf("body = %q, want %q", body, "hello from tls upstream") } } func TestHTTPSHTMLRewriting(t *testing.T) { rs := blocklist.NewRuleSet() rs.AddLine("||ads.tracker.com^") rs.AddLine("##.ad-banner") upstream := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusOK) w.Write([]byte(`
` + `` + `` + `` + `Content
` + ``)) }) env := startTestEnv(t, upstream, rs) client := env.httpClient(t) resp, err := client.Get(env.httpsURL + "/page.html") if err != nil { t.Fatalf("GET: %v", err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) bodyStr := string(body) if !strings.Contains(bodyStr, "