|
| 1 | +package http_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/pem" |
| 6 | + "io" |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + "net/http/httptest" |
| 10 | + "net/url" |
| 11 | + "os" |
| 12 | + "path/filepath" |
| 13 | + "testing" |
| 14 | + "time" |
| 15 | + |
| 16 | + "github.com/stretchr/testify/require" |
| 17 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 18 | + |
| 19 | + httputil "github.com/operator-framework/operator-controller/internal/shared/util/http" |
| 20 | +) |
| 21 | + |
| 22 | +// startRecordingProxy starts a plain-HTTP CONNECT proxy that tunnels HTTPS |
| 23 | +// connections and records the target host of each CONNECT request. |
| 24 | +func startRecordingProxy(proxied chan<- string) *httptest.Server { |
| 25 | + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 26 | + if r.Method != http.MethodConnect { |
| 27 | + http.Error(w, "only CONNECT supported", http.StatusMethodNotAllowed) |
| 28 | + return |
| 29 | + } |
| 30 | + // Non-blocking: if there are unexpected extra CONNECT requests (retries, |
| 31 | + // parallel connections) we record the first one and drop the rest rather |
| 32 | + // than blocking the proxy handler goroutine. |
| 33 | + select { |
| 34 | + case proxied <- r.Host: |
| 35 | + default: |
| 36 | + } |
| 37 | + |
| 38 | + dst, err := net.Dial("tcp", r.Host) |
| 39 | + if err != nil { |
| 40 | + http.Error(w, err.Error(), http.StatusBadGateway) |
| 41 | + return |
| 42 | + } |
| 43 | + defer dst.Close() |
| 44 | + |
| 45 | + hj, ok := w.(http.Hijacker) |
| 46 | + if !ok { |
| 47 | + http.Error(w, "hijacking not supported", http.StatusInternalServerError) |
| 48 | + return |
| 49 | + } |
| 50 | + conn, _, err := hj.Hijack() |
| 51 | + if err != nil { |
| 52 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 53 | + return |
| 54 | + } |
| 55 | + defer conn.Close() |
| 56 | + |
| 57 | + if _, err = conn.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n")); err != nil { |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + done := make(chan struct{}, 2) |
| 62 | + tunnel := func(dst, src net.Conn) { |
| 63 | + defer func() { done <- struct{}{} }() |
| 64 | + _, _ = io.Copy(dst, src) |
| 65 | + } |
| 66 | + go tunnel(dst, conn) |
| 67 | + go tunnel(conn, dst) |
| 68 | + <-done |
| 69 | + })) |
| 70 | +} |
| 71 | + |
| 72 | +// certPoolWatcherForTLSServer creates a CertPoolWatcher that trusts the given |
| 73 | +// TLS test server's certificate. |
| 74 | +func certPoolWatcherForTLSServer(t *testing.T, server *httptest.Server) *httputil.CertPoolWatcher { |
| 75 | + t.Helper() |
| 76 | + |
| 77 | + dir := t.TempDir() |
| 78 | + certPath := filepath.Join(dir, "server.pem") |
| 79 | + |
| 80 | + certDER := server.TLS.Certificates[0].Certificate[0] |
| 81 | + f, err := os.Create(certPath) |
| 82 | + require.NoError(t, err) |
| 83 | + require.NoError(t, pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})) |
| 84 | + require.NoError(t, f.Close()) |
| 85 | + |
| 86 | + cpw, err := httputil.NewCertPoolWatcher(dir, log.FromContext(context.Background())) |
| 87 | + require.NoError(t, err) |
| 88 | + require.NotNil(t, cpw) |
| 89 | + t.Cleanup(cpw.Done) |
| 90 | + require.NoError(t, cpw.Start(context.Background())) |
| 91 | + return cpw |
| 92 | +} |
| 93 | + |
| 94 | +// TestBuildHTTPClientTransportUsesProxyFromEnvironment verifies that the |
| 95 | +// transport returned by BuildHTTPClient has Proxy set to http.ProxyFromEnvironment |
| 96 | +// so that HTTPS_PROXY and NO_PROXY env vars are honoured at runtime. |
| 97 | +func TestBuildHTTPClientTransportUsesProxyFromEnvironment(t *testing.T) { |
| 98 | + // Use system certs (empty dir) — we only need a valid CertPoolWatcher. |
| 99 | + cpw, err := httputil.NewCertPoolWatcher("", log.FromContext(context.Background())) |
| 100 | + require.NoError(t, err) |
| 101 | + t.Cleanup(cpw.Done) |
| 102 | + require.NoError(t, cpw.Start(context.Background())) |
| 103 | + |
| 104 | + client, err := httputil.BuildHTTPClient(cpw) |
| 105 | + require.NoError(t, err) |
| 106 | + |
| 107 | + transport, ok := client.Transport.(*http.Transport) |
| 108 | + require.True(t, ok) |
| 109 | + require.NotNil(t, transport.Proxy, |
| 110 | + "BuildHTTPClient must set transport.Proxy so that HTTPS_PROXY env vars are respected; "+ |
| 111 | + "a nil Proxy field means no proxy regardless of environment") |
| 112 | +} |
| 113 | + |
| 114 | +// TestBuildHTTPClientProxyTunnelsConnections verifies end-to-end that the |
| 115 | +// HTTP client produced by BuildHTTPClient correctly tunnels HTTPS connections |
| 116 | +// through an HTTP CONNECT proxy. |
| 117 | +// |
| 118 | +// The test overrides transport.Proxy with http.ProxyURL rather than relying on |
| 119 | +// HTTPS_PROXY: httptest servers bind to 127.0.0.1, which http.ProxyFromEnvironment |
| 120 | +// silently excludes from proxying, and env-var changes within the same process |
| 121 | +// are unreliable due to sync.Once caching. Using http.ProxyURL directly exercises |
| 122 | +// the same tunnelling code path that HTTPS_PROXY triggers in production. |
| 123 | +func TestBuildHTTPClientProxyTunnelsConnections(t *testing.T) { |
| 124 | + targetServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 125 | + w.WriteHeader(http.StatusOK) |
| 126 | + })) |
| 127 | + defer targetServer.Close() |
| 128 | + |
| 129 | + proxied := make(chan string, 1) |
| 130 | + proxyServer := startRecordingProxy(proxied) |
| 131 | + defer proxyServer.Close() |
| 132 | + |
| 133 | + proxyURL, err := url.Parse(proxyServer.URL) |
| 134 | + require.NoError(t, err) |
| 135 | + |
| 136 | + cpw := certPoolWatcherForTLSServer(t, targetServer) |
| 137 | + client, err := httputil.BuildHTTPClient(cpw) |
| 138 | + require.NoError(t, err) |
| 139 | + |
| 140 | + // Point the transport directly at our test proxy, bypassing the loopback |
| 141 | + // exclusion and env-var caching of http.ProxyFromEnvironment. |
| 142 | + transport, ok := client.Transport.(*http.Transport) |
| 143 | + require.True(t, ok) |
| 144 | + transport.Proxy = http.ProxyURL(proxyURL) |
| 145 | + |
| 146 | + resp, err := client.Get(targetServer.URL) |
| 147 | + require.NoError(t, err) |
| 148 | + resp.Body.Close() |
| 149 | + |
| 150 | + select { |
| 151 | + case host := <-proxied: |
| 152 | + require.Equal(t, targetServer.Listener.Addr().String(), host, |
| 153 | + "proxy must have received a CONNECT request for the target server address") |
| 154 | + case <-time.After(5 * time.Second): |
| 155 | + t.Fatal("HTTPS connection to target server did not go through the proxy") |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +// TestBuildHTTPClientProxyBlocksWhenRejected verifies that when the proxy |
| 160 | +// rejects the CONNECT tunnel, the client request fails rather than silently |
| 161 | +// falling back to a direct connection. |
| 162 | +func TestBuildHTTPClientProxyBlocksWhenRejected(t *testing.T) { |
| 163 | + targetServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 164 | + w.WriteHeader(http.StatusOK) |
| 165 | + })) |
| 166 | + defer targetServer.Close() |
| 167 | + |
| 168 | + // A proxy that returns 403 Forbidden for every CONNECT request. |
| 169 | + rejectingProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 170 | + if r.Method == http.MethodConnect { |
| 171 | + http.Error(w, "proxy access denied", http.StatusForbidden) |
| 172 | + return |
| 173 | + } |
| 174 | + http.Error(w, "only CONNECT supported", http.StatusMethodNotAllowed) |
| 175 | + })) |
| 176 | + defer rejectingProxy.Close() |
| 177 | + |
| 178 | + proxyURL, err := url.Parse(rejectingProxy.URL) |
| 179 | + require.NoError(t, err) |
| 180 | + |
| 181 | + cpw := certPoolWatcherForTLSServer(t, targetServer) |
| 182 | + client, err := httputil.BuildHTTPClient(cpw) |
| 183 | + require.NoError(t, err) |
| 184 | + |
| 185 | + transport, ok := client.Transport.(*http.Transport) |
| 186 | + require.True(t, ok) |
| 187 | + transport.Proxy = http.ProxyURL(proxyURL) |
| 188 | + |
| 189 | + resp, err := client.Get(targetServer.URL) |
| 190 | + if resp != nil { |
| 191 | + resp.Body.Close() |
| 192 | + } |
| 193 | + require.Error(t, err, "request should fail when the proxy rejects the CONNECT tunnel") |
| 194 | +} |
0 commit comments