-
Notifications
You must be signed in to change notification settings - Fork 11
/
proxy.go
885 lines (696 loc) · 23.4 KB
/
proxy.go
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
// Copyright 2021 The forwarder Authors. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package proxy
import (
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"github.com/eapache/go-resiliency/retrier"
"github.com/elazarl/goproxy"
"github.com/elazarl/goproxy/ext/auth"
"github.com/saucelabs/customerror"
"github.com/saucelabs/forwarder/internal/credential"
"github.com/saucelabs/forwarder/internal/logger"
"github.com/saucelabs/forwarder/internal/pac"
"github.com/saucelabs/forwarder/internal/util"
"github.com/saucelabs/forwarder/internal/validation"
"github.com/saucelabs/randomness"
"github.com/saucelabs/sypl"
"github.com/saucelabs/sypl/fields"
"github.com/saucelabs/sypl/level"
"github.com/saucelabs/sypl/options"
)
const (
ConstantBackoff = 300
DNSTimeout = 1 * time.Minute
MaxRetry = 3
httpPort = 80
httpsPort = 443
proxyAuthHeader = "Proxy-Authorization"
authHeader = "Authorization"
)
// Possible ways to run Forwarder.
type Mode string
const (
Direct Mode = "DIRECT"
Upstream Mode = "Upstream"
PAC Mode = "PAC"
)
// Valid proxy schemes.
const (
HTTP = "http"
HTTPS = "https"
SOCKS5 = "socks5"
SOCKS = "socks"
QUIC = "quic"
)
// State helps the proxy to don't run the same state multiple times.
type State string
const (
// Initializing means that a new proxy has been instantiated, but has not
// yet finished setup.
Initializing State = "Initializing"
// Setup state means it's done setting it up, but not running yet.
Setup State = "Setup"
// Running means proxy is running.
Running State = "Running"
)
var (
ErrFailedToAllocatePort = customerror.New("No available port to use", customerror.WithStatusCode(http.StatusInternalServerError))
ErrFailedToDialToDNS = customerror.NewFailedToError("dial to DNS")
ErrFailedToStartProxy = customerror.NewFailedToError("start proxy")
ErrInvalidDNSURI = customerror.NewInvalidError("dns URI")
ErrInvalidLocalProxyURI = customerror.NewInvalidError("local proxy URI")
ErrInvalidOrParentOrPac = customerror.NewInvalidError("params. Can't set upstream proxy, and PAC at the same time")
ErrInvalidPACProxyURI = customerror.NewInvalidError("PAC proxy URI")
ErrInvalidPACURI = customerror.NewInvalidError("PAC URI")
ErrInvalidProxyParams = customerror.NewInvalidError("params")
ErrInvalidUpstreamProxyURI = customerror.NewInvalidError("upstream proxy URI")
ErrInvalidSiteCredentials = customerror.NewInvalidError("invalid site credentials")
)
// LoggingOptions defines logging options.
type LoggingOptions = logger.Options
// RetryPortOptions defines port's retry options.
type RetryPortOptions struct {
// MaxRange defines the max port number. Default value is `65535`.
MaxRange int
// MaxRetry defines how many times to retry, until fail.
MaxRetry int
}
// Default sets `RetryPortOptions` default values.
func (r *RetryPortOptions) Default() *RetryPortOptions {
if r == nil {
r = &RetryPortOptions{}
}
if r.MaxRange < 80 || r.MaxRange > 65535 {
r.MaxRange = 65535
}
if r.MaxRetry == 0 {
r.MaxRetry = 3
}
return r
}
// Options definition.
//
//nolint:maligned
type Options struct {
*LoggingOptions
*RetryPortOptions
// AutomaticallyRetryPort if `true`, and the specified port is in-use, will
// try to automatically allocate a free port.
AutomaticallyRetryPort bool
// DNSURIs are DNS URIs:
// - Known protocol: udp, tcp
// - Some hostname (x.io - min 4 chars), or IP
// - Port in a valid range: 53 - 65535.
// Example: udp://10.0.0.3:53
DNSURIs []string `json:"dns_uris" validate:"omitempty,dive,dnsURI"`
// ProxyLocalhost if `true`, requests to `localhost`/`127.0.0.1` will be
// forwarded to any upstream - if set.
ProxyLocalhost bool
// SiteCredentials contains URLs with the credentials, for example:
// - https://usr1:pwd1@foo.bar:4443
// - http://usr2:pwd2@bar.foo:8080
// - usr3:pwd3@bar.foo:8080
// Proxy will add basic auth headers for requests to these URLs.
SiteCredentials []string `json:"site_credentials" validate:"omitempty"`
}
// Default sets `Options` default values.
func (o *Options) Default() {
loggingOptions := &LoggingOptions{}
loggingOptions.Default()
o.LoggingOptions = loggingOptions
retryPortOptions := &RetryPortOptions{}
retryPortOptions.Default()
o.AutomaticallyRetryPort = false
o.ProxyLocalhost = false
o.RetryPortOptions = retryPortOptions
}
// Proxy definition. Proxy can be protected, or not. It can forward connections
// to an upstream proxy protected, or not. The upstream proxy can be
// automatically setup via PAC. PAC content can be retrieved from multiple
// sources, e.g.: a HTTP server, also, protected or not.
//
// Protection means basic auth protection.
type Proxy struct {
// LocalProxyURI is the local proxy URI:
// - Known schemes: http, https, socks, socks5, or quic
// - Some hostname (x.io - min 4 chars), or IP
// - Port in a valid range: 80 - 65535.
// Example: http://127.0.0.1:8080
LocalProxyURI string `json:"local_proxy_uri" validate:"required,proxyURI"`
// UpstreamProxyURI is the upstream proxy URI:
// - Known schemes: http, https, socks, socks5, or quic
// - Some hostname (x.io - min 4 chars), or IP
// - Port in a valid range: 80 - 65535.
// Example: http://u456:p456@127.0.0.1:8085
UpstreamProxyURI string `json:"upstream_proxy_uri" validate:"omitempty,proxyURI"`
// PACURI is the PAC URI:
// - Known schemes: http, https, socks, socks5, or quic
// - Some hostname (x.io - min 4 chars), or IP
// - Port in a valid range: 80 - 65535.
// Example: http://127.0.0.1:8087/data.pac
PACURI string `json:"pac_uri" validate:"omitempty,gte=6"`
// Mode the Proxy is running.
Mode Mode
// Current state of the proxy. Multiple calls to `Run`, if running, will do
// nothing.
State State
// Options to setup proxy.
*Options
mutex *sync.RWMutex
// Parsed local proxy URI.
parsedLocalProxyURI *url.URL
// Parsed upstream proxy URI.
parsedUpstreamProxyURI *url.URL
// PAC parser implementation.
pacParser *pac.Parser
// Credentials for proxies specified in PAC content.
pacProxiesCredentials []string
// credentials for passing basic authentication to requests
siteCredentialsMatcher siteCredentialsMatcher
// Underlying proxy implementation.
proxy *goproxy.ProxyHttpServer
}
func basicAuth(userpwd string) string {
return base64.StdEncoding.EncodeToString([]byte(userpwd))
}
// Sets the `Proxy-Authorization` header based on `uri` user info.
func setProxyBasicAuthHeader(uri *url.URL, req *http.Request) {
req.Header.Set(
proxyAuthHeader,
fmt.Sprintf("Basic %s", basicAuth(uri.User.String())),
)
logger.Get().Debuglnf(
"%s header set with %s:*** for %s",
proxyAuthHeader,
uri.User.Username(),
req.URL.String(),
)
}
// Removes any upstream proxy settings.
//
//nolint:gosec
func resetUpstreamSettings(ctx *goproxy.ProxyCtx) {
ctx.Proxy.ConnectDial = nil
ctx.Proxy.Tr = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, Proxy: nil}
}
// Sets the default DNS.
//
//nolint:interfacer
func setupDNS(mutex *sync.RWMutex, dnsURIs []string) error {
mutex.Lock()
defer mutex.Unlock()
parsedDNSURIs := []*url.URL{}
for _, dnsURI := range dnsURIs {
parsedDNSURI, err := url.ParseRequestURI(dnsURI)
if err != nil {
return customerror.Wrap(ErrInvalidDNSURI, err)
}
parsedDNSURIs = append(parsedDNSURIs, parsedDNSURI)
}
net.DefaultResolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{Timeout: DNSTimeout}
var finalConn net.Conn
var finalError error
for i := 0; i < len(parsedDNSURIs); i++ {
parsedDNSURI := parsedDNSURIs[i]
c, err := d.DialContext(ctx, parsedDNSURI.Scheme, parsedDNSURI.Host)
finalConn = c
finalError = err
if err != nil {
errMsg := fmt.Sprintf("dial to DNS @ %s", parsedDNSURI.String())
logger.Get().Tracelnf(customerror.NewFailedToError(errMsg, customerror.WithError(err)).Error())
} else {
logger.Get().Tracelnf("Request resolved by DNS @ %s", parsedDNSURI)
break
}
}
if finalError != nil {
ErrAllDNSResolversFailed := customerror.New(
"All DNS resolvers failed",
customerror.WithStatusCode(http.StatusInternalServerError),
customerror.WithError(finalError),
)
logger.Get().Traceln(ErrAllDNSResolversFailed)
return finalConn, ErrAllDNSResolversFailed
}
return finalConn, nil
},
}
return nil
}
// Returns `true` if should NOT proxy connections to any upstream proxy.
func (p *Proxy) shouldNotProxyLocalhost(ctx *goproxy.ProxyCtx) bool {
if !p.ProxyLocalhost && util.IsLocalHost(ctx.Req) {
resetUpstreamSettings(ctx)
return true
}
return false
}
// setupUpstreamProxyConnection forwards connections to an upstream proxy.
func setupUpstreamProxyConnection(ctx *goproxy.ProxyCtx, uri *url.URL) {
ctx.Proxy.Tr.Proxy = http.ProxyURL(uri)
var connectReqHandler func(req *http.Request)
if uri.User.Username() != "" {
connectReqHandler = func(req *http.Request) {
logger.Get().Traceln("Setting basic auth header from connection handler to upstream proxy.")
setProxyBasicAuthHeader(uri, req)
}
}
ctx.Proxy.ConnectDial = ctx.Proxy.NewConnectDialToProxyWithHandler(uri.String(), connectReqHandler)
logger.Get().Tracelnf("Connection to the upstream proxy %s is set up", uri.Redacted())
}
// setupPACUpstreamProxyConnection dynamically forwards connections to an upstream
// proxy setup via PAC.
func setupPACUpstreamProxyConnection(p *Proxy, ctx *goproxy.ProxyCtx) error {
urlToFindProxyFor := ctx.Req.URL.String()
hostToFindProxyFor := ctx.Req.URL.Hostname()
logger.Get().Tracelnf("Finding proxy for %s", hostToFindProxyFor)
pacProxies, err := p.pacParser.Find(urlToFindProxyFor)
if err != nil {
return err
}
// Should only do something if there's any proxy
if len(pacProxies) > 0 {
// TODO: Should find the best proxy from a list of possible proxies?
pacProxy := pacProxies[0]
pacProxyURI := pacProxy.GetURI()
// Should only set up upstream if there's a proxy and not `DIRECT`.
if pacProxyURI != nil {
logger.Get().Debuglnf("Using proxy %s for %s", pacProxyURI.Redacted(), hostToFindProxyFor)
setupUpstreamProxyConnection(ctx, pacProxyURI)
return nil
}
}
logger.Get().Debugln("Using no proxy for", hostToFindProxyFor)
// Clear upstream proxy settings (if any) for this request.
resetUpstreamSettings(ctx)
return nil
}
// parseSiteCredentials takes a list of "user:pass@host:port" strings.
//
// A port of '0' means a wildcard port
// A host of '*' means a wildcard host
// A host:port of '*:0' will match everything
//
// They are converted to a map of:
// - "host:port": base64("user:pass").
// - "port": base64("user:pass")
// - "host": base64("user:pass")
// and a global wildcard string.
func parseSiteCredentials(creds []string) (map[string]string, map[string]string, map[string]string, string, error) {
hostportMap := make(map[string]string, len(creds))
hostMap := make(map[string]string, len(creds))
portMap := make(map[string]string, len(creds))
global := ""
for _, credentialText := range creds {
uri, err := util.NormalizeURI(credentialText)
if err != nil {
return nil, nil, nil, "", fmt.Errorf("%w: %s", ErrInvalidSiteCredentials, err)
}
// Get the base64 of the credentials
pass, found := uri.User.Password()
if !found {
return nil, nil, nil, "", fmt.Errorf("%w: password not found in %s", ErrInvalidSiteCredentials, credentialText)
}
basicAuth, err := credential.NewBasicAuth(uri.User.Username(), pass)
if err != nil {
return nil, nil, nil, "", err
}
encoded := basicAuth.ToBase64()
if uri.Hostname() == "*" && uri.Port() == "0" {
if global != "" {
return nil, nil, nil, "", fmt.Errorf("%w: multiple credentials for global wildcard", ErrInvalidSiteCredentials)
}
global = encoded
continue
}
if uri.Hostname() == "*" {
_, found = portMap[uri.Port()]
if found {
return nil, nil, nil, "", fmt.Errorf("%w: multiple credentials for wildcard host with port %s", ErrInvalidSiteCredentials, uri.Port())
}
portMap[uri.Port()] = encoded
continue
}
if uri.Port() == "0" {
_, found = hostMap[uri.Hostname()]
if found {
return nil, nil, nil, "", fmt.Errorf("%w: multiple credentials for wildcard port with host %s", ErrInvalidSiteCredentials, uri.Hostname())
}
hostMap[uri.Hostname()] = encoded
continue
}
// No wildcards, add the host:port directly
_, found = hostportMap[uri.Host]
if found {
return nil, nil, nil, "", fmt.Errorf("%w: multiple credentials for %s", ErrInvalidSiteCredentials, uri.Host)
}
hostportMap[uri.Host] = encoded
}
return hostportMap, hostMap, portMap, global, nil
}
// DRY on handler's code.
//
//nolint:exhaustive
func (p *Proxy) setupHandlers(ctx *goproxy.ProxyCtx) error {
if p.shouldNotProxyLocalhost(ctx) {
logger.Get().Tracelnf("Not proxifying request to localhost URL: %s", ctx.Req.URL.String())
return nil
}
switch p.Mode {
case Upstream:
setupUpstreamProxyConnection(ctx, p.parsedUpstreamProxyURI)
case PAC:
if err := setupPACUpstreamProxyConnection(p, ctx); err != nil {
return err
}
}
return nil
}
// setupBasicAuth protects proxy with basic auth.
func (p *Proxy) setupBasicAuth(uri *url.URL) error {
// Should be a valid credential.
// TODO: Use URI instead of credential.
c, err := credential.NewBasicAuthFromText(uri.User.String())
if err != nil {
return err
}
// TODO: Allows to set `realm`.
auth.ProxyBasic(p.proxy, "localhost", func(user, pwd string) bool {
ok := user == c.Username && pwd == c.Password
logger.Get().PrintlnfWithOptions(&options.Options{
Fields: fields.Fields{
"authorized": ok,
},
}, level.Trace, "Incoming request. This proxy (%s) is protected", p.parsedLocalProxyURI.Redacted())
return ok
})
logger.Get().Debuglnf("Basic auth setup for proxy @ %s", p.parsedLocalProxyURI.Redacted())
return nil
}
// Verifies if the port in `address` is in-use.
func (p *Proxy) isPortInUse(host string) bool {
ln, err := net.Listen("tcp", host)
if err != nil {
return true
}
if ln != nil {
ln.Close()
}
return false
}
// Finds available port.
func (p *Proxy) findAvailablePort(uri *url.URL) error {
portInt, err := strconv.Atoi(uri.Port())
if err != nil {
return err
}
possiblePorts := []int64{int64(portInt)}
r, err := randomness.New(portInt, p.Options.RetryPortOptions.MaxRange, MaxRetry, true)
if err != nil {
return err
}
// N times to retry option
randomPorts, err := r.GenerateMany(p.Options.RetryPortOptions.MaxRetry)
if err != nil {
return err
}
possiblePorts = append(possiblePorts, randomPorts...)
availablePorts := []int64{}
// Find some available port.
for _, port := range possiblePorts {
isPortInUse := p.isPortInUse(net.JoinHostPort(uri.Hostname(), fmt.Sprintf("%d", port)))
logger.Get().Tracelnf("Is %d available? %v", port, !isPortInUse)
if !isPortInUse {
availablePorts = append(availablePorts, port)
logger.Get().Tracelnf("Added %d to available ports", port)
}
}
// Any available port?
if len(availablePorts) < 1 {
return ErrFailedToAllocatePort
}
// Updates data struct.
uri.Host = net.JoinHostPort(uri.Hostname(), fmt.Sprintf("%d", availablePorts[0]))
p.parsedLocalProxyURI = uri
logger.Get().PrintlnfWithOptions(&options.Options{
Fields: fields.Fields{
"availablePorts": availablePorts,
},
}, level.Debug, "Updated URI with new available port: %s", uri.String())
return nil
}
// Run starts the proxy. it fails to start, it will exit with fatal. It's safe
// to call it multiple times - nothing will happen.
func (p *Proxy) Run() {
// Should not panic, but exit with proper error if method is called without
// Proxy is setup.
if p == nil {
logger.Get().Fatalln(ErrFailedToStartProxy, "Proxy isn't set up")
}
// Do nothing if already running.
p.mutex.RLock()
if p.State == Running {
logger.Get().Traceln("Proxy is already running")
return
}
p.mutex.RUnlock()
// TODO: Allows to pass an error channel.
if p.Options.AutomaticallyRetryPort && p.isPortInUse(p.parsedLocalProxyURI.Host) {
r := retrier.New(retrier.ConstantBackoff(
p.Options.RetryPortOptions.MaxRetry,
ConstantBackoff*time.Millisecond,
), nil)
err := r.Run(func() error {
return p.findAvailablePort(p.parsedLocalProxyURI)
})
if err != nil {
logger.Get().Fatalln(customerror.Wrap(ErrFailedToStartProxy, err))
}
}
logger.Get().Debuglnf("Listening on %s", p.parsedLocalProxyURI.Host)
// Updates state.
p.mutex.Lock()
p.State = Running
p.mutex.Unlock()
if err := http.ListenAndServe(p.parsedLocalProxyURI.Host, p.proxy); err != nil {
logger.Get().Fatalln(customerror.Wrap(ErrFailedToStartProxy, err))
}
}
func (p *Proxy) setupProxyHandlers() {
p.proxy.OnRequest().HandleConnectFunc(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
logger.Get().Debuglnf("%s %s -> %s", ctx.Req.Method, ctx.Req.RemoteAddr, ctx.Req.Host)
logger.Get().Debuglnf("%q", dumpHeaders(ctx.Req))
if err := p.setupHandlers(ctx); err != nil {
logger.Get().Errorlnf("Failed to setup handler (HTTPS) for request %s. %+v", ctx.Req.URL.Redacted(), err)
return goproxy.RejectConnect, host
}
return nil, host
})
p.proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
logger.Get().Debuglnf("%s %s -> %s %s %s", req.Method, req.RemoteAddr, req.URL.Scheme, req.Host, req.URL.Port())
logger.Get().Tracelnf("%q", dumpHeaders(ctx.Req))
if err := p.setupHandlers(ctx); err != nil {
logger.Get().Errorlnf("Failed to setup handler (HTTP) for request %s. %+v", ctx.Req.URL.Redacted(), err)
return nil, goproxy.NewResponse(
ctx.Req,
goproxy.ContentTypeText,
http.StatusInternalServerError,
err.Error(),
)
}
return ctx.Req, nil
})
if p.siteCredentialsMatcher.isSet() {
p.proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
p.maybeAddAuthHeader(req)
return ctx.Req, nil
})
}
p.proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if resp != nil {
logger.Get().Debuglnf("%s <- %s %v (%v bytes)",
resp.Request.RemoteAddr, resp.Request.Host, resp.Status, resp.ContentLength)
} else {
logger.Get().Tracelnf("%s <- %s response is empty", ctx.Req.Host, ctx.Req.RemoteAddr)
}
return resp
})
}
// maybeAddAuthHeader modifies the request and adds an authorization header if necessary.
func (p *Proxy) maybeAddAuthHeader(req *http.Request) {
hostport := req.Host
if req.URL.Port() == "" {
// When the destination URL doesn't contain an explicit port, Go http-parsed
// URL Port() returns an empty string.
switch req.URL.Scheme {
case "http":
hostport = fmt.Sprintf("%s:%d", req.Host, httpPort)
case "https":
hostport = fmt.Sprintf("%s:%d", req.Host, httpsPort)
default:
logger.Get().Warnlnf("Failed to determine port for %s.", req.URL.Redacted())
}
}
creds := p.siteCredentialsMatcher.match(hostport)
if creds != "" {
req.Header.Set(authHeader, fmt.Sprintf("Basic %s", creds))
}
}
//////
// Factory
//////
// New is the Proxy factory. Errors can be introspected, and provide contextual
// information.
func New(
localProxyURI string,
upstreamProxyURI string,
pacURI string, pacProxiesCredentials []string,
options *Options,
) (*Proxy, error) {
// Instantiate validator.
validation.Setup()
//////
// Proxy setup.
//////
finalOptions := &Options{}
finalOptions.Default()
if options == nil {
options = &Options{}
}
// Will not copy logger reference, so, storing a reference.
var externalLogger sypl.Sypl
if options.LoggingOptions.Logger != nil {
externalLogger = *options.LoggingOptions.Logger
}
if err := deepCopy(options, finalOptions); err != nil {
return nil, err
}
siteCredentials := options.SiteCredentials
siteCredentialsFromEnv := loadSiteCredentialsFromEnvVar("FORWARDER_SITE_CREDENTIALS")
if len(siteCredentials) == 0 && siteCredentialsFromEnv != nil {
siteCredentials = siteCredentialsFromEnv
}
// Parse site credential list into map of host:port -> base64 encoded credentials.
hostportMap, hostMap, portMap, global, err := parseSiteCredentials(siteCredentials)
if err != nil {
return nil, err
}
credsMatcher := siteCredentialsMatcher{
siteCredentials: hostportMap,
siteCredentialsHost: hostMap,
siteCredentialsPort: portMap,
siteCredentialsWildcard: global,
}
p := &Proxy{
LocalProxyURI: localProxyURI,
Mode: Direct,
Options: finalOptions,
PACURI: pacURI,
State: Initializing,
UpstreamProxyURI: upstreamProxyURI,
pacProxiesCredentials: pacProxiesCredentials,
mutex: &sync.RWMutex{},
siteCredentialsMatcher: credsMatcher,
}
if err := validation.Get().Struct(p); err != nil {
return nil, customerror.Wrap(ErrInvalidProxyParams, err)
}
// Should allow to set logger.
if options.LoggingOptions.Logger != nil {
finalOptions.LoggingOptions.Logger = &externalLogger
}
logger.Setup(finalOptions.LoggingOptions)
// Can't have upstream proxy configuration, and PAC at the same time.
if p.UpstreamProxyURI != "" && p.PACURI != "" {
return nil, ErrInvalidOrParentOrPac
}
//////
// Underlying proxy implementation setup.
//////
// Instantiate underlying proxy implementation. It can be abstracted in the
// future to allow easy swapping.
proxy := goproxy.NewProxyHttpServer()
if p.Options.LoggingOptions != nil && level.MustFromString(p.Options.LoggingOptions.Level) > level.Info {
proxyLogger := &logger.ProxyLogger{
Logger: logger.Get().New("goproxy"),
}
proxy.Logger = proxyLogger
proxy.Verbose = true
}
proxy.KeepDestinationHeaders = true
// This is required.
//
// See: https://maelvls.dev/go-ignores-proxy-localhost/
// See: https://github.com/golang/go/issues/28866
// See: https://github.com/elazarl/goproxy/issues/306
proxy.KeepHeader = true
p.proxy = proxy
//////
// DNS.
//////
if p.Options.DNSURIs != nil {
if err := setupDNS(p.mutex, p.Options.DNSURIs); err != nil {
return nil, err
}
}
//////
// Local proxy setup.
//////
parsedLocalProxyURI, err := url.ParseRequestURI(p.LocalProxyURI)
if err != nil {
return nil, customerror.Wrap(ErrInvalidLocalProxyURI, err)
}
err = loadCredentialFromEnvVar("FORWARDER_LOCALPROXY_AUTH", parsedLocalProxyURI)
if err != nil {
return nil, err
}
p.parsedLocalProxyURI = parsedLocalProxyURI
p.LocalProxyURI = parsedLocalProxyURI.String()
if p.UpstreamProxyURI != "" {
p.Mode = Upstream
parsedUpstreamProxyURI, err := url.ParseRequestURI(p.UpstreamProxyURI)
if err != nil {
return nil, customerror.Wrap(ErrInvalidUpstreamProxyURI, err)
}
err = loadCredentialFromEnvVar("FORWARDER_UPSTREAMPROXY_AUTH", parsedUpstreamProxyURI)
if err != nil {
return nil, err
}
p.parsedUpstreamProxyURI = parsedUpstreamProxyURI
p.UpstreamProxyURI = parsedUpstreamProxyURI.String()
}
if p.PACURI != "" {
p.Mode = PAC
// `uri` doesn't need to be validated, this is already done by `pac.New`.
// Also, there's no need to wrap `err`, pac is powered by `customerror`.
pacParser, err := pac.New(p.PACURI, p.pacProxiesCredentials...)
if err != nil {
return nil, err
}
p.pacParser = pacParser
}
// Setup the request and response handlers
p.setupProxyHandlers()
// Local proxy authentication.
if parsedLocalProxyURI.User.Username() != "" {
if err := p.setupBasicAuth(parsedLocalProxyURI); err != nil {
return nil, err
}
}
// Updates state.
p.State = Setup
return p, nil
}