cacert-boardvoting/cmd/boardvoting/main.go
Jan Dittberner 164495c818 Improve design
- improve icons
- implement VoteChoice and VoteStatus as real types with Scanner and Value
  methods
2022-05-27 14:42:39 +02:00

258 lines
6.3 KiB
Go

/*
Copyright 2017-2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// The CAcert board voting software.
package main
import (
"crypto/tls"
"crypto/x509"
"database/sql"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/alexedwards/scs/sqlite3store"
"github.com/alexedwards/scs/v2"
"github.com/go-playground/form/v4"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"git.cacert.org/cacert-boardvoting/internal"
"git.cacert.org/cacert-boardvoting/internal/models"
)
const sessionHours = 12
var (
version = "undefined"
commit = "undefined"
date = "undefined"
)
type application struct {
errorLog, infoLog *log.Logger
users *models.UserModel
motions *models.MotionModel
jobScheduler *JobScheduler
mailNotifier *MailNotifier
mailConfig *mailConfig
templateCache map[string]*template.Template
sessionManager *scs.SessionManager
formDecoder *form.Decoder
}
func main() {
configFile := flag.String("config", "config.yaml", "Configuration file name")
flag.Parse()
infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime)
infoLog.Printf("CAcert Board Voting version %s, commit %s built at %s", version, commit, date)
config, err := parseConfig(*configFile)
if err != nil {
errorLog.Fatal(err)
}
db, err := openDB(config.DatabaseFile)
if err != nil {
errorLog.Fatal(err)
}
defer func(db *sqlx.DB) {
_ = db.Close()
}(db)
if err != nil {
errorLog.Fatalf("could not setup decision model: %v", err)
}
templateCache, err := newTemplateCache()
if err != nil {
errorLog.Fatal(err)
}
sessionManager := scs.New()
sessionManager.Store = sqlite3store.New(db.DB)
sessionManager.Lifetime = sessionHours * time.Hour
sessionManager.Cookie.SameSite = http.SameSiteStrictMode
sessionManager.Cookie.Secure = true
app := &application{
errorLog: errorLog,
infoLog: infoLog,
motions: &models.MotionModel{DB: db, InfoLog: infoLog},
users: &models.UserModel{DB: db},
mailConfig: config.MailConfig,
templateCache: templateCache,
sessionManager: sessionManager,
formDecoder: setupFormDecoder(),
}
err = internal.InitializeDb(db.DB, infoLog)
if err != nil {
errorLog.Fatal(err)
}
app.NewMailNotifier()
defer app.mailNotifier.Quit()
go app.StartMailNotifier()
app.NewJobScheduler()
defer app.jobScheduler.Quit()
go app.jobScheduler.Schedule()
infoLog.Printf("Starting server on %s", config.HTTPAddress)
errChan := make(chan error, 1)
infoLog.Printf("TLS config setup, starting TLS server on %s", config.HTTPSAddress)
go setupHTTPRedirect(config, errChan)
err = app.startHTTPSServer(config)
if err != nil {
errorLog.Fatalf("ListenAndServeTLS (HTTPS) failed: %v", err)
}
if err := <-errChan; err != nil {
errorLog.Fatalf("ListenAndServe (HTTP) failed: %v", err)
}
}
func setupFormDecoder() *form.Decoder {
decoder := form.NewDecoder()
decoder.RegisterCustomTypeFunc(func(values []string) (interface{}, error) {
v, err := models.VoteTypeFromString(values[0])
if err != nil {
return nil, fmt.Errorf("could not convert value %s: %w", values[0], err)
}
return v, nil
}, new(models.VoteType))
decoder.RegisterCustomTypeFunc(func(values []string) (interface{}, error) {
v, err := models.VoteChoiceFromString(values[0])
if err != nil {
return nil, fmt.Errorf("could not convert value %s: %w", values[0], err)
}
return v, nil
}, new(models.VoteChoice))
return decoder
}
func (app *application) startHTTPSServer(config *Config) error {
tlsConfig, err := setupTLSConfig(config)
if err != nil {
return fmt.Errorf("could not setup TLS configuration: %w", err)
}
srv := &http.Server{
Addr: config.HTTPSAddress,
TLSConfig: tlsConfig,
ErrorLog: app.errorLog,
Handler: app.routes(),
IdleTimeout: config.Timeouts.Idle,
ReadHeaderTimeout: config.Timeouts.ReadHeader,
ReadTimeout: config.Timeouts.Read,
WriteTimeout: config.Timeouts.Write,
}
err = srv.ListenAndServeTLS(config.ServerCert, config.ServerKey)
if err != nil {
return fmt.Errorf("")
}
return nil
}
func setupHTTPRedirect(config *Config, errChan chan error) {
redirect := &http.Server{
Addr: config.HTTPAddress,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
redirectURL := url.URL{
Scheme: "https://",
Host: strings.Join(
[]string{
strings.Split(r.URL.Host, ":")[0],
strings.Split(config.HTTPSAddress, ":")[1],
},
":",
),
Path: r.URL.Path,
}
http.Redirect(w, r, redirectURL.String(), http.StatusMovedPermanently)
}),
IdleTimeout: config.Timeouts.Idle,
ReadHeaderTimeout: config.Timeouts.ReadHeader,
ReadTimeout: config.Timeouts.Read,
WriteTimeout: config.Timeouts.Write,
}
if err := redirect.ListenAndServe(); err != nil {
errChan <- err
}
close(errChan)
}
func setupTLSConfig(config *Config) (*tls.Config, error) {
caCert, err := ioutil.ReadFile(config.ClientCACertificates)
if err != nil {
return nil, fmt.Errorf("could not read client certificate CAs %w", err)
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCert) {
return nil, fmt.Errorf(
"could not initialize client CA certificate pool from %s",
config.ClientCACertificates,
)
}
return &tls.Config{
MinVersion: tls.VersionTLS12,
ClientCAs: caCertPool,
ClientAuth: tls.VerifyClientCertIfGiven,
}, nil
}
func openDB(dbFile string) (*sqlx.DB, error) {
db, err := sql.Open("sqlite3", dbFile)
if err != nil {
return nil, fmt.Errorf("could not open database file %s: %w", dbFile, err)
}
if err = db.Ping(); err != nil {
return nil, fmt.Errorf("could not ping database: %w", err)
}
return sqlx.NewDb(db, "sqlite3"), nil
}