| 1 | package hostproxy |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "net" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "os" |
| 13 | "strings" |
| 14 | "sync/atomic" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "golang.org/x/net/http/httpproxy" |
| 19 | ) |
| 20 | |
| 21 | func TestHTTPSDownloadUsesHostProxyAndRedirects(t *testing.T) { |
| 22 | var connects atomic.Int32 |
| 23 | origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 24 | if r.URL.Path == "/first" { |
| 25 | http.Redirect(w, r, "/image", http.StatusFound) |
| 26 | return |
| 27 | } |
| 28 | io.WriteString(w, "image bytes") |
| 29 | })) |
| 30 | defer origin.Close() |
| 31 | proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 32 | if r.Method != "CONNECT" || r.Host != "image.invalid:443" { |
| 33 | t.Errorf("unexpected proxy request: %s %s", r.Method, r.Host) |
| 34 | http.Error(w, "bad target", 400) |
| 35 | return |
| 36 | } |
| 37 | connects.Add(1) |
| 38 | upstream, err := net.Dial("tcp", strings.TrimPrefix(origin.URL, "https://")) |
| 39 | if err != nil { |
| 40 | t.Error(err) |
| 41 | return |
| 42 | } |
| 43 | defer upstream.Close() |
| 44 | downstream, buffer, err := w.(http.Hijacker).Hijack() |
| 45 | if err != nil { |
| 46 | t.Error(err) |
| 47 | return |
| 48 | } |
| 49 | defer downstream.Close() |
| 50 | buffer.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n") |
| 51 | buffer.Flush() |
| 52 | go io.Copy(upstream, buffer) |
| 53 | io.Copy(downstream, upstream) |
| 54 | })) |
| 55 | defer proxy.Close() |
| 56 | proxyURL, _ := url.Parse(proxy.URL) |
| 57 | tr := transport(&httpproxy.Config{}, func(*http.Request) (*url.URL, error) { return proxyURL, nil }) |
| 58 | tr.TLSClientConfig = origin.Client().Transport.(*http.Transport).TLSClientConfig.Clone() |
| 59 | |
| 60 | |
| 61 | tr.TLSClientConfig.ServerName = "example.com" |
| 62 | defer tr.CloseIdleConnections() |
| 63 | client := &http.Client{Transport: tr, Timeout: 5 * time.Second} |
| 64 | resp, err := client.Get("https://image.invalid/first") |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | defer resp.Body.Close() |
| 69 | body, _ := io.ReadAll(resp.Body) |
| 70 | if string(body) != "image bytes" || connects.Load() == 0 { |
| 71 | t.Fatalf("body=%q proxy CONNECTs=%d", body, connects.Load()) |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | func TestHostProxyFailureNeverFallsBackToOrigin(t *testing.T) { |
| 76 | var direct atomic.Int32 |
| 77 | origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { direct.Add(1) })) |
| 78 | defer origin.Close() |
| 79 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 80 | if err != nil { |
| 81 | t.Fatal(err) |
| 82 | } |
| 83 | dead, _ := url.Parse("http://" + listener.Addr().String()) |
| 84 | listener.Close() |
| 85 | for _, resolve := range []func(*http.Request) (*url.URL, error){ |
| 86 | func(*http.Request) (*url.URL, error) { return dead, nil }, |
| 87 | func(*http.Request) (*url.URL, error) { return nil, errors.New("PAC failed") }, |
| 88 | } { |
| 89 | tr := transport(&httpproxy.Config{}, resolve) |
| 90 | _, err := (&http.Client{Transport: tr, Timeout: time.Second}).Get(origin.URL) |
| 91 | tr.CloseIdleConnections() |
| 92 | if err == nil { |
| 93 | t.Fatal("proxy failure accepted") |
| 94 | } |
| 95 | } |
| 96 | if direct.Load() != 0 { |
| 97 | t.Fatal("origin contacted after proxy failure") |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | func TestEnvironmentOverridesAndBypass(t *testing.T) { |
| 102 | for _, test := range []struct{ address, want string }{{"https://official.invalid/image", "http://127.0.0.1:7890"}, {"https://skip.invalid/image", ""}} { |
| 103 | tr := transport(&httpproxy.Config{HTTPSProxy: "http://127.0.0.1:7890", NoProxy: "skip.invalid"}, func(*http.Request) (*url.URL, error) { t.Fatal("system proxy used over explicit env"); return nil, nil }) |
| 104 | req, _ := http.NewRequest("GET", test.address, nil) |
| 105 | got, err := tr.Proxy(req) |
| 106 | if err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | value := "" |
| 110 | if got != nil { |
| 111 | value = got.String() |
| 112 | } |
| 113 | if value != test.want { |
| 114 | t.Fatalf("got %q want %q", value, test.want) |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | func TestHTTPOnlyEnvironmentKeepsHTTPSSystemProxy(t *testing.T) { |
| 120 | want, _ := url.Parse("http://127.0.0.1:7896") |
| 121 | tr := transport(&httpproxy.Config{HTTPProxy: "http://127.0.0.1:7890"}, func(*http.Request) (*url.URL, error) { return want, nil }) |
| 122 | req, _ := http.NewRequest("GET", "https://official.invalid/image", nil) |
| 123 | got, err := tr.Proxy(req) |
| 124 | if err != nil || got == nil || got.String() != want.String() { |
| 125 | t.Fatalf("proxy=%v err=%v", got, err) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func TestHostDownloadSubprocessKeepsCapturedProxyAfterGuestSanitization(t *testing.T) { |
| 130 | environment.Lock() |
| 131 | previous := environment.config |
| 132 | environment.config = nil |
| 133 | environment.Unlock() |
| 134 | t.Cleanup(func() { environment.Lock(); environment.config = previous; environment.Unlock() }) |
| 135 | t.Setenv("HTTPS_PROXY", "http://127.0.0.1:7896") |
| 136 | t.Setenv("HTTP_PROXY", "http://127.0.0.1:7896") |
| 137 | t.Setenv("NO_PROXY", "skip.invalid") |
| 138 | t.Setenv("no_proxy", "skip.invalid") |
| 139 | t.Setenv("https_proxy", "") |
| 140 | t.Setenv("http_proxy", "") |
| 141 | CaptureEnvironment() |
| 142 | t.Setenv("HTTPS_PROXY", "") |
| 143 | t.Setenv("HTTP_PROXY", "") |
| 144 | t.Setenv("NO_PROXY", "") |
| 145 | t.Setenv("no_proxy", "") |
| 146 | got := strings.Join(DownloadEnvironment(), "\n") |
| 147 | if !strings.Contains(got, "HTTPS_PROXY=http://127.0.0.1:7896") || !strings.Contains(got, "NO_PROXY=skip.invalid") { |
| 148 | t.Fatalf("host subprocess lost captured proxy settings: %s", got) |
| 149 | } |
| 150 | if os.Getenv("HTTPS_PROXY") != "" { |
| 151 | t.Fatal("host settings were restored into the guest process environment") |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | |
| 156 | func TestLiveSystemProxyDownload(t *testing.T) { |
| 157 | if testing.Short() { |
| 158 | t.Skip("live check") |
| 159 | } |
| 160 | |
| 161 | if os.Getenv("CAGE_TEST_HOST_PROXY_LIVE") == "" { |
| 162 | t.Skip("set CAGE_TEST_HOST_PROXY_LIVE=1") |
| 163 | } |
| 164 | for _, name := range []string{"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy"} { |
| 165 | t.Setenv(name, "") |
| 166 | } |
| 167 | tr := NewTransport() |
| 168 | defer tr.CloseIdleConnections() |
| 169 | req, _ := http.NewRequestWithContext(context.Background(), "GET", "https://cloud.debian.org/images/cloud/bookworm/latest/SHA512SUMS", nil) |
| 170 | proxy, err := tr.Proxy(req) |
| 171 | if err != nil || proxy == nil { |
| 172 | t.Fatalf("system proxy=%v err=%v", proxy, err) |
| 173 | } |
| 174 | var peer string |
| 175 | dial := tr.DialContext |
| 176 | tr.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) { |
| 177 | peer = address |
| 178 | return dial(ctx, network, address) |
| 179 | } |
| 180 | resp, err := (&http.Client{Transport: tr, Timeout: 30 * time.Second}).Do(req) |
| 181 | if err != nil { |
| 182 | t.Fatal(err) |
| 183 | } |
| 184 | defer resp.Body.Close() |
| 185 | line, err := bufio.NewReader(resp.Body).ReadString('\n') |
| 186 | if err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | if peer != proxy.Host || resp.StatusCode != 200 || len(line) < 128 { |
| 190 | t.Fatalf("peer=%s proxy=%s status=%d bytes=%d", peer, proxy.Host, resp.StatusCode, len(line)) |
| 191 | } |
| 192 | t.Logf("system proxy %s, connected peer %s, official Debian checksum HTTP %d (%d-byte first line)", proxy.Redacted(), peer, resp.StatusCode, len(line)) |
| 193 | if image := os.Getenv("CAGE_TEST_HOST_IMAGE_URL"); image != "" { |
| 194 | req, _ := http.NewRequest("GET", image, nil) |
| 195 | req.Header.Set("Range", "bytes=0-65535") |
| 196 | resp, err := (&http.Client{Transport: tr, Timeout: 30 * time.Second}).Do(req) |
| 197 | if err != nil { |
| 198 | t.Fatal(err) |
| 199 | } |
| 200 | defer resp.Body.Close() |
| 201 | count, err := io.Copy(io.Discard, io.LimitReader(resp.Body, 65537)) |
| 202 | if err != nil || resp.StatusCode != 206 || count != 65536 || peer != proxy.Host { |
| 203 | t.Fatalf("image peer=%s status=%d bytes=%d err=%v", peer, resp.StatusCode, count, err) |
| 204 | } |
| 205 | t.Logf("official system image HTTP %d, received %d bytes through %s", resp.StatusCode, count, peer) |
| 206 | } |
| 207 | } |