~mna/kick

ref: e42652bfd3e60c862f089c6cf03d8cf0623400ef kick/builder/builder.go -rw-r--r-- 8.0 KiB View raw
e42652bfMartin Angers start validating handler 1 year, 3 months ago
                                                                                
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
// Package builder defines the default builder functions that
// generate a kick server.
package builder

import (
	"compress/gzip"
	"crypto/tls"
	"errors"
	"fmt"
	"net/http"
	"time"

	"git.sr.ht/~mna/kick"
	"github.com/NYTimes/gziphandler"
	"github.com/gorilla/csrf"
	"github.com/gorilla/handlers"
	"github.com/julienschmidt/httprouter"
	"github.com/unrolled/secure"
	"golang.org/x/crypto/acme/autocert"
)

// Default is a ready-to-use kick.Builders that uses the
// builder functions of this package.
var Default = &kick.Builders{
	TLS:        TLS,
	HTTPServer: HTTPServer,
	Handler:    Handler,
}

// TLS builds the TLS configuration for the server.
func TLS(s *kick.Server) (*tls.Config, error) {
	var tc *tls.Config

	if s.TLS == nil {
		return nil, nil
	}

	if s.TLS.AutoCert {
		tc = configureTLSAutoCert(s.TLS)
	} else {
		tc = new(tls.Config)
	}

	switch s.TLS.Mode {
	case kick.TLSDefault:
		// zero-value of tls.Config requested

	case kick.TLSIntermediate, kick.TLSModern:
		// Causes servers to use Go's default ciphersuite preferences,
		// which are tuned to avoid attacks.
		tc.PreferServerCipherSuites = true
		// Only use curves which have assembly implementations
		tc.CurvePreferences = []tls.CurveID{
			tls.CurveP256,
			tls.X25519,
		}
		if s.TLS.Mode == kick.TLSIntermediate {
			break
		}

		tc.MinVersion = tls.VersionTLS12
		tc.CipherSuites = []uint16{
			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,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,

			// Best disabled, as they don't provide Forward Secrecy,
			// but might be necessary for some clients
			// tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
			// tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
		}

	default:
		return nil, fmt.Errorf("tls: unsupported TLS mode: %d", s.TLS.Mode)
	}

	if !s.TLS.AutoCert {
		if err := configureTLSCertificate(tc, s.TLS.CertFile, s.TLS.KeyFile); err != nil {
			return nil, err
		}
	}

	return tc, nil
}

func configureTLSAutoCert(config *kick.TLSConfig) *tls.Config {
	m := &autocert.Manager{
		Cache:      autocert.DirCache(config.AutoCertCacheDir),
		Prompt:     autocert.AcceptTOS,
		HostPolicy: autocert.HostWhitelist(config.AutoCertExactHosts...),
		Email:      config.AutoCertContactEmail,
	}
	return m.TLSConfig()
}

func configureTLSCertificate(tc *tls.Config, certFile, keyFile string) error {
	// certfile and keyfile are required
	if certFile == "" || keyFile == "" {
		return errors.New("tls: certificate and key files must be set")
	}

	var err error
	tc.Certificates = make([]tls.Certificate, 1)
	tc.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
	return err
}

// HTTPServer builds the http.Server struct for the server.
func HTTPServer(s *kick.Server) (*http.Server, error) {
	srv := &http.Server{
		Addr:              s.Addr,
		ReadTimeout:       s.ReadTimeout,
		ReadHeaderTimeout: s.ReadHeaderTimeout,
		WriteTimeout:      s.WriteTimeout,
		IdleTimeout:       s.IdleTimeout,
		MaxHeaderBytes:    s.MaxHeaderBytes,
		ConnState:         s.ConnStateHook,
		ErrorLog:          s.ErrorLog,
	}
	return srv, nil
}

type middleware func(http.Handler) http.Handler

// Handler builds the handler for the routes defined on the
// server, including any required middleware.
func Handler(s *kick.Server) (http.Handler, error) {
	router := httprouter.New()
	router.RedirectTrailingSlash = true
	router.RedirectFixedPath = true

	var mw []middleware
	var err error

	if s.Root != nil {
		mw, err = rootMiddleware(s, router)
		if err != nil {
			return nil, err
		}
	}

	for _, route := range s.Routes {
		if err := configureRoute(router, route); err != nil {
			return nil, err
		}
	}

	h := combineMiddleware(router, mw)
	return h, nil
}

func rootMiddleware(s *kick.Server, router *httprouter.Router) ([]middleware, error) {
	if s.Root.MethodNotAllowedHandler != nil {
		router.MethodNotAllowed = s.Root.MethodNotAllowedHandler
		router.HandleMethodNotAllowed = true
	}
	if s.Root.NotFoundHandler != nil {
		router.NotFound = s.Root.NotFoundHandler
	}

	var mw []middleware

	if fn := s.Root.PanicRecoveryFunc; fn != nil {
		mw = append(mw, panicRecovery(fn))
	}
	if s.Root.TrustProxyHeaders {
		mw = append(mw, handlers.ProxyHeaders)
	}
	if s.Root.AllowMethodOverride {
		mw = append(mw, handlers.HTTPMethodOverrideHandler)
	}
	if s.Root.RequestIDHeader != "" {
		mw = append(mw, requestID(s.Root.RequestIDHeader, s.Root.RequestIDForceNew))
	}
	if s.Root.SecurityHeaders != nil {
		sec := secure.New(*s.Root.SecurityHeaders)
		mw = append(mw, sec.Handler)
	}
	if fn := s.Root.LoggingFunc; fn != nil {
		mw = append(mw, logging(fn))
	}

	if s.Root.CanonicalHost != "" {
		redir := s.Root.CanonicalHostRedirectStatusCode
		if redir < 300 || redir >= 400 {
			return nil, fmt.Errorf("handler: canonical host redirection code must be in the 3xx family: %d", redir)
		}
		mw = append(mw, handlers.CanonicalHost(s.Root.CanonicalHost, redir))
	}

	if conf := s.Root.Gzip; conf != nil {
		level := conf.CompressionLevel
		if level == 0 {
			level = gzip.DefaultCompression
		}
		gzh, err := gziphandler.GzipHandlerWithOpts(
			gziphandler.CompressionLevel(level),
			gziphandler.ContentTypes(conf.ContentTypes),
			gziphandler.MinSize(conf.MinSize),
		)
		if err != nil {
			return nil, err
		}
		mw = append(mw, gzh)
	}

	return mw, nil
}

func configureRoute(router *httprouter.Router, route *kick.Route) error {
	if route.Path == "" {
		return errors.New("handler: route must have a path")
	}
	if route.Path[0] != '/' {
		return fmt.Errorf("handler: route path %s must start with a slash `/`", route.Path)
	}
	if route.Method == "" {
		return fmt.Errorf("handler: method is missing for route %s", route.Path)
	}
	if route.Handler == nil {
		return fmt.Errorf("handler: handler is missing for route %s %s", route.Method, route.Path)
	}

	if route.Config == nil {
		router.Handler(route.Method, route.Path, route.Handler)
		return nil
	}

	var mw []middleware

	if route.Config.HandlerTimeout > 0 {
		mw = append(mw, timeoutHandler(route.Config.HandlerTimeout))
	}

	if conf := route.Config.RequestLimit; conf != nil {
		// either rate or fill interval must be set, not both.
		if conf.FillInterval > 0 && conf.Rate > 0 {
			return fmt.Errorf("handler: only one of FillInterval or Rate must be set")
		}
		if conf.FillInterval <= 0 && conf.Rate <= 0 {
			return fmt.Errorf("handler: one of FillInterval or Rate must be set")
		}
		mw = append(mw, requestLimit(route.Config.RequestLimit))
	}

	if conf := route.Config.CORS; conf != nil {
		opts := []handlers.CORSOption{
			handlers.AllowedHeaders(conf.AllowedHeaders),
			handlers.AllowedMethods(conf.AllowedMethods),
			handlers.AllowedOrigins(conf.AllowedOrigins),
			handlers.ExposedHeaders(conf.ExposedHeaders),
			handlers.MaxAge(int(conf.MaxAge / time.Second)),
		}
		if conf.AllowCredentials {
			opts = append(opts, handlers.AllowCredentials())
		}
		if conf.OptionsStatusCode > 0 {
			opts = append(opts, handlers.OptionStatusCode(conf.OptionsStatusCode))
		}
		mw = append(mw, handlers.CORS(opts...))
	}

	if conf := route.Config.CSRF; conf != nil {
		mw = append(mw, csrf.Protect(
			conf.AuthKey,
			csrf.CookieName(conf.CookieName),
			csrf.Domain(conf.Domain),
			csrf.HttpOnly(conf.HTTPOnly),
			csrf.MaxAge(int(conf.MaxAge/time.Second)),
			csrf.Path(conf.Path),
			csrf.RequestHeader(conf.RequestHeader),
			csrf.Secure(conf.Secure),
		))
	}

	if route.Config.MaxRequestBodyBytes > 0 {
		mw = append(mw, limitRequestBodyBytes(route.Config.MaxRequestBodyBytes))
	}

	if route.Config.MaxResponseBodyBytes > 0 {
		mw = append(mw, limitResponseBodyBytes(route.Config.MaxResponseBodyBytes))
	}

	if cts := route.Config.RequestContentTypes; len(cts) > 0 {
		mw = append(mw, requestContentType(cts))
	}

	if cts := route.Config.ResponseContentTypes; len(cts) > 0 {
		mw = append(mw, responseContentType(cts))
	}

	h := combineMiddleware(route.Handler, mw)
	router.Handler(route.Method, route.Path, h)

	return nil
}

func combineMiddleware(h http.Handler, mw []middleware) http.Handler {
	for i := len(mw) - 1; i >= 0; i-- {
		h = mw[i](h)
	}
	return h
}