-
Notifications
You must be signed in to change notification settings - Fork 561
/
server.go
214 lines (190 loc) · 5.78 KB
/
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
/* Package server provides tools to create http servers and handlers wrapping the
lura router
*/
// SPDX-License-Identifier: Apache-2.0
package server
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"sync"
"time"
"github.com/luraproject/lura/config"
"github.com/luraproject/lura/core"
)
// ToHTTPError translates an error into a HTTP status code
type ToHTTPError func(error) int
// DefaultToHTTPError is a ToHTTPError transalator that always returns an
// internal server error
func DefaultToHTTPError(_ error) int {
return http.StatusInternalServerError
}
const (
// HeaderCompleteResponseValue is the value of the CompleteResponseHeader
// if the response is complete
HeaderCompleteResponseValue = "true"
// HeaderIncompleteResponseValue is the value of the CompleteResponseHeader
// if the response is not complete
HeaderIncompleteResponseValue = "false"
)
var (
// CompleteResponseHeaderName is the header to flag incomplete responses to the client
CompleteResponseHeaderName = "X-KrakenD-Completed"
// HeadersToSend are the headers to pass from the router request to the proxy
HeadersToSend = []string{"Content-Type"}
// UserAgentHeaderValue is the value of the User-Agent header to add to the proxy request
UserAgentHeaderValue = []string{core.KrakendUserAgent}
// ErrInternalError is the error returned by the router when something went wrong
ErrInternalError = errors.New("internal server error")
// ErrPrivateKey is the error returned by the router when the private key is not defined
ErrPrivateKey = errors.New("private key not defined")
// ErrPublicKey is the error returned by the router when the public key is not defined
ErrPublicKey = errors.New("public key not defined")
)
// InitHTTPDefaultTransport ensures the default HTTP transport is configured just once per execution
func InitHTTPDefaultTransport(cfg config.ServiceConfig) {
onceTransportConfig.Do(func() {
http.DefaultTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: cfg.DialerTimeout,
KeepAlive: cfg.DialerKeepAlive,
FallbackDelay: cfg.DialerFallbackDelay,
DualStack: true,
}).DialContext,
DisableCompression: cfg.DisableCompression,
DisableKeepAlives: cfg.DisableKeepAlives,
MaxIdleConns: cfg.MaxIdleConns,
MaxIdleConnsPerHost: cfg.MaxIdleConnsPerHost,
IdleConnTimeout: cfg.IdleConnTimeout,
ResponseHeaderTimeout: cfg.ResponseHeaderTimeout,
ExpectContinueTimeout: cfg.ExpectContinueTimeout,
TLSHandshakeTimeout: 10 * time.Second,
}
})
}
// RunServer runs a http.Server with the given handler and configuration.
// It configures the TLS layer if required by the received configuration.
func RunServer(ctx context.Context, cfg config.ServiceConfig, handler http.Handler) error {
done := make(chan error)
s := NewServer(cfg, handler)
if s.TLSConfig == nil {
go func() {
done <- s.ListenAndServe()
}()
} else {
if cfg.TLS.PublicKey == "" {
return ErrPublicKey
}
if cfg.TLS.PrivateKey == "" {
return ErrPrivateKey
}
go func() {
done <- s.ListenAndServeTLS(cfg.TLS.PublicKey, cfg.TLS.PrivateKey)
}()
}
select {
case err := <-done:
return err
case <-ctx.Done():
return s.Shutdown(context.Background())
}
}
// NewServer returns a http.Server ready to serve the injected handler
func NewServer(cfg config.ServiceConfig, handler http.Handler) *http.Server {
return &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: handler,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
ReadHeaderTimeout: cfg.ReadHeaderTimeout,
IdleTimeout: cfg.IdleTimeout,
TLSConfig: ParseTLSConfig(cfg.TLS),
}
}
// ParseTLSConfig creates a tls.Config from the TLS section of the service configuration
func ParseTLSConfig(cfg *config.TLS) *tls.Config {
if cfg == nil {
return nil
}
if cfg.IsDisabled {
return nil
}
tlsConfig := &tls.Config{
MinVersion: parseTLSVersion(cfg.MinVersion),
MaxVersion: parseTLSVersion(cfg.MaxVersion),
CurvePreferences: parseCurveIDs(cfg),
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
CipherSuites: parseCipherSuites(cfg),
}
if !cfg.EnableMTLS {
return tlsConfig
}
certPool, err := x509.SystemCertPool()
if err != nil {
certPool = x509.NewCertPool()
}
caCert, err := ioutil.ReadFile(cfg.PublicKey)
if err != nil {
return tlsConfig
}
certPool.AppendCertsFromPEM(caCert)
tlsConfig.ClientCAs = certPool
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
return tlsConfig
}
func parseTLSVersion(key string) uint16 {
if v, ok := versions[key]; ok {
return v
}
return tls.VersionTLS12
}
func parseCurveIDs(cfg *config.TLS) []tls.CurveID {
l := len(cfg.CurvePreferences)
if l == 0 {
return defaultCurves
}
curves := make([]tls.CurveID, len(cfg.CurvePreferences))
for i := range curves {
curves[i] = tls.CurveID(cfg.CurvePreferences[i])
}
return curves
}
func parseCipherSuites(cfg *config.TLS) []uint16 {
l := len(cfg.CipherSuites)
if l == 0 {
return defaultCipherSuites
}
cs := make([]uint16, l)
for i := range cs {
cs[i] = uint16(cfg.CipherSuites[i])
}
return cs
}
var (
onceTransportConfig sync.Once
defaultCurves = []tls.CurveID{
tls.CurveP521,
tls.CurveP384,
tls.CurveP256,
}
defaultCipherSuites = []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
}
versions = map[string]uint16{
"SSL3.0": tls.VersionSSL30,
"TLS10": tls.VersionTLS10,
"TLS11": tls.VersionTLS11,
"TLS12": tls.VersionTLS12,
}
)