Add autocert
This commit is contained in:
@@ -18,11 +18,14 @@ import (
|
||||
"github.uio.no/torjus/apiary/honeypot/store"
|
||||
"github.uio.no/torjus/apiary/models"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/crypto/acme/autocert"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
http.Server
|
||||
|
||||
cfg config.FrontendConfig
|
||||
|
||||
store store.LoginAttemptStore
|
||||
|
||||
ServerLogger *zap.SugaredLogger
|
||||
@@ -33,7 +36,8 @@ type Server struct {
|
||||
attemptListenersLock sync.RWMutex
|
||||
attemptListeners map[string]chan models.LoginAttempt
|
||||
|
||||
streamContext context.Context
|
||||
streamContext context.Context
|
||||
httpRedirectServer http.Server
|
||||
}
|
||||
|
||||
func NewServer(cfg config.FrontendConfig, hs *honeypot.HoneypotServer, store store.LoginAttemptStore) *Server {
|
||||
@@ -41,8 +45,35 @@ func NewServer(cfg config.FrontendConfig, hs *honeypot.HoneypotServer, store sto
|
||||
ServerLogger: zap.NewNop().Sugar(),
|
||||
AccessLogger: zap.NewNop().Sugar(),
|
||||
store: store,
|
||||
cfg: cfg,
|
||||
}
|
||||
|
||||
if cfg.Autocert.Enable {
|
||||
certManager := autocert.Manager{
|
||||
Prompt: autocert.AcceptTOS,
|
||||
HostPolicy: autocert.HostWhitelist(cfg.Autocert.Domains...),
|
||||
Email: cfg.Autocert.Email,
|
||||
}
|
||||
if cfg.Autocert.CacheDir != "" {
|
||||
certManager.Cache = autocert.DirCache(cfg.Autocert.CacheDir)
|
||||
}
|
||||
|
||||
tlsConfig := certManager.TLSConfig()
|
||||
s.TLSConfig = tlsConfig
|
||||
s.RegisterOnShutdown(func() {
|
||||
timeoutCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
s.httpRedirectServer.Shutdown(timeoutCtx)
|
||||
})
|
||||
s.Addr = ":443"
|
||||
|
||||
if cfg.Autocert.RedirectHTTP {
|
||||
s.httpRedirectServer.Addr = ":80"
|
||||
s.httpRedirectServer.Handler = certManager.HTTPHandler(nil)
|
||||
}
|
||||
} else {
|
||||
s.Addr = cfg.ListenAddr
|
||||
}
|
||||
s.Addr = cfg.ListenAddr
|
||||
|
||||
r := chi.NewRouter()
|
||||
|
||||
@@ -79,6 +110,22 @@ func NewServer(cfg config.FrontendConfig, hs *honeypot.HoneypotServer, store sto
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) StartServe() error {
|
||||
if s.cfg.Autocert.Enable {
|
||||
if s.cfg.Autocert.RedirectHTTP {
|
||||
s.ServerLogger.Debug("Starting HTTP redirect server")
|
||||
go func() {
|
||||
if err := s.httpRedirectServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
s.ServerLogger.Warnw("HTTP redirect server returned error", "error", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
return s.ListenAndServeTLS("", "")
|
||||
} else {
|
||||
return s.ListenAndServe()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) addAttemptListener() (string, chan models.LoginAttempt) {
|
||||
ch := make(chan models.LoginAttempt)
|
||||
s.attemptListenersLock.Lock()
|
||||
|
Reference in New Issue
Block a user