oidc-idp/cmd/idp/main.go

363 lines
10 KiB
Go
Raw Normal View History

/*
Copyright CAcert Inc.
2023-05-13 11:27:19 +00:00
SPDX-License-Identifier: Apache-2.0
2023-05-13 11:27:19 +00:00
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
2023-05-13 11:27:19 +00:00
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"
2021-09-19 17:54:00 +00:00
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/toml"
"github.com/knadh/koanf/providers/confmap"
hydra "github.com/ory/hydra-client-go/v2"
2023-07-29 20:00:53 +00:00
"code.cacert.org/cacert/oidc-idp/internal/handlers"
"code.cacert.org/cacert/oidc-idp/internal/services"
"code.cacert.org/cacert/oidc-idp/ui"
)
2023-05-13 11:27:19 +00:00
const (
IdleTimeout = 30 * time.Second
ShutdownTimeout = 30 * time.Second
ReadTimeOut = 20 * time.Second
WriteTimeOut = 20 * time.Second
2023-05-13 11:27:19 +00:00
DefaultCSRFMaxAge = 600
httpsDefaultPort = 443
sessionKeyLength = 32
sessionAuthKeyLength = 64
minCSRFKeyLength = 64
2023-05-13 11:27:19 +00:00
)
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)
2023-05-13 11:27:19 +00:00
2023-07-29 17:47:51 +00:00
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)
2023-05-13 11:27:19 +00:00
}
services.InitSessionStore(sessionAuthKey, sessionEncKey)
2023-07-29 18:40:36 +00:00
clientTransport, err := configureAdminClient(config)
if err != nil {
logger.Error("could not configure Hydra admin client", "error", err)
os.Exit(1)
}
tc := handlers.PopulateTemplateCache()
2023-05-13 11:27:19 +00:00
needsAuth := handlers.NewAuthMiddleware(logger, tc, i18nService).NeedsAuth
indexHandler := handlers.NewIndex(logger, tc, i18nService)
2024-05-11 20:27:22 +00:00
manageConsentHandler := handlers.NewManageConsent(logger, tc, i18nService, clientTransport.OAuth2API)
revokeConsentHandler := handlers.NewRevokeConsent(logger, tc, i18nService, clientTransport.OAuth2API)
2024-05-11 20:27:22 +00:00
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)
2022-08-22 16:50:59 +00:00
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)
2023-05-13 11:27:19 +00:00
nextRequestID := func() string {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
2023-05-13 11:27:19 +00:00
tracing := handlers.Tracing(nextRequestID)
logging := handlers.Logging(logger)
hsts := handlers.EnableHSTS()
csrfProtect := csrf.Protect(
csrfKey,
csrf.Secure(true),
csrf.SameSite(csrf.SameSiteStrictMode),
2023-05-13 11:27:19 +00:00
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)
}
2021-09-19 17:54:00 +00:00
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)
}
2021-09-19 17:54:00 +00:00
}
func configureAdminClient(config *koanf.Koanf) (*hydra.APIClient, error) {
2023-07-29 18:40:36 +00:00
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()}
2023-07-29 18:40:36 +00:00
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
2023-07-29 18:40:36 +00:00
}
func startServer(logger *slog.Logger, config *koanf.Koanf, handlerChain http.Handler) error {
2021-09-19 17:54:00 +00:00
clientCertificateCAFile := config.MustString("security.client.ca-file")
serverBindAddress := config.String("server.bind_address")
2021-09-19 17:54:00 +00:00
serverName := config.String("server.name")
serverPort := config.Int("server.port")
clientCertPool := x509.NewCertPool()
2023-05-13 11:27:19 +00:00
pemBytes, err := os.ReadFile(clientCertificateCAFile)
if err != nil {
return fmt.Errorf("could not load client CA certificates: %w", err)
}
2023-05-13 11:27:19 +00:00
clientCertPool.AppendCertsFromPEM(pemBytes)
tlsConfig := &tls.Config{
2021-09-19 17:54:00 +00:00
ServerName: serverName,
MinVersion: tls.VersionTLS12,
ClientAuth: tls.VerifyClientCertIfGiven,
ClientCAs: clientCertPool,
}
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", serverBindAddress, serverPort),
2021-09-19 17:54:00 +00:00
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)
2023-05-13 11:27:19 +00:00
if err := server.Shutdown(ctx); err != nil {
logger.Error("could not shutdown server gracefully", "error", err)
}
2023-05-13 11:27:19 +00:00
close(done)
}()
logger.Info(
"Server is ready to handle requests",
"address", server.Addr, "url", publicAddress(serverName, serverPort),
)
atomic.StoreInt32(&handlers.Healthy, 1)
2023-05-13 11:27:19 +00:00
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
}