-
Notifications
You must be signed in to change notification settings - Fork 13
/
http_server.go
263 lines (225 loc) · 6.76 KB
/
http_server.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
// Copyright 2022-2024 Sauce Labs Inc., all rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package forwarder
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"sync"
"time"
"github.com/saucelabs/forwarder/httplog"
"github.com/saucelabs/forwarder/log"
"github.com/saucelabs/forwarder/middleware"
)
type Scheme string
const (
HTTPScheme Scheme = "http"
HTTPSScheme Scheme = "https"
HTTP2Scheme Scheme = "h2"
)
func (s Scheme) String() string {
return string(s)
}
func httpsTLSConfigTemplate() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, //nolint:gosec // allow weak ciphers
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
}
}
func h2TLSConfigTemplate() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_CHACHA20_POLY1305_SHA256,
tls.TLS_AES_128_GCM_SHA256,
tls.TLS_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
},
NextProtos: []string{"h2", "http/1.1"},
}
}
type HTTPServerConfig struct {
ListenerConfig
Protocol Scheme
TLSServerConfig
IdleTimeout time.Duration
ReadTimeout time.Duration
ReadHeaderTimeout time.Duration
WriteTimeout time.Duration
shutdownConfig
LogHTTPMode httplog.Mode
BasicAuth *url.Userinfo
PromConfig
}
func DefaultHTTPServerConfig() *HTTPServerConfig {
return &HTTPServerConfig{
ListenerConfig: *DefaultListenerConfig(":8080"),
Protocol: HTTPScheme,
IdleTimeout: 1 * time.Hour,
ReadHeaderTimeout: 1 * time.Minute,
shutdownConfig: defaultShutdownConfig(),
}
}
func (c *HTTPServerConfig) Validate() error {
if err := validatedUserInfo(c.BasicAuth); err != nil {
return fmt.Errorf("basic_auth: %w", err)
}
return nil
}
type HTTPServer struct {
config HTTPServerConfig
log log.Logger
srv *http.Server
listener net.Listener
}
// NewHTTPServer creates a new HTTP server.
// It is the caller's responsibility to call Close on the returned server.
func NewHTTPServer(cfg *HTTPServerConfig, h http.Handler, log log.Logger) (*HTTPServer, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
hs := &HTTPServer{
config: *cfg,
log: log,
srv: &http.Server{
Handler: withMiddleware(cfg, log, h),
IdleTimeout: cfg.IdleTimeout,
ReadTimeout: cfg.ReadTimeout,
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
WriteTimeout: cfg.WriteTimeout,
},
}
switch hs.config.Protocol {
case HTTPScheme:
// do nothing
case HTTPSScheme:
if err := hs.configureHTTPS(); err != nil {
return nil, err
}
case HTTP2Scheme:
if err := hs.configureHTTP2(); err != nil {
return nil, err
}
}
l, err := hs.listen()
if err != nil {
return nil, err
}
hs.listener = l
hs.log.Infof("HTTP server listen address=%s protocol=%s", l.Addr(), hs.config.Protocol)
return hs, nil
}
func withMiddleware(cfg *HTTPServerConfig, log log.Logger, h http.Handler) http.Handler {
// Note that the order of execution is reversed.
if cfg.BasicAuth != nil {
p, _ := cfg.BasicAuth.Password()
h = middleware.NewBasicAuth().Wrap(h, cfg.BasicAuth.Username(), p)
}
// Logger middleware must immediately follow the Prometheus middleware because it uses the Prometheus delegator.
if cfg.LogHTTPMode != httplog.None {
h = httplog.NewLogger(log.Infof, cfg.LogHTTPMode).LogFunc().Wrap(h)
}
// Prometheus middleware must be the first one to be executed to collect metrics for all other middlewares.
h = middleware.NewPrometheus(cfg.PromRegistry, cfg.PromNamespace).Wrap(h)
return h
}
func (hs *HTTPServer) configureHTTPS() error {
if hs.config.CertFile == "" && hs.config.KeyFile == "" {
hs.log.Infof("no TLS certificate provided, using self-signed certificate")
} else {
hs.log.Debugf("loading TLS certificate from %s and %s", hs.config.CertFile, hs.config.KeyFile)
}
hs.srv.TLSConfig = httpsTLSConfigTemplate()
hs.srv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
return hs.config.ConfigureTLSConfig(hs.srv.TLSConfig)
}
func (hs *HTTPServer) configureHTTP2() error {
if hs.config.CertFile == "" && hs.config.KeyFile == "" {
hs.log.Infof("no TLS certificate provided, using self-signed certificate")
} else {
hs.log.Debugf("loading TLS certificate from %s and %s", hs.config.CertFile, hs.config.KeyFile)
}
hs.srv.TLSConfig = h2TLSConfigTemplate()
return hs.config.ConfigureTLSConfig(hs.srv.TLSConfig)
}
func (hs *HTTPServer) Run(ctx context.Context) error {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
var cancel context.CancelFunc
ctx, cancel = shutdownContext(hs.config.shutdownConfig)
defer cancel()
if err := hs.srv.Shutdown(ctx); err != nil {
hs.log.Debugf("failed to gracefully shutdown server error=%s", err)
if err := hs.srv.Close(); err != nil {
hs.log.Debugf("failed to close server error=%s", err)
}
}
}()
var srvErr error
switch hs.config.Protocol {
case HTTPScheme:
srvErr = hs.srv.Serve(hs.listener)
case HTTP2Scheme, HTTPSScheme:
srvErr = hs.srv.ServeTLS(hs.listener, "", "")
default:
return fmt.Errorf("invalid protocol %q", hs.config.Protocol)
}
if srvErr != nil {
if errors.Is(srvErr, http.ErrServerClosed) {
hs.log.Debugf("server was shutdown gracefully")
srvErr = nil
}
return srvErr
}
wg.Wait()
return nil
}
func (hs *HTTPServer) listen() (net.Listener, error) {
switch hs.config.Protocol {
case HTTPScheme, HTTPSScheme, HTTP2Scheme:
l := Listener{
ListenerConfig: hs.config.ListenerConfig,
PromConfig: hs.config.PromConfig,
}
if err := l.Listen(); err != nil {
return nil, fmt.Errorf("failed to open listener on address %s: %w", hs.srv.Addr, err)
}
return &l, nil
default:
return nil, fmt.Errorf("invalid protocol %q", hs.config.Protocol)
}
}
// Addr returns the address the server is listening on.
func (hs *HTTPServer) Addr() string {
return hs.listener.Addr().String()
}
func (hs *HTTPServer) Close() error {
return hs.listener.Close()
}