File: proxy.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (264 lines) | stat: -rw-r--r-- 6,925 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package httpproxy

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"

	"github.com/crc-org/crc/v2/pkg/crc/logging"

	"github.com/asaskevich/govalidator"
	crcstrings "github.com/crc-org/crc/v2/pkg/strings"
	"github.com/pkg/errors"
	"golang.org/x/net/http/httpproxy"
)

var (
	DefaultProxy     ProxyConfig
	defaultNoProxies = []string{"127.0.0.1", "localhost"}
)

// ProxyConfig keeps the proxy configuration for the current environment
type ProxyConfig struct {
	HTTPProxy   string
	HTTPSProxy  string
	noProxy     []string
	ProxyCACert string
	ProxyCAFile string
	fromEnv     bool
}

func (p *ProxyConfig) String() string {
	var caCertForDisplay string
	if p.ProxyCAFile != "" {
		caCertForDisplay = fmt.Sprintf(", proxyCAFile: %s", p.ProxyCAFile)
	}
	return fmt.Sprintf("HTTP-PROXY: %s, HTTPS-PROXY: %s, NO-PROXY: %s%s", p.HTTPProxyForDisplay(),
		p.HTTPSProxyForDisplay(), p.GetNoProxyString(), caCertForDisplay)
}

func readProxyCAData(proxyCAFile string) (string, error) {
	if proxyCAFile == "" {
		return "", nil
	}
	proxyCACert, err := os.ReadFile(proxyCAFile)
	if err != nil {
		return "", err
	}
	return crcstrings.TrimTrailingEOL(string(proxyCACert)), nil
}

func NewProxyDefaults(httpProxy, httpsProxy, noProxy, proxyCAFile string) (*ProxyConfig, error) {
	proxyCAData, err := readProxyCAData(proxyCAFile)
	if err != nil {
		return nil, errors.Wrapf(err, "not able to read proxy CA data from %s", proxyCAFile)
	}

	DefaultProxy = ProxyConfig{
		HTTPProxy:   httpProxy,
		HTTPSProxy:  httpsProxy,
		ProxyCACert: proxyCAData,
		ProxyCAFile: proxyCAFile,
		fromEnv:     false,
	}
	envProxy := httpproxy.FromEnvironment()

	if DefaultProxy.HTTPProxy == "" && envProxy.HTTPProxy != "" {
		DefaultProxy.HTTPProxy = envProxy.HTTPProxy
		DefaultProxy.fromEnv = true
	}
	if DefaultProxy.HTTPSProxy == "" && envProxy.HTTPSProxy != "" {
		DefaultProxy.HTTPSProxy = envProxy.HTTPSProxy
		DefaultProxy.fromEnv = true
	}
	if noProxy == "" {
		noProxy = envProxy.NoProxy
	}
	DefaultProxy.setNoProxyString(noProxy)

	return NewProxyConfig()
}

// NewProxyConfig creates a proxy configuration with the specified parameters. If an empty string is passed
// the corresponding environment variable is checked.
func NewProxyConfig() (*ProxyConfig, error) {
	config := ProxyConfig{
		HTTPProxy:   DefaultProxy.HTTPProxy,
		HTTPSProxy:  DefaultProxy.HTTPSProxy,
		ProxyCACert: DefaultProxy.ProxyCACert,
		ProxyCAFile: DefaultProxy.ProxyCAFile,
		fromEnv:     DefaultProxy.fromEnv,
	}

	config.noProxy = defaultNoProxies
	if len(DefaultProxy.noProxy) != 0 {
		config.AddNoProxy(DefaultProxy.noProxy...)
	}

	err := ValidateProxyURL(config.HTTPProxy, false)
	if err != nil {
		if config.fromEnv {
			return nil, fmt.Errorf("Please check HTTP_PROXY env variable: %w", err)
		}
		return nil, err
	}

	err = ValidateProxyURL(config.HTTPSProxy, true)
	if err != nil {
		if config.fromEnv {
			return nil, fmt.Errorf("Please check HTTPS_PROXY env variable: %w", err)
		}
		return nil, err
	}

	return &config, nil
}

// HTTPProxy with hidden credentials
func (p *ProxyConfig) HTTPProxyForDisplay() string {
	httpProxy, _ := URIStringForDisplay(p.HTTPProxy)
	return httpProxy
}

// HTTPSProxy with hidden credentials
func (p *ProxyConfig) HTTPSProxyForDisplay() string {
	httpsProxy, _ := URIStringForDisplay(p.HTTPSProxy)
	return httpsProxy
}

// AddNoProxy appends the specified host to the list of no proxied hosts.
func (p *ProxyConfig) AddNoProxy(host ...string) {
	p.noProxy = append(p.noProxy, host...)
}

func (p *ProxyConfig) setNoProxyString(noProxies string) {
	if noProxies == "" {
		return
	}
	p.noProxy = strings.Split(noProxies, ",")
}

func (p *ProxyConfig) GetNoProxyString() string {
	return strings.Join(p.noProxy, ",")
}

// Sets the current config as environment variables in the current process.
func (p *ProxyConfig) ApplyToEnvironment() {
	if !p.IsEnabled() {
		return
	}

	if p.HTTPProxy != "" {
		os.Setenv("HTTP_PROXY", p.HTTPProxy)
		os.Setenv("http_proxy", p.HTTPProxy)
	}
	if p.HTTPSProxy != "" {
		os.Setenv("HTTPS_PROXY", p.HTTPSProxy)
		os.Setenv("https_proxy", p.HTTPSProxy)
	}
	if len(p.noProxy) != 0 {
		os.Setenv("NO_PROXY", p.GetNoProxyString())
		os.Setenv("no_proxy", p.GetNoProxyString())
	}
}

// This wraps https://pkg.go.dev/golang.org/x/net/http/httpproxy#Config.ProxyFunc
// This can be called on a nil *ProxyConfig
func (p *ProxyConfig) ProxyFunc() func(req *http.Request) (*url.URL, error) {
	var cfg httpproxy.Config

	if p != nil {
		cfg = httpproxy.Config{
			HTTPProxy:  p.HTTPProxy,
			HTTPSProxy: p.HTTPSProxy,
			NoProxy:    p.GetNoProxyString(),
		}
	}

	return func(req *http.Request) (*url.URL, error) { return cfg.ProxyFunc()(req.URL) }
}

// Enabled returns true if at least one proxy (HTTP or HTTPS) is configured. Returns false otherwise.
func (p *ProxyConfig) IsEnabled() bool {
	return p.HTTPProxy != "" || p.HTTPSProxy != ""
}

// ValidateProxyURL validates that the specified proxyURL is valid
func ValidateProxyURL(proxyURL string, isHTTPSProxy bool) error {
	if proxyURL == "" {
		return nil
	}

	// check URL scheme
	// http proxy URLs must start with http://
	// https proxy URLs must start with http://or https://
	httpScheme := strings.HasPrefix(proxyURL, "http://")
	httpsScheme := strings.HasPrefix(proxyURL, "https://")
	switch {
	case !isHTTPSProxy && !httpScheme:
		return fmt.Errorf("HTTP proxy URL '%s' is not valid: url should start with http://", proxyURL)
	case isHTTPSProxy && !httpScheme && !httpsScheme:
		return fmt.Errorf("HTTPS proxy URL '%s' is not valid: url should start with http:// or https://", proxyURL)
	}

	if !govalidator.IsURL(proxyURL) {
		return fmt.Errorf("Proxy URL '%s' is not valid", proxyURL)
	}
	return nil
}

func (p *ProxyConfig) tlsConfig() (*tls.Config, error) {
	if p.ProxyCACert == "" {
		return nil, nil
	}
	caCertPool, err := x509.SystemCertPool()
	if err != nil {
		logging.Warnf("Could not load system CA pool: %v", err)
		return nil, err
	}
	ok := caCertPool.AppendCertsFromPEM([]byte(p.ProxyCACert))
	if !ok {
		return nil, fmt.Errorf("Failed to append proxy CA to system CAs")
	}
	return &tls.Config{
		MinVersion: tls.VersionTLS12,
		RootCAs:    caCertPool,
	}, nil
}

func (p *ProxyConfig) HTTPTransport() http.RoundTripper {
	if !p.IsEnabled() {
		return http.DefaultTransport
	}

	defaultTransport, ok := http.DefaultTransport.(*http.Transport)
	if !ok {
		logging.Warnf("Unexpected default http transport type")
		return http.DefaultTransport
	}

	transport := defaultTransport.Clone()

	transport.Proxy = p.ProxyFunc()
	tlsConfig, err := p.tlsConfig()
	if err != nil {
		logging.Warnf("Failed to add proxy CA to crc http transport")
		return transport
	}
	transport.TLSClientConfig = tlsConfig

	return transport
}

func HTTPTransport() http.RoundTripper {
	proxyConfig, err := NewProxyConfig()
	if err != nil {
		return http.DefaultTransport
	}

	return proxyConfig.HTTPTransport()
}