violet/servers/https.go

129 lines
4.2 KiB
Go
Raw Normal View History

2023-04-21 03:21:46 +01:00
package servers
2023-04-22 18:11:21 +01:00
import (
"crypto/tls"
"fmt"
2023-07-22 01:11:47 +01:00
"github.com/1f349/violet/favicons"
2024-05-13 19:33:33 +01:00
"github.com/1f349/violet/logger"
2023-07-22 01:11:47 +01:00
"github.com/1f349/violet/servers/conf"
2024-02-16 01:41:42 +00:00
"github.com/1f349/violet/servers/metrics"
2023-07-22 01:11:47 +01:00
"github.com/1f349/violet/utils"
2024-02-16 01:41:42 +00:00
"github.com/prometheus/client_golang/prometheus"
2023-04-22 18:11:21 +01:00
"github.com/sethvargo/go-limiter/httplimit"
"github.com/sethvargo/go-limiter/memorystore"
"net/http"
2023-06-20 17:33:43 +01:00
"path"
"runtime"
2023-04-22 18:11:21 +01:00
"time"
)
// NewHttpsServer creates and runs a http server containing the public https
// endpoints for the reverse proxy.
2024-02-16 01:41:42 +00:00
func NewHttpsServer(conf *conf.Conf, registry *prometheus.Registry) *http.Server {
2023-08-12 15:58:41 +01:00
r := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
2024-05-13 19:33:33 +01:00
logger.Logger.Debug("Request", "method", req.Method, "url", req.URL, "remote", req.RemoteAddr, "host", req.Host, "length", req.ContentLength, "goroutine", runtime.NumGoroutine())
2023-08-12 15:58:41 +01:00
conf.Router.ServeHTTP(rw, req)
})
favMiddleware := setupFaviconMiddleware(conf.Favicons, r)
2024-02-21 11:44:51 +00:00
metricsMeta := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
r.ServeHTTP(rw, req)
2024-02-21 11:44:51 +00:00
})
if registry != nil {
metricsMiddleware := metrics.New(registry, nil).WrapHandler("violet-https", favMiddleware)
metricsMeta = func(rw http.ResponseWriter, req *http.Request) {
metricsMiddleware.ServeHTTP(rw, metrics.AddHostCtx(req))
}
}
rateLimiter := setupRateLimiter(conf.RateLimit, metricsMeta)
2024-02-16 01:41:42 +00:00
hsts := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
rateLimiter.ServeHTTP(rw, req)
2024-02-16 01:41:42 +00:00
})
2023-08-12 15:58:41 +01:00
2023-06-04 22:28:48 +01:00
return &http.Server{
2024-02-16 01:41:42 +00:00
Handler: hsts,
2023-12-06 08:37:35 +00:00
TLSConfig: &tls.Config{
2023-12-16 00:53:24 +00:00
// Suggested by https://ssl-config.mozilla.org/#server=go&version=1.21.5&config=intermediate
MinVersion: tls.VersionTLS12,
2024-02-16 01:41:42 +00:00
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_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
},
2023-12-06 08:37:35 +00:00
GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
// error out on invalid domains
if !conf.Domains.IsValid(info.ServerName) {
return nil, fmt.Errorf("invalid hostname used: '%s'", info.ServerName)
}
2023-04-22 18:11:21 +01:00
2023-12-06 08:37:35 +00:00
// find a certificate
cert := conf.Certs.GetCertForDomain(info.ServerName)
if cert == nil {
return nil, fmt.Errorf("failed to find certificate for: '%s'", info.ServerName)
}
2023-04-22 18:11:21 +01:00
2023-12-06 08:37:35 +00:00
// time to return
return cert, nil
},
},
2023-04-22 18:11:21 +01:00
ReadTimeout: 150 * time.Second,
ReadHeaderTimeout: 150 * time.Second,
WriteTimeout: 150 * time.Second,
IdleTimeout: 150 * time.Second,
MaxHeaderBytes: 4096000,
}
}
// setupRateLimiter is an internal function to create a middleware to manage
// rate limits.
2023-06-03 19:33:06 +01:00
func setupRateLimiter(rateLimit uint64, next http.Handler) http.Handler {
2023-04-22 18:11:21 +01:00
// create memory store
store, err := memorystore.New(&memorystore.Config{
Tokens: rateLimit,
Interval: time.Minute,
})
if err != nil {
2024-05-13 19:33:33 +01:00
logger.Logger.Fatal("Failed to initialize memory store", "err", err)
2023-04-22 18:11:21 +01:00
}
// create a middleware using ips as the key for rate limits
middleware, err := httplimit.NewMiddleware(store, httplimit.IPKeyFunc())
if err != nil {
2024-05-13 19:33:33 +01:00
logger.Logger.Fatal("Failed to initialize httplimit middleware", "err", err)
2023-04-22 18:11:21 +01:00
}
2023-06-03 19:33:06 +01:00
return middleware.Handle(next)
}
func setupFaviconMiddleware(fav *favicons.Favicons, next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
2023-08-30 11:34:53 +01:00
if req.Header.Get("X-Violet-Loop-Detect") == "1" {
rw.WriteHeader(http.StatusLoopDetected)
_, _ = rw.Write([]byte("Detected a routing loop\n"))
return
}
2023-06-03 19:33:06 +01:00
if req.Header.Get("X-Violet-Raw-Favicon") != "1" {
switch req.URL.Path {
2023-06-20 17:33:43 +01:00
case "/favicon.svg", "/favicon.png", "/favicon.ico":
2023-06-03 19:33:06 +01:00
icons := fav.GetIcons(req.Host)
if icons == nil {
break
}
2023-06-20 17:33:43 +01:00
raw, contentType, err := icons.ProduceForExt(path.Ext(req.URL.Path))
2023-06-03 19:33:06 +01:00
if err != nil {
2023-06-20 17:33:43 +01:00
utils.RespondVioletError(rw, http.StatusTeapot, "No icon available")
2023-06-03 19:33:06 +01:00
return
}
2023-06-20 17:33:43 +01:00
rw.Header().Set("Content-Type", contentType)
2023-06-03 19:33:06 +01:00
rw.WriteHeader(http.StatusOK)
_, _ = rw.Write(raw)
return
}
}
next.ServeHTTP(rw, req)
})
2023-04-22 18:11:21 +01:00
}