Implement CSRF protection
[cacert-boardvoting.git] / boardvoting.go
index 1e62908..e8a83e4 100644 (file)
@@ -5,42 +5,68 @@ import (
        "context"
        "crypto/tls"
        "crypto/x509"
+       "database/sql"
        "encoding/base64"
        "encoding/pem"
+       "flag"
        "fmt"
-       "github.com/Masterminds/sprig"
-       "github.com/gorilla/sessions"
-       "github.com/jmoiron/sqlx"
-       "github.com/juju/loggo"
-       _ "github.com/mattn/go-sqlite3"
-       "gopkg.in/yaml.v2"
        "html/template"
        "io/ioutil"
        "net/http"
+       "os"
+       "sort"
        "strconv"
        "strings"
        "time"
+
+       "github.com/Masterminds/sprig"
+       "github.com/gorilla/csrf"
+       "github.com/gorilla/sessions"
+       _ "github.com/mattn/go-sqlite3"
+       "github.com/op/go-logging"
+       "gopkg.in/yaml.v2"
+
+       "git.cacert.org/cacert-boardvoting/boardvoting"
 )
 
+var configFile string
 var config *Config
 var store *sessions.CookieStore
+var csrfKey []byte
 var version = "undefined"
 var build = "undefined"
-var logger loggo.Logger
+var log *logging.Logger
 
 const sessionCookieName = "votesession"
 
-func getTemplateFilenames(templates []string) (result []string) {
-       result = make([]string, len(templates))
-       for i := range templates {
-               result[i] = fmt.Sprintf("templates/%s", templates[i])
+func renderTemplate(w http.ResponseWriter, r *http.Request, templates []string, context interface{}) {
+       funcMaps := sprig.FuncMap()
+       funcMaps["nl2br"] = func(text string) template.HTML {
+               return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1))
        }
-       return result
-}
+       funcMaps[csrf.TemplateTag] = func() template.HTML {
+               return csrf.TemplateField(r)
+       }
+
+       var baseTemplate *template.Template
 
-func renderTemplate(w http.ResponseWriter, templates []string, context interface{}) {
-       t := template.Must(template.New(templates[0]).Funcs(sprig.FuncMap()).ParseFiles(getTemplateFilenames(templates)...))
-       if err := t.Execute(w, context); err != nil {
+       for count, t := range templates {
+               if assetBytes, err := boardvoting.Asset(fmt.Sprintf("templates/%s", t)); err != nil {
+                       http.Error(w, err.Error(), http.StatusInternalServerError)
+               } else {
+                       if count == 0 {
+                               if baseTemplate, err = template.New(t).Funcs(funcMaps).Parse(string(assetBytes)); err != nil {
+                                       http.Error(w, err.Error(), http.StatusInternalServerError)
+                               }
+                       } else {
+                               if _, err := baseTemplate.New(t).Funcs(funcMaps).Parse(string(assetBytes)); err != nil {
+                                       http.Error(w, err.Error(), http.StatusInternalServerError)
+                               }
+                       }
+               }
+       }
+
+       if err := baseTemplate.Execute(w, context); err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
        }
 }
@@ -48,7 +74,7 @@ func renderTemplate(w http.ResponseWriter, templates []string, context interface
 type contextKey int
 
 const (
-       ctxNeedsAuth contextKey = iota
+       ctxNeedsAuth         contextKey = iota
        ctxVoter
        ctxDecision
        ctxVote
@@ -56,11 +82,14 @@ const (
 )
 
 func authenticateRequest(w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request)) {
+       emailsTried := make(map[string]bool)
        for _, cert := range r.TLS.PeerCertificates {
                for _, extKeyUsage := range cert.ExtKeyUsage {
                        if extKeyUsage == x509.ExtKeyUsageClientAuth {
                                for _, emailAddress := range cert.EmailAddresses {
-                                       voter, err := FindVoterByAddress(emailAddress)
+                                       emailLower := strings.ToLower(emailAddress)
+                                       emailsTried[emailLower] = true
+                                       voter, err := FindVoterByAddress(emailLower)
                                        if err != nil {
                                                http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
                                                return
@@ -77,8 +106,18 @@ func authenticateRequest(w http.ResponseWriter, r *http.Request, handler func(ht
        }
        needsAuth, ok := r.Context().Value(ctxNeedsAuth).(bool)
        if ok && needsAuth {
+               var templateContext struct {
+                       PageTitle string
+                       Voter     *Voter
+                       Flashes   interface{}
+                       Emails    []string
+               }
+               for k := range emailsTried {
+                       templateContext.Emails = append(templateContext.Emails, k)
+               }
+               sort.Strings(templateContext.Emails)
                w.WriteHeader(http.StatusForbidden)
-               renderTemplate(w, []string{"denied.html"}, nil)
+               renderTemplate(w, r, []string{"denied.html", "header.html", "footer.html"}, templateContext)
                return
        }
        handler(w, r)
@@ -89,7 +128,7 @@ type motionParameters struct {
 }
 
 type motionListParameters struct {
-       Page  int64
+       Page int64
        Flags struct {
                Confirmed, Withdraw, Unvoted bool
        }
@@ -162,7 +201,7 @@ func motionListHandler(w http.ResponseWriter, r *http.Request) {
                templateContext.PrevPage = params.Page - 1
        }
 
-       renderTemplate(w, []string{"motions.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
+       renderTemplate(w, r, []string{"motions.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
 }
 
 func motionHandler(w http.ResponseWriter, r *http.Request) {
@@ -195,7 +234,7 @@ func motionHandler(w http.ResponseWriter, r *http.Request) {
        }
        templateContext.Decision = decision
        templateContext.PageTitle = fmt.Sprintf("Motion %s: %s", decision.Tag, decision.Title)
-       renderTemplate(w, []string{"motion.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
+       renderTemplate(w, r, []string{"motion.html", "motion_fragments.html", "header.html", "footer.html"}, templateContext)
 }
 
 func singleDecisionHandler(w http.ResponseWriter, r *http.Request, tag string, handler func(http.ResponseWriter, *http.Request)) {
@@ -239,16 +278,16 @@ func getVoteFromRequest(r *http.Request) (vote VoteChoice, ok bool) {
 
 type FlashMessageAction struct{}
 
-func (a *FlashMessageAction) AddFlash(w http.ResponseWriter, r *http.Request, message interface{}, tags ...string) (err error) {
+func (a *FlashMessageAction) AddFlash(w http.ResponseWriter, r *http.Request, message interface{}, tags ...string) {
        session, err := store.Get(r, sessionCookieName)
        if err != nil {
-               logger.Errorf("getting session failed: %s", err)
+               log.Errorf("getting session failed: %v", err)
                return
        }
        session.AddFlash(message, tags...)
        session.Save(r, w)
        if err != nil {
-               logger.Errorf("saving session failed: %s", err)
+               log.Errorf("saving session failed: %v", err)
                return
        }
        return
@@ -275,6 +314,7 @@ func (a *withDrawMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
                PageTitle string
                Decision  *DecisionForDisplay
                Flashes   interface{}
+               Voter     *Voter
        }
 
        switch r.Method {
@@ -282,22 +322,20 @@ func (a *withDrawMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
                decision.Status = voteStatusWithdrawn
                decision.Modified = time.Now().UTC()
                if err := decision.UpdateStatus(); err != nil {
-                       logger.Errorf("withdrawing motion failed: %s", err)
+                       log.Errorf("withdrawing motion failed: %v", err)
                        http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
                        return
                }
 
                NotifyMailChannel <- NewNotificationWithDrawMotion(&(decision.Decision), voter)
 
-               if err := a.AddFlash(w, r, fmt.Sprintf("Motion %s has been withdrawn!", decision.Tag)); err != nil {
-                       http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
-                       return
-               }
+               a.AddFlash(w, r, fmt.Sprintf("Motion %s has been withdrawn!", decision.Tag))
 
                http.Redirect(w, r, "/motions/", http.StatusTemporaryRedirect)
        default:
                templateContext.Decision = decision
-               renderTemplate(w, templates, templateContext)
+               templateContext.Voter = voter
+               renderTemplate(w, r, templates, templateContext)
        }
 }
 
@@ -330,22 +368,19 @@ func (h *newMotionHandler) Handle(w http.ResponseWriter, r *http.Request) {
                if valid, data := form.Validate(); !valid {
                        templateContext.Voter = voter
                        templateContext.Form = form
-                       renderTemplate(w, templates, templateContext)
+                       renderTemplate(w, r, templates, templateContext)
                } else {
                        data.Proposed = time.Now().UTC()
                        data.ProponentId = voter.Id
                        if err := data.Create(); err != nil {
-                               logger.Errorf("saving motion failed: %s", err)
-                               http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+                               log.Errorf("saving motion failed: %v", err)
+                               http.Error(w, "Saving motion failed", http.StatusInternalServerError)
                                return
                        }
 
                        NotifyMailChannel <- &NotificationCreateMotion{decision: *data, voter: *voter}
 
-                       if err := h.AddFlash(w, r, "The motion has been proposed!"); err != nil {
-                               http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
-                               return
-                       }
+                       h.AddFlash(w, r, "The motion has been proposed!")
 
                        http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
                }
@@ -356,7 +391,7 @@ func (h *newMotionHandler) Handle(w http.ResponseWriter, r *http.Request) {
                templateContext.Form = NewDecisionForm{
                        VoteType: strconv.FormatInt(voteTypeMotion, 10),
                }
-               renderTemplate(w, templates, templateContext)
+               renderTemplate(w, r, templates, templateContext)
        }
 }
 
@@ -396,21 +431,18 @@ func (a editMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
                if valid, data := form.Validate(); !valid {
                        templateContext.Voter = voter
                        templateContext.Form = form
-                       renderTemplate(w, templates, templateContext)
+                       renderTemplate(w, r, templates, templateContext)
                } else {
                        data.Modified = time.Now().UTC()
                        if err := data.Update(); err != nil {
-                               logger.Errorf("updating motion failed: %s", err)
-                               http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+                               log.Errorf("updating motion failed: %v", err)
+                               http.Error(w, "Updating the motion failed.", http.StatusInternalServerError)
                                return
                        }
 
                        NotifyMailChannel <- NewNotificationUpdateMotion(*data, *voter)
 
-                       if err := a.AddFlash(w, r, "The motion has been modified!"); err != nil {
-                               http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
-                               return
-                       }
+                       a.AddFlash(w, r, "The motion has been modified!")
 
                        http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
                }
@@ -423,7 +455,7 @@ func (a editMotionAction) Handle(w http.ResponseWriter, r *http.Request) {
                        VoteType: fmt.Sprintf("%d", decision.VoteType),
                        Decision: &decision.Decision,
                }
-               renderTemplate(w, templates, templateContext)
+               renderTemplate(w, r, templates, templateContext)
        }
 }
 
@@ -498,19 +530,16 @@ func (h *directVoteHandler) Handle(w http.ResponseWriter, r *http.Request) {
        case http.MethodPost:
                voteResult := &Vote{
                        VoterId: voter.Id, Vote: vote, DecisionId: decision.Id, Voted: time.Now().UTC(),
-                       Notes: fmt.Sprintf("Direct Vote\n\n%s", getPEMClientCert(r))}
+                       Notes:   fmt.Sprintf("Direct Vote\n\n%s", getPEMClientCert(r))}
                if err := voteResult.Save(); err != nil {
-                       logger.Errorf("Problem saving vote: %s", err)
-                       http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+                       log.Errorf("Problem saving vote: %v", err)
+                       http.Error(w, "Problem saving vote", http.StatusInternalServerError)
                        return
                }
 
                NotifyMailChannel <- NewNotificationDirectVote(&decision.Decision, voter, voteResult)
 
-               if err := h.AddFlash(w, r, "Your vote has been registered."); err != nil {
-                       http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
-                       return
-               }
+               h.AddFlash(w, r, "Your vote has been registered.")
 
                http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
        default:
@@ -520,10 +549,12 @@ func (h *directVoteHandler) Handle(w http.ResponseWriter, r *http.Request) {
                        VoteChoice VoteChoice
                        PageTitle  string
                        Flashes    interface{}
+                       Voter      *Voter
                }
                templateContext.Decision = decision
                templateContext.VoteChoice = vote
-               renderTemplate(w, templates, templateContext)
+               templateContext.Voter = voter
+               renderTemplate(w, r, templates, templateContext)
        }
 }
 
@@ -557,7 +588,9 @@ func (h *proxyVoteHandler) Handle(w http.ResponseWriter, r *http.Request) {
                Voters    *[]Voter
                PageTitle string
                Flashes   interface{}
+               Voter     *Voter
        }
+       templateContext.Voter = proxy
        switch r.Method {
        case http.MethodPost:
                form := ProxyVoteForm{
@@ -569,13 +602,13 @@ func (h *proxyVoteHandler) Handle(w http.ResponseWriter, r *http.Request) {
                if valid, voter, data, justification := form.Validate(); !valid {
                        templateContext.Form = form
                        templateContext.Decision = decision
-                       if voters, err := GetVotersForProxy(proxy, &decision.Decision); err != nil {
+                       if voters, err := GetVotersForProxy(proxy); err != nil {
                                http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
                                return
                        } else {
                                templateContext.Voters = voters
                        }
-                       renderTemplate(w, templates, templateContext)
+                       renderTemplate(w, r, templates, templateContext)
                } else {
                        data.DecisionId = decision.Id
                        data.Voted = time.Now().UTC()
@@ -584,17 +617,14 @@ func (h *proxyVoteHandler) Handle(w http.ResponseWriter, r *http.Request) {
                                proxy.Name, justification, getPEMClientCert(r))
 
                        if err := data.Save(); err != nil {
-                               logger.Errorf("Error saving vote: %s", err)
+                               log.Errorf("Error saving vote: %s", err)
                                http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
                                return
                        }
 
                        NotifyMailChannel <- NewNotificationProxyVote(&decision.Decision, proxy, voter, data, justification)
 
-                       if err := h.AddFlash(w, r, "The vote has been registered."); err != nil {
-                               http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
-                               return
-                       }
+                       h.AddFlash(w, r, "The vote has been registered.")
 
                        http.Redirect(w, r, "/motions/", http.StatusMovedPermanently)
                }
@@ -602,13 +632,13 @@ func (h *proxyVoteHandler) Handle(w http.ResponseWriter, r *http.Request) {
        default:
                templateContext.Form = ProxyVoteForm{}
                templateContext.Decision = decision
-               if voters, err := GetVotersForProxy(proxy, &decision.Decision); err != nil {
+               if voters, err := GetVotersForProxy(proxy); err != nil {
                        http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
                        return
                } else {
                        templateContext.Voters = voters
                }
-               renderTemplate(w, templates, templateContext)
+               renderTemplate(w, r, templates, templateContext)
        }
 }
 
@@ -657,109 +687,194 @@ type Config struct {
        ServerCert                string `yaml:"server_certificate"`
        ServerKey                 string `yaml:"server_key"`
        CookieSecret              string `yaml:"cookie_secret"`
+       CsrfKey                   string `yaml:"csrf_key"`
        BaseURL                   string `yaml:"base_url"`
        MigrationsPath            string `yaml:"migrations_path"`
-       MailServer                struct {
+       HttpAddress               string `yaml:"http_address"`
+       HttpsAddress              string `yaml:"https_address"`
+       MailServer struct {
                Host string `yaml:"host"`
                Port int    `yaml:"port"`
        } `yaml:"mail_server"`
 }
 
-func init() {
-       loggo.ConfigureLoggers("<root>=ERROR; boardvoting=INFO")
-       logger = loggo.GetLogger("boardvoting")
-       logger.Infof("Logger initialized")
+func setupLogging(ctx context.Context) {
+       log = logging.MustGetLogger("boardvoting")
+       consoleLogFormat := logging.MustStringFormatter(`%{color}%{time:20060102 15:04:05.000-0700} %{longfile} ▶ %{level:s} %{id:05d}%{color:reset} %{message}`)
+       fileLogFormat := logging.MustStringFormatter(`%{time:20060102 15:04:05.000-0700} %{level:s} %{id:05d} %{message}`)
+
+       consoleBackend := logging.NewLogBackend(os.Stderr, "", 0)
 
-       source, err := ioutil.ReadFile("config.yaml")
+       logfile, err := os.OpenFile("boardvoting.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.FileMode(0640))
        if err != nil {
-               logger.Criticalf("Opening configuration file failed: %s", err)
-               panic(err)
+               panic("Could not open logfile")
+       }
+
+       fileBackend := logging.NewLogBackend(logfile, "", 0)
+       fileBackendLeveled := logging.AddModuleLevel(logging.NewBackendFormatter(fileBackend, fileLogFormat))
+       fileBackendLeveled.SetLevel(logging.INFO, "")
+
+       logging.SetBackend(fileBackendLeveled,
+               logging.NewBackendFormatter(consoleBackend, consoleLogFormat))
+
+       go func() {
+               for range ctx.Done() {
+                       if err = logfile.Close(); err != nil {
+                               fmt.Fprintf(os.Stderr, "Problem closing the log file: %v", err)
+                       }
+               }
+       }()
+
+       log.Info("Setup logging")
+}
+
+func readConfig() {
+       source, err := ioutil.ReadFile(configFile)
+       if err != nil {
+               log.Panicf("Opening configuration file failed: %v", err)
        }
        if err := yaml.Unmarshal(source, &config); err != nil {
-               logger.Criticalf("Loading configuration failed: %s", err)
-               panic(err)
+               log.Panicf("Loading configuration failed: %v", err)
+       }
+
+       if config.HttpsAddress == "" {
+               config.HttpsAddress = "127.0.0.1:8443"
+       }
+       if config.HttpAddress == "" {
+               config.HttpAddress = "127.0.0.1:8080"
        }
 
        cookieSecret, err := base64.StdEncoding.DecodeString(config.CookieSecret)
        if err != nil {
-               logger.Criticalf("Decoding cookie secret failed: %s", err)
+               log.Panicf("Decoding cookie secret failed: %v", err)
                panic(err)
        }
        if len(cookieSecret) < 32 {
-               logger.Criticalf("Cookie secret is less than 32 bytes long")
-               panic("Cookie secret too short")
+               log.Panic("Cookie secret is less than 32 bytes long")
+       }
+       csrfKey, err = base64.StdEncoding.DecodeString(config.CsrfKey)
+       if err != nil {
+               log.Panicf("Decoding csrf key failed: %v", err)
+       }
+       if len(csrfKey) != 32 {
+               log.Panicf("CSRF key must be exactly 32 bytes long but is %d bytes long", len(csrfKey))
        }
        store = sessions.NewCookieStore(cookieSecret)
-       logger.Infof("Read configuration")
+       log.Info("Read configuration")
+}
 
-       db, err = sqlx.Open("sqlite3", config.DatabaseFile)
+func setupDbConfig(ctx context.Context) {
+       database, err := sql.Open("sqlite3", config.DatabaseFile)
        if err != nil {
-               logger.Criticalf("Opening database failed: %s", err)
-               panic(err)
+               log.Panicf("Opening database failed: %v", err)
        }
-       logger.Infof("opened database connection")
-}
+       db = NewDB(database)
 
-func main() {
-       logger.Infof("CAcert Board Voting version %s, build %s", version, build)
+       go func() {
+               for range ctx.Done() {
+                       if err := db.Close(); err != nil {
+                               fmt.Fprintf(os.Stderr, "Problem closing the database: %v", err)
+                       }
+               }
+       }()
 
-       defer db.Close()
+       log.Infof("opened database connection")
+}
 
+func setupNotifications(ctx context.Context) {
        quitMailChannel := make(chan int)
        go MailNotifier(quitMailChannel)
-       defer func() { quitMailChannel <- 1 }()
 
+       go func() {
+               for range ctx.Done() {
+                       quitMailChannel <- 1
+               }
+       }()
+}
+
+func setupJobs(ctx context.Context) {
        quitChannel := make(chan int)
        go JobScheduler(quitChannel)
-       defer func() { quitChannel <- 1 }()
 
+       go func() {
+               for range ctx.Done() {
+                       quitChannel <- 1
+               }
+       }()
+}
+
+func setupHandlers() {
        http.Handle("/motions/", http.StripPrefix("/motions/", motionsHandler{}))
        http.Handle("/newmotion/", motionsHandler{})
        http.Handle("/proxy/", &decisionVoteHandler{})
        http.Handle("/vote/", &decisionVoteHandler{})
-       http.Handle("/static/", http.FileServer(http.Dir(".")))
+       http.Handle("/static/", http.FileServer(boardvoting.GetAssetFS()))
        http.Handle("/", http.RedirectHandler("/motions/", http.StatusMovedPermanently))
+}
 
+func setupTLSConfig() (tlsConfig *tls.Config) {
        // load CA certificates for client authentication
        caCert, err := ioutil.ReadFile(config.ClientCACertificates)
        if err != nil {
-               logger.Criticalf("Error reading client certificate CAs", err)
-               panic(err)
+               log.Panicf("Error reading client certificate CAs %v", err)
        }
        caCertPool := x509.NewCertPool()
        if !caCertPool.AppendCertsFromPEM(caCert) {
-               logger.Criticalf("could not initialize client CA certificate pool")
-               panic("client certificate CA pool initialization failed")
+               log.Panic("could not initialize client CA certificate pool")
        }
 
        // setup HTTPS server
-       tlsConfig := &tls.Config{
+       tlsConfig = &tls.Config{
                ClientCAs:  caCertPool,
                ClientAuth: tls.VerifyClientCertIfGiven,
        }
        tlsConfig.BuildNameToCertificate()
+       return
+}
+
+func init() {
+       flag.StringVar(
+               &configFile, "config", "config.yaml", "Configuration file name")
+}
+
+func main() {
+       flag.Parse()
+
+       var stopAll func()
+       executionContext, stopAll := context.WithCancel(context.Background())
+       setupLogging(executionContext)
+       readConfig()
+       setupDbConfig(executionContext)
+       setupNotifications(executionContext)
+       setupJobs(executionContext)
+       setupHandlers()
+       tlsConfig := setupTLSConfig()
+
+       defer stopAll()
+
+       log.Infof("CAcert Board Voting version %s, build %s", version, build)
 
        server := &http.Server{
-               Addr:      ":8443",
+               Addr:      config.HttpsAddress,
                TLSConfig: tlsConfig,
        }
 
-       logger.Infof("Launching application on https://localhost%s/", server.Addr)
+       server.Handler = csrf.Protect(csrfKey)(http.DefaultServeMux)
+
+       log.Infof("Launching application on https://%s/", server.Addr)
 
        errs := make(chan error, 1)
        go func() {
-               if err := http.ListenAndServe(":8080", http.RedirectHandler(config.BaseURL, http.StatusMovedPermanently)); err != nil {
+               if err := http.ListenAndServe(config.HttpsAddress, http.RedirectHandler(config.BaseURL, http.StatusMovedPermanently)); err != nil {
                        errs <- err
                }
                close(errs)
        }()
 
-       if err = server.ListenAndServeTLS(config.ServerCert, config.ServerKey); err != nil {
-               logger.Criticalf("ListenAndServerTLS failed: %s", err)
-               panic(err)
+       if err := server.ListenAndServeTLS(config.ServerCert, config.ServerKey); err != nil {
+               log.Panicf("ListenAndServerTLS failed: %v", err)
        }
        if err := <-errs; err != nil {
-               logger.Criticalf("ListenAndServe failed: %s", err)
-               panic(err)
+               log.Panicf("ListenAndServe failed: %v", err)
        }
 }