oidc-idp/cmd/idp/main.go

362 lines
10 KiB
Go

/*
Copyright 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"
"errors"
"fmt"
"log/slog"
"net/http"
"net/url"
"os"
"os/signal"
"sync/atomic"
"time"
"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/v2"
"code.cacert.org/cacert/oidc-idp/internal/handlers"
"code.cacert.org/cacert/oidc-idp/internal/services"
"code.cacert.org/cacert/oidc-idp/ui"
)
const (
IdleTimeout = 30 * time.Second
ShutdownTimeout = 30 * time.Second
ReadTimeOut = 20 * time.Second
WriteTimeOut = 20 * time.Second
DefaultCSRFMaxAge = 600
httpsDefaultPort = 443
sessionKeyLength = 32
sessionAuthKeyLength = 64
minCSRFKeyLength = 32
)
var (
version = "local"
commit = "unknown"
date = "unknown"
)
func main() {
var (
logLevel = new(slog.LevelVar)
logHandler slog.Handler
logger *slog.Logger
)
logHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel})
logger = slog.New(logHandler)
slog.SetDefault(logger)
config, err := services.ConfigureApplication(logger, "IDP", services.DefaultConfig)
if err != nil {
logger.Error("error loading configuration", "err", err)
os.Exit(1)
}
if level := config.Bytes("log.level"); level != nil {
err := logLevel.UnmarshalText(level)
if err != nil {
logger.Error("could not parse log level", "error", err)
os.Exit(1)
}
slog.SetLogLoggerLevel(logLevel.Level())
}
if config.Bool("log.json") {
logHandler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel})
logger = slog.New(logHandler)
slog.SetDefault(logger)
}
logger.Info("Starting CAcert OpenID Connect Identity Provider",
"version", version, "commit", commit, "date", date,
)
logger.Info("Server is starting")
i18nService := services.InitI18n(logger, config.Strings("i18n.languages"))
if err = i18nService.AddMessages(); err != nil {
logger.Error("could not add messages for i18n", "error", err)
os.Exit(1)
}
sessionAuthKey, sessionEncKey, csrfKey, err := configureSessionParameters(config)
if err != nil {
logger.Error("could not configure session parameters", "error", err)
os.Exit(1)
}
services.InitSessionStore(sessionAuthKey, sessionEncKey)
clientTransport, err := configureAdminClient(config)
if err != nil {
logger.Error("could not configure Hydra admin client", "error", err)
os.Exit(1)
}
tc := handlers.PopulateTemplateCache()
needsAuth := handlers.NewAuthMiddleware(logger, tc, i18nService).NeedsAuth
indexHandler := handlers.NewIndex(logger, tc, i18nService)
manageConsentHandler := handlers.NewManageConsent(logger, tc, i18nService, clientTransport.OAuth2API)
revokeConsentHandler := handlers.NewRevokeConsent(logger, tc, i18nService, clientTransport.OAuth2API)
loginHandler := handlers.NewLoginHandler(logger, tc, i18nService, clientTransport.OAuth2API)
consentHandler := handlers.NewConsentHandler(logger, tc, i18nService, clientTransport.OAuth2API)
logoutHandler := handlers.NewLogout(logger, clientTransport.OAuth2API)
logoutSuccessHandler := handlers.NewLogoutSuccess(logger, tc, i18nService)
errorHandler := handlers.NewErrorHandler(logger, i18nService)
staticFiles := http.FileServer(http.FS(ui.Static))
router := http.NewServeMux()
router.HandleFunc("/", needsAuth(indexHandler))
router.Handle("/manage-consent", needsAuth(manageConsentHandler))
router.Handle("/revoke-consent/", needsAuth(revokeConsentHandler))
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)
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, tc, i18nService)
if err != nil {
logger.Error("could not initialize request error handling", "error", err)
os.Exit(1)
}
handlerChain := tracing(logging(hsts(errorMiddleware(csrfProtect(router)))))
err = startServer(logger, config, handlerChain)
if err != nil {
logger.Error("server start failed", "error", err)
os.Exit(1)
}
}
func configureAdminClient(config *koanf.Koanf) (*hydra.APIClient, error) {
adminURL, err := url.Parse(config.MustString("admin.url"))
if err != nil {
return nil, fmt.Errorf("error parsing admin URL: %w", err)
}
configuration := hydra.NewConfiguration()
configuration.Servers = []hydra.ServerConfiguration{
{
URL: adminURL.String(),
},
}
tlsClientConfig := &tls.Config{MinVersion: tls.VersionTLS12, ServerName: adminURL.Hostname()}
if config.Exists("api-client.rootCAs") {
rootCAFile := config.MustString("api-client.rootCAs")
caCertPool := x509.NewCertPool()
pemBytes, err := os.ReadFile(rootCAFile)
if err != nil {
return nil, fmt.Errorf("could not read CA certificate file: %w", err)
}
caCertPool.AppendCertsFromPEM(pemBytes)
tlsClientConfig.RootCAs = caCertPool
}
tlsClientTransport := &http.Transport{TLSClientConfig: tlsClientConfig}
c := hydra.NewAPIClient(configuration)
configuration.HTTPClient.Transport = tlsClientTransport
return c, nil
}
func startServer(logger *slog.Logger, config *koanf.Koanf, handlerChain http.Handler) error {
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 {
return fmt.Errorf("could not load client CA certificates: %w", 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: ReadTimeOut,
WriteTimeout: WriteTimeOut,
IdleTimeout: IdleTimeout,
TLSConfig: tlsConfig,
}
done := make(chan bool)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
go func() {
<-quit
logger.Info("Server is shutting down...")
atomic.StoreInt32(&handlers.Healthy, 0)
ctx, cancel := context.WithTimeout(context.Background(), ShutdownTimeout)
defer cancel()
server.SetKeepAlivesEnabled(false)
if err := server.Shutdown(ctx); err != nil {
logger.Error("could not shutdown server gracefully", "error", err)
}
close(done)
}()
logger.Info(
"Server is ready to handle requests",
"address", server.Addr, "url", publicAddress(serverName, serverPort),
)
atomic.StoreInt32(&handlers.Healthy, 1)
if err := server.ListenAndServeTLS(
config.String("server.certificate"), config.String("server.key"),
); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("could not listen on configured server address", "server_addr", server.Addr)
return fmt.Errorf("could not create listener: %w", err)
}
<-done
logger.Info("Server stopped")
return nil
}
func publicAddress(serverName string, serverPort int) string {
if serverPort != httpsDefaultPort {
return fmt.Sprintf("https://%s:%d/", serverName, serverPort)
}
return fmt.Sprintf("https://%s/", serverName)
}
func configureSessionParameters(config *koanf.Koanf) ([]byte, []byte, []byte, error) { //nolint:cyclop
sessionAuthKey, err := base64.StdEncoding.DecodeString(config.String("session.auth-key"))
if err != nil {
return nil, nil, nil, fmt.Errorf("could not decode session auth key: %w", err)
}
sessionEncKey, err := base64.StdEncoding.DecodeString(config.String("session.enc-key"))
if err != nil {
return nil, nil, nil, fmt.Errorf("could not decode session encryption key: %w", err)
}
csrfKey, err := base64.StdEncoding.DecodeString(config.String("security.csrf.key"))
if err != nil {
return nil, nil, nil, fmt.Errorf("could not decode CSRF key bytes: %w", err)
}
generated := false
if len(sessionAuthKey) != sessionAuthKeyLength {
sessionAuthKey, err = services.GenerateKey(sessionAuthKeyLength)
if err != nil {
return nil, nil, nil, fmt.Errorf("could not generate session authentication key: %w", err)
}
generated = true
}
if len(sessionEncKey) != sessionKeyLength {
sessionEncKey, err = services.GenerateKey(sessionKeyLength)
if err != nil {
return nil, nil, nil, fmt.Errorf("could not generate session encryption key: %w", err)
}
generated = true
}
if len(csrfKey) < minCSRFKeyLength {
csrfKey, err = services.GenerateKey(minCSRFKeyLength)
if err != nil {
return nil, nil, nil, fmt.Errorf("could not generate CSRF key: %w", err)
}
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),
"security.csrf.key": base64.StdEncoding.EncodeToString(csrfKey),
}, "."), nil)
tomlData, err := config.Marshal(toml.Parser())
if err != nil {
return nil, nil, nil, fmt.Errorf("could not encode session config: %w", err)
}
slog.Info("generated configuration values, put the following into your idp.toml")
fmt.Printf("------\n%s------\n", string(tomlData)) //nolint:forbidigo
}
return sessionAuthKey, sessionEncKey, csrfKey, nil
}