Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 0 additions & 21 deletions fetch/fetcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,27 +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")
}
want := reflect.ValueOf(http.ProxyFromEnvironment).Pointer()
got := reflect.ValueOf(transport.Proxy).Pointer()
if got != want {
t.Errorf("Transport.Proxy 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 {
Expand Down
65 changes: 63 additions & 2 deletions fetch/transport_std.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net"
"net/http"
"net/url"
"time"

"github.com/rs/dnscache"
Expand All @@ -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{})
Expand All @@ -40,14 +46,17 @@ 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,
}
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 {
Expand All @@ -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
}
Expand All @@ -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
}
175 changes: 175 additions & 0 deletions fetch/transport_std_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
//go:build !tinygo

package fetch

import (
"context"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"sync/atomic"
"testing"

"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.
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)
}
}