You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
oidc-idp/cmd/idp/main.go

240 lines
6.6 KiB
Go

/*
Copyright 2020-2023 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
https://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"
"net/http"
"net/url"
"os"
"os/signal"
"sync/atomic"
"time"
"github.com/go-openapi/runtime/client"
"github.com/gorilla/csrf"
"github.com/knadh/koanf"
hydra "github.com/ory/hydra-client-go/client"
log "github.com/sirupsen/logrus"
"code.cacert.org/cacert/oidc_idp/ui"
"code.cacert.org/cacert/oidc_idp/internal/handlers"
"code.cacert.org/cacert/oidc_idp/internal/services"
)
const (
TimeoutThirty = 30 * time.Second
TimeoutTwenty = 20 * time.Second
DefaultCSRFMaxAge = 600
DefaultServerPort = 3000
)
var (
version = "local"
commit = "unknown"
date = "unknown"
)
func main() {
logger := log.New()
config, err := services.ConfigureApplication(
logger,
"IDP",
map[string]interface{}{
"server.bind_address": "",
"server.name": "idp.cacert.localhost",
"server.port": DefaultServerPort,
"server.key": "idp.cacert.localhost+1-key.pem",
"server.certificate": "idp.cacert.localhost+1.pem",
"security.client.ca-file": "client_ca.pem",
"admin.url": "https://hydra.cacert.localhost:4445/",
"i18n.languages": []string{"en", "de"},
})
if err != nil {
log.Fatalf("error loading configuration: %v", err)
}
logger.WithFields(log.Fields{
"version": version, "commit": commit, "date": date,
}).Info("Starting CAcert OpenID Connect Identity Provider")
logger.Infoln("Server is starting")
bundle, catalog := services.InitI18n(logger, config.Strings("i18n.languages"))
if err = services.AddMessages(catalog); err != nil {
logger.Fatalf("could not add messages for i18n: %v", err)
}
adminURL, err := url.Parse(config.MustString("admin.url"))
if err != nil {
logger.Fatalf("error parsing admin URL: %v", err)
}
tlsClientConfig := &tls.Config{MinVersion: tls.VersionTLS12}
if config.Exists("api-client.rootCAs") {
rootCAFile := config.MustString("api-client.rootCAs")
caCertPool := x509.NewCertPool()
pemBytes, err := os.ReadFile(rootCAFile)
if err != nil {
log.Fatalf("could not read CA certificate file: %v", err)
}
caCertPool.AppendCertsFromPEM(pemBytes)
tlsClientConfig.RootCAs = caCertPool
}
tlsClientTransport := &http.Transport{TLSClientConfig: tlsClientConfig}
httpClient := &http.Client{Transport: tlsClientTransport}
clientTransport := client.NewWithClient(
adminURL.Host,
adminURL.Path,
[]string{adminURL.Scheme},
httpClient,
)
adminClient := hydra.New(clientTransport, nil)
loginHandler := handlers.NewLoginHandler(logger, bundle, catalog, adminClient.Admin)
consentHandler := handlers.NewConsentHandler(logger, bundle, catalog, adminClient.Admin)
logoutHandler := handlers.NewLogoutHandler(logger, adminClient.Admin)
logoutSuccessHandler := handlers.NewLogoutSuccessHandler(logger, bundle, catalog)
errorHandler := handlers.NewErrorHandler()
staticFiles := http.FileServer(http.FS(ui.Static))
router := http.NewServeMux()
router.Handle("/login", loginHandler)
router.Handle("/consent", consentHandler)
router.Handle("/logout", logoutHandler)
router.Handle("/error", errorHandler)
router.Handle("/logout-successful", logoutSuccessHandler)
router.Handle("/health", handlers.NewHealthHandler())
router.Handle("/images/", staticFiles)
router.Handle("/css/", staticFiles)
router.Handle("/js/", staticFiles)
if err != nil {
logger.Fatal(err)
}
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(DefaultCSRFMaxAge))
errorMiddleware, err := handlers.ErrorHandling(
logger,
ui.Templates,
bundle,
catalog,
)
if err != nil {
logger.Fatalf("could not initialize request error handling: %v", err)
}
handlerChain := tracing(logging(hsts(errorMiddleware(csrfProtect(router)))))
startServer(context.Background(), handlerChain, logger, config)
}
func startServer(ctx context.Context, handlerChain http.Handler, logger *log.Logger, config *koanf.Koanf) {
clientCertificateCAFile := config.MustString("security.client.ca-file")
serverBindAddress := config.String("server.bind_address")
serverName := config.String("server.name")
serverPort := config.Int("server.port")
clientCertPool := x509.NewCertPool()
pemBytes, err := os.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", serverBindAddress, serverPort),
Handler: handlerChain,
ReadTimeout: TimeoutTwenty,
WriteTimeout: TimeoutTwenty,
IdleTimeout: TimeoutThirty,
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, TimeoutThirty)
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.WithFields(log.Fields{
"address": server.Addr,
"url": fmt.Sprintf("https://%s:%d/", serverName, serverPort),
}).Info("Server is ready to handle requests")
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")
}