From b7fbd09fe0a442a51d4b9c2f3483461ef76c6cd5 Mon Sep 17 00:00:00 2001 From: abhinavgautam01 Date: Sun, 6 Dec 2026 21:16:37 +0530 Subject: [PATCH 1/2] Check the destination of fetcher requests sent through a forward proxy --- fetch/fetcher_test.go | 5 +- fetch/transport_std.go | 65 ++++++++++++++- fetch/transport_std_test.go | 152 ++++++++++++++++++++++++++++++++++++ 3 files changed, 218 insertions(+), 4 deletions(-) create mode 100644 fetch/transport_std_test.go diff --git a/fetch/fetcher_test.go b/fetch/fetcher_test.go index a012e86..f404b26 100644 --- a/fetch/fetcher_test.go +++ b/fetch/fetcher_test.go @@ -391,10 +391,11 @@ func TestFetcherHonorsProxyEnvironment(t *testing.T) { if transport.Proxy == nil { t.Fatal("Transport.Proxy is nil; HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars would be ignored") } + // Transport.Proxy wraps proxyFromEnvironment with the destination check. want := reflect.ValueOf(http.ProxyFromEnvironment).Pointer() - got := reflect.ValueOf(transport.Proxy).Pointer() + got := reflect.ValueOf(proxyFromEnvironment).Pointer() if got != want { - t.Errorf("Transport.Proxy is not http.ProxyFromEnvironment") + t.Errorf("proxyFromEnvironment is not http.ProxyFromEnvironment") } if transport.ResponseHeaderTimeout == 0 { t.Error("Transport.ResponseHeaderTimeout is 0; hung upstreams will only fail at the overall client timeout") diff --git a/fetch/transport_std.go b/fetch/transport_std.go index 42b42c6..35875da 100644 --- a/fetch/transport_std.go +++ b/fetch/transport_std.go @@ -7,6 +7,7 @@ import ( "fmt" "net" "net/http" + "net/url" "time" "github.com/rs/dnscache" @@ -23,6 +24,11 @@ const ( tlsHandshakeTimeout = 10 * time.Second ) +// proxyFromEnvironment picks the forward proxy for a request. It is a +// variable so tests can route requests through a test proxy, since +// http.ProxyFromEnvironment reads the environment only once per process. +var proxyFromEnvironment = http.ProxyFromEnvironment + func (f *Fetcher) initHTTPClient() { resolver := &dnscache.Resolver{} stop := make(chan struct{}) @@ -40,6 +46,9 @@ func (f *Fetcher) initHTTPClient() { } }() + // f.ipChecker is set after the options are applied, so read it per call. + check := func(host string, ip net.IP) error { return f.ipChecker.Check(host, ip) } + dialer := &net.Dialer{ Timeout: dialTimeout, KeepAlive: dialKeepAlive, @@ -47,7 +56,7 @@ func (f *Fetcher) initHTTPClient() { f.client = &http.Client{ Timeout: httpClientTimeout, Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, + Proxy: guardProxy(proxyFromEnvironment, check, resolver.LookupHost), DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { host, port, err := net.SplitHostPort(addr) if err != nil { @@ -61,7 +70,7 @@ func (f *Fetcher) initHTTPClient() { var lastErr error for _, ip := range ips { if parsed := net.ParseIP(ip); parsed != nil { - if err := f.ipChecker.Check(host, parsed); err != nil { + if err := check(host, parsed); err != nil { lastErr = err continue } @@ -86,3 +95,55 @@ func (f *Fetcher) initHTTPClient() { }, } } + +// guardProxy wraps proxy so that a request sent through a forward proxy is +// held to the same address rules as a direct one. DialContext only sees the +// address it connects to, which for a proxied request is the forward proxy, +// so without this the forward proxy would connect to any destination. +// +// The destination is resolved here and every address must pass check. A +// host that cannot be resolved locally is passed on, since networks that +// route all traffic through a forward proxy often resolve public names only +// there. Requests that are not proxied are left to the DialContext check. +func guardProxy( + proxy func(*http.Request) (*url.URL, error), + check func(host string, ip net.IP) error, + lookup func(ctx context.Context, host string) ([]string, error), +) func(*http.Request) (*url.URL, error) { + if proxy == nil { + return nil + } + return func(req *http.Request) (*url.URL, error) { + proxyURL, err := proxy(req) + if err != nil || proxyURL == nil { + return proxyURL, err + } + if err := checkProxiedHost(req.Context(), req.URL.Hostname(), check, lookup); err != nil { + return nil, err + } + return proxyURL, nil + } +} + +func checkProxiedHost( + ctx context.Context, + host string, + check func(host string, ip net.IP) error, + lookup func(ctx context.Context, host string) ([]string, error), +) error { + if ip := net.ParseIP(host); ip != nil { + return check(host, ip) + } + addrs, err := lookup(ctx, host) + if err != nil { + return nil //nolint:nilerr // the forward proxy resolves names this host cannot + } + for _, addr := range addrs { + if ip := net.ParseIP(addr); ip != nil { + if err := check(host, ip); err != nil { + return err + } + } + } + return nil +} diff --git a/fetch/transport_std_test.go b/fetch/transport_std_test.go new file mode 100644 index 0000000..2d9d752 --- /dev/null +++ b/fetch/transport_std_test.go @@ -0,0 +1,152 @@ +//go:build !tinygo + +package fetch + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/git-pkgs/registries/safehttp" +) + +// routeFetcherThroughTestProxy starts a forward proxy that answers every +// request itself and makes fetchers created afterwards send their requests +// to it, as HTTP_PROXY would. +func routeFetcherThroughTestProxy(t *testing.T) *atomic.Int32 { + t.Helper() + var received atomic.Int32 + forward := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + received.Add(1) + _, _ = w.Write([]byte("via proxy")) + })) + t.Cleanup(forward.Close) + forwardURL, err := url.Parse(forward.URL) + if err != nil { + t.Fatal(err) + } + + old := proxyFromEnvironment + proxyFromEnvironment = http.ProxyURL(forwardURL) + t.Cleanup(func() { proxyFromEnvironment = old }) + return &received +} + +func TestFetchThroughForwardProxyChecksDestination(t *testing.T) { + received := routeFetcherThroughTestProxy(t) + f := NewFetcher(WithMaxRetries(0)) + defer func() { _ = f.Close() }() + + for _, tt := range []struct { + url string + blocked bool + }{ + {"http://169.254.169.254/latest/meta-data/", true}, + {"https://169.254.169.254/latest/meta-data/", true}, + {"http://[fe80::1]/", true}, + {"http://0.0.0.0/", true}, + {"http://203.0.113.10/artifact.tgz", false}, + } { + before := received.Load() + artifact, err := f.Fetch(context.Background(), tt.url) + reached := received.Load() > before + if tt.blocked { + if err == nil || reached { + t.Errorf("Fetch %s: err = %v, reached forward proxy = %v; want refused before the forward proxy", tt.url, err, reached) + } + if artifact != nil { + _ = artifact.Body.Close() + } + continue + } + if err != nil || !reached { + t.Errorf("Fetch %s: err = %v, reached forward proxy = %v; want it passed to the forward proxy", tt.url, err, reached) + continue + } + body, _ := io.ReadAll(artifact.Body) + _ = artifact.Body.Close() + if string(body) != "via proxy" { + t.Errorf("Fetch %s: body = %q, want the forward proxy's response", tt.url, body) + } + } +} + +func TestHeadThroughForwardProxyChecksDestination(t *testing.T) { + received := routeFetcherThroughTestProxy(t) + f := NewFetcher() + defer func() { _ = f.Close() }() + + _, _, err := f.Head(context.Background(), "http://169.254.169.254/") + if err == nil || received.Load() != 0 { + t.Errorf("Head: err = %v, forward proxy requests = %d; want refused before the forward proxy", err, received.Load()) + } +} + +func TestGuardProxyChecksResolvedDestination(t *testing.T) { + checker := safehttp.NewHostIPChecker(safehttp.Options{}) + hosts := map[string][]string{ + "metadata.example.test": {"169.254.169.254"}, + "mixed.example.test": {"203.0.113.10", "fe80::1"}, + "public.example.test": {"203.0.113.10", "2001:db8::10"}, + } + lookup := func(_ context.Context, host string) ([]string, error) { + if addrs, ok := hosts[host]; ok { + return addrs, nil + } + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} + } + forwardURL := &url.URL{Scheme: "http", Host: "proxy.example.test:3128"} + guarded := guardProxy(http.ProxyURL(forwardURL), checker.Check, lookup) + + for _, tt := range []struct { + url string + blocked string + }{ + {"http://metadata.example.test/", "link-local"}, + {"http://mixed.example.test/", "link-local"}, + {"http://169.254.169.254/", "link-local"}, + {"http://public.example.test/", ""}, + {"http://unresolvable.example.test/", ""}, + } { + req := httptest.NewRequest(http.MethodGet, tt.url, nil) + proxyURL, err := guarded(req) + if tt.blocked != "" { + if err == nil || !strings.Contains(err.Error(), tt.blocked) || proxyURL != nil { + t.Errorf("%s: proxy = %v, err = %v; want refused as %s", tt.url, proxyURL, err, tt.blocked) + } + continue + } + if err != nil || proxyURL == nil || *proxyURL != *forwardURL { + t.Errorf("%s: proxy = %v, err = %v; want %v", tt.url, proxyURL, err, forwardURL) + } + } +} + +func TestGuardProxyKeepsDirectRequests(t *testing.T) { + checker := safehttp.NewHostIPChecker(safehttp.Options{}) + lookup := func(context.Context, string) ([]string, error) { + t.Error("lookup called for a request that is not proxied") + return nil, nil + } + if guardProxy(nil, checker.Check, lookup) != nil { + t.Error("a transport without a proxy func got one") + } + + req := httptest.NewRequest(http.MethodGet, "http://169.254.169.254/", nil) + proxyErr := errors.New("bad proxy config") + failing := guardProxy(func(*http.Request) (*url.URL, error) { return nil, proxyErr }, checker.Check, lookup) + if _, err := failing(req); !errors.Is(err, proxyErr) { + t.Errorf("err = %v, want the proxy func's own error", err) + } + direct := guardProxy(func(*http.Request) (*url.URL, error) { return nil, nil }, checker.Check, lookup) + if proxyURL, err := direct(req); proxyURL != nil || err != nil { + t.Errorf("direct request: proxy = %v, err = %v; want nil, nil so DialContext checks it", proxyURL, err) + } +} From 0c6576022e1ed29427cc66feae3e9a1960508516 Mon Sep 17 00:00:00 2001 From: abhinavgautam01 Date: Sun, 6 Dec 2026 21:21:45 +0530 Subject: [PATCH 2/2] Move proxy environment test into the non-TinyGo test file --- fetch/fetcher_test.go | 22 ---------------------- fetch/transport_std_test.go | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/fetch/fetcher_test.go b/fetch/fetcher_test.go index f404b26..dbb6afd 100644 --- a/fetch/fetcher_test.go +++ b/fetch/fetcher_test.go @@ -380,28 +380,6 @@ func TestFetchDNSCaching(t *testing.T) { } } -func TestFetcherHonorsProxyEnvironment(t *testing.T) { - f := NewFetcher() - defer func() { _ = f.Close() }() - - transport, ok := f.client.Transport.(*http.Transport) - if !ok { - t.Fatalf("Transport = %T, want *http.Transport", f.client.Transport) - } - if transport.Proxy == nil { - t.Fatal("Transport.Proxy is nil; HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars would be ignored") - } - // Transport.Proxy wraps proxyFromEnvironment with the destination check. - want := reflect.ValueOf(http.ProxyFromEnvironment).Pointer() - got := reflect.ValueOf(proxyFromEnvironment).Pointer() - if got != want { - t.Errorf("proxyFromEnvironment is not http.ProxyFromEnvironment") - } - if transport.ResponseHeaderTimeout == 0 { - t.Error("Transport.ResponseHeaderTimeout is 0; hung upstreams will only fail at the overall client timeout") - } -} - func TestFetcherCloseStopsGoroutine(t *testing.T) { f := NewFetcher() if err := f.Close(); err != nil { diff --git a/fetch/transport_std_test.go b/fetch/transport_std_test.go index 2d9d752..f82aae2 100644 --- a/fetch/transport_std_test.go +++ b/fetch/transport_std_test.go @@ -10,6 +10,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "reflect" "strings" "sync/atomic" "testing" @@ -17,6 +18,28 @@ import ( "github.com/git-pkgs/registries/safehttp" ) +func TestFetcherHonorsProxyEnvironment(t *testing.T) { + f := NewFetcher() + defer func() { _ = f.Close() }() + + transport, ok := f.client.Transport.(*http.Transport) + if !ok { + t.Fatalf("Transport = %T, want *http.Transport", f.client.Transport) + } + if transport.Proxy == nil { + t.Fatal("Transport.Proxy is nil; HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars would be ignored") + } + // Transport.Proxy wraps proxyFromEnvironment with the destination check. + want := reflect.ValueOf(http.ProxyFromEnvironment).Pointer() + got := reflect.ValueOf(proxyFromEnvironment).Pointer() + if got != want { + t.Errorf("proxyFromEnvironment is not http.ProxyFromEnvironment") + } + if transport.ResponseHeaderTimeout == 0 { + t.Error("Transport.ResponseHeaderTimeout is 0; hung upstreams will only fail at the overall client timeout") + } +} + // routeFetcherThroughTestProxy starts a forward proxy that answers every // request itself and makes fetchers created afterwards send their requests // to it, as HTTP_PROXY would.