235 lines
7 KiB
Go
235 lines
7 KiB
Go
/*
|
|
Copyright 2021 Jan Dittberner
|
|
|
|
|
|
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.
|
|
*/
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"crypto/x509"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/signal"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"git.cacert.org/oidc_registration/handlers"
|
|
"git.cacert.org/oidc_registration/services"
|
|
openapiClient "github.com/go-openapi/runtime/client"
|
|
"github.com/gorilla/csrf"
|
|
"github.com/knadh/koanf"
|
|
"github.com/knadh/koanf/parsers/toml"
|
|
"github.com/knadh/koanf/providers/confmap"
|
|
hydra "github.com/ory/hydra-client-go/client"
|
|
"github.com/ory/hydra-client-go/client/admin"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func main() {
|
|
logger := log.New()
|
|
config, err := services.ConfigureApplication(
|
|
logger,
|
|
"REGISTRATION",
|
|
map[string]interface{}{
|
|
"server.port": 5000,
|
|
"server.name": "registration.cacert.localhost",
|
|
"server.key": "certs/registration.cacert.localhost.key",
|
|
"server.certificate": "certs/registration.cacert.localhost.crt.pem",
|
|
"hydra.admin.url": "https://auth.cacert.localhost:4445/",
|
|
"session.path": "sessions/registration",
|
|
"i18n.languages": []string{"en", "de"},
|
|
})
|
|
if err != nil {
|
|
log.Fatalf("error loading configuration: %v", err)
|
|
}
|
|
|
|
sessionPath, sessionAuthKey, sessionEncKey := configureSessionParameters(config)
|
|
services.InitSessionStore(logger, sessionPath, sessionAuthKey, sessionEncKey)
|
|
|
|
tlsClientConfig := &tls.Config{
|
|
MinVersion: tls.VersionTLS12,
|
|
}
|
|
if config.Exists("hydra.rootCAs") {
|
|
rootCAFile := config.MustString("hydra.rootCAs")
|
|
caCertPool := x509.NewCertPool()
|
|
pemBytes, err := ioutil.ReadFile(rootCAFile)
|
|
if err != nil {
|
|
log.Fatalf("could not read CA certificate file: %v", err)
|
|
}
|
|
caCertPool.AppendCertsFromPEM(pemBytes)
|
|
tlsClientConfig.RootCAs = caCertPool
|
|
}
|
|
|
|
ctx := context.Background()
|
|
ctx = services.InitI18n(ctx, logger, config.Strings("i18n.languages"))
|
|
services.AddMessages(ctx)
|
|
|
|
adminURL, err := url.Parse(config.MustString("hydra.admin.url"))
|
|
if err != nil {
|
|
log.Panicf("could not parse Hydra admin URL: %v", err)
|
|
}
|
|
tlsClientTransport := &http.Transport{TLSClientConfig: tlsClientConfig}
|
|
httpClient := &http.Client{Transport: tlsClientTransport}
|
|
adminClient := hydra.New(openapiClient.NewWithClient(
|
|
adminURL.Host,
|
|
adminURL.Path,
|
|
[]string{adminURL.Scheme},
|
|
httpClient,
|
|
), nil)
|
|
|
|
alive, err := adminClient.Admin.IsInstanceAlive(admin.NewIsInstanceAliveParams())
|
|
if err != nil {
|
|
log.Panicf("could not check hydra health: %v", err)
|
|
}
|
|
log.Infof("hydra status is %s", alive.GetPayload().Status)
|
|
|
|
ctx = context.WithValue(ctx, services.CtxAdminClient, adminClient.Admin)
|
|
|
|
csrfKey, err := base64.StdEncoding.DecodeString(config.MustString("security.csrf.key"))
|
|
if err != nil {
|
|
logger.Fatalf("could not parse CSRF key bytes: %v", err)
|
|
}
|
|
|
|
nextRequestId := func() string {
|
|
return fmt.Sprintf("%d", time.Now().UnixNano())
|
|
}
|
|
|
|
tracing := handlers.Tracing(nextRequestId)
|
|
logging := handlers.Logging(logger)
|
|
hsts := handlers.EnableHSTS()
|
|
csrfProtect := csrf.Protect(
|
|
csrfKey,
|
|
csrf.Secure(true),
|
|
csrf.SameSite(csrf.SameSiteStrictMode),
|
|
csrf.MaxAge(600))
|
|
errorMiddleware := handlers.ErrorHandling(
|
|
ctx,
|
|
logger,
|
|
"templates",
|
|
)
|
|
|
|
errorHandler := handlers.NewErrorHandler()
|
|
staticFiles := http.FileServer(http.Dir("static"))
|
|
|
|
router := http.NewServeMux()
|
|
router.Handle("/error", errorHandler)
|
|
router.Handle("/health", handlers.NewHealthHandler())
|
|
router.Handle("/images/", staticFiles)
|
|
router.Handle("/css/", staticFiles)
|
|
router.Handle("/js/", staticFiles)
|
|
|
|
handlerChain := tracing(logging(hsts(errorMiddleware(csrfProtect(router)))))
|
|
|
|
startServer(ctx, handlerChain, logger, config)
|
|
}
|
|
|
|
func configureSessionParameters(config *koanf.Koanf) (string, []byte, []byte) {
|
|
sessionPath := config.MustString("session.path")
|
|
sessionAuthKey, err := base64.StdEncoding.DecodeString(config.String("session.auth-key"))
|
|
if err != nil {
|
|
log.Fatalf("could not decode session auth key: %s", err)
|
|
}
|
|
sessionEncKey, err := base64.StdEncoding.DecodeString(config.String("session.enc-key"))
|
|
if err != nil {
|
|
log.Fatalf("could not decode session encryption key: %s", err)
|
|
}
|
|
|
|
generated := false
|
|
if len(sessionAuthKey) != 64 {
|
|
sessionAuthKey = services.GenerateKey(64)
|
|
generated = true
|
|
}
|
|
if len(sessionEncKey) != 32 {
|
|
sessionEncKey = services.GenerateKey(32)
|
|
generated = true
|
|
}
|
|
|
|
if generated {
|
|
_ = config.Load(confmap.Provider(map[string]interface{}{
|
|
"session.auth-key": base64.StdEncoding.EncodeToString(sessionAuthKey),
|
|
"session.enc-key": base64.StdEncoding.EncodeToString(sessionEncKey),
|
|
}, "."), nil)
|
|
tomlData, err := config.Marshal(toml.Parser())
|
|
if err != nil {
|
|
log.Fatalf("could not encode session config")
|
|
}
|
|
log.Infof("put the following in your registration.toml:\n%s", string(tomlData))
|
|
}
|
|
return sessionPath, sessionAuthKey, sessionEncKey
|
|
}
|
|
|
|
func startServer(ctx context.Context, handlerChain http.Handler, logger *log.Logger, config *koanf.Koanf) {
|
|
clientCertificateCAFile := config.MustString("security.client.ca-file")
|
|
serverName := config.String("server.name")
|
|
serverPort := config.Int("server.port")
|
|
|
|
clientCertPool := x509.NewCertPool()
|
|
pemBytes, err := ioutil.ReadFile(clientCertificateCAFile)
|
|
if err != nil {
|
|
logger.Fatalf("could not load client CA certificates: %v", err)
|
|
}
|
|
clientCertPool.AppendCertsFromPEM(pemBytes)
|
|
|
|
tlsConfig := &tls.Config{
|
|
ServerName: serverName,
|
|
MinVersion: tls.VersionTLS12,
|
|
ClientAuth: tls.VerifyClientCertIfGiven,
|
|
ClientCAs: clientCertPool,
|
|
}
|
|
server := &http.Server{
|
|
Addr: fmt.Sprintf("%s:%d", serverName, serverPort),
|
|
Handler: handlerChain,
|
|
ReadTimeout: 20 * time.Second,
|
|
WriteTimeout: 20 * time.Second,
|
|
IdleTimeout: 30 * time.Second,
|
|
TLSConfig: tlsConfig,
|
|
}
|
|
|
|
done := make(chan bool)
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, os.Interrupt)
|
|
|
|
go func() {
|
|
<-quit
|
|
logger.Infoln("Server is shutting down...")
|
|
atomic.StoreInt32(&handlers.Healthy, 0)
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
defer cancel()
|
|
|
|
server.SetKeepAlivesEnabled(false)
|
|
if err := server.Shutdown(ctx); err != nil {
|
|
logger.Fatalf("Could not gracefully shutdown the server: %v\n", err)
|
|
}
|
|
close(done)
|
|
}()
|
|
|
|
logger.Infof("Server is ready to handle requests at https://%s/", server.Addr)
|
|
atomic.StoreInt32(&handlers.Healthy, 1)
|
|
if err := server.ListenAndServeTLS(
|
|
config.String("server.certificate"), config.String("server.key"),
|
|
); err != nil && err != http.ErrServerClosed {
|
|
logger.Fatalf("Could not listen on %s: %v\n", server.Addr, err)
|
|
}
|
|
|
|
<-done
|
|
logger.Infoln("Server stopped")
|
|
}
|