2021-09-11 11:37:31 +00:00
|
|
|
/*
|
2024-05-12 10:12:27 +00:00
|
|
|
Copyright CAcert Inc.
|
2023-07-29 15:46:33 +00:00
|
|
|
SPDX-License-Identifier: Apache-2.0
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2023-07-29 15:46:33 +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
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
https://www.apache.org/licenses/LICENSE-2.0
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2023-07-29 15:46:33 +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.
|
2021-09-11 11:37:31 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
2024-05-12 10:02:27 +00:00
|
|
|
"log/slog"
|
2021-09-11 11:37:31 +00:00
|
|
|
"net/http"
|
2023-07-29 15:46:33 +00:00
|
|
|
"os"
|
2021-09-11 11:37:31 +00:00
|
|
|
"time"
|
|
|
|
|
2021-09-19 17:55:00 +00:00
|
|
|
"github.com/knadh/koanf"
|
2021-09-11 11:37:31 +00:00
|
|
|
"github.com/knadh/koanf/parsers/toml"
|
|
|
|
"github.com/knadh/koanf/providers/confmap"
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2024-05-12 10:12:27 +00:00
|
|
|
"code.cacert.org/cacert/oidc-demo-app/ui"
|
|
|
|
|
2023-07-29 15:53:26 +00:00
|
|
|
"code.cacert.org/cacert/oidc-demo-app/internal/handlers"
|
|
|
|
"code.cacert.org/cacert/oidc-demo-app/internal/services"
|
2023-07-29 15:46:33 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
defaultReadTimeout = 5 * time.Second
|
|
|
|
defaultWriteTimeout = 10 * time.Second
|
|
|
|
defaultIdleTimeout = 15 * time.Second
|
|
|
|
|
|
|
|
sessionKeyLength = 32
|
|
|
|
sessionAuthKeyLength = 64
|
2021-09-11 11:37:31 +00:00
|
|
|
)
|
|
|
|
|
2023-07-29 16:34:40 +00:00
|
|
|
var (
|
|
|
|
version = "local"
|
|
|
|
commit = "unknown"
|
|
|
|
date = "unknown"
|
|
|
|
)
|
|
|
|
|
2023-08-03 14:46:28 +00:00
|
|
|
type StaticFSWrapper struct {
|
|
|
|
http.FileSystem
|
|
|
|
ModTime time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *StaticFSWrapper) Open(name string) (http.File, error) {
|
|
|
|
file, err := f.FileSystem.Open(name)
|
|
|
|
|
|
|
|
return &StaticFileWrapper{File: file, fixedModTime: f.ModTime}, err //nolint:wrapcheck
|
|
|
|
}
|
|
|
|
|
|
|
|
type StaticFileWrapper struct {
|
|
|
|
http.File
|
|
|
|
fixedModTime time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *StaticFileWrapper) Stat() (os.FileInfo, error) {
|
|
|
|
fileInfo, err := f.File.Stat()
|
|
|
|
|
|
|
|
return &StaticFileInfoWrapper{FileInfo: fileInfo, fixedModTime: f.fixedModTime}, err //nolint:wrapcheck
|
|
|
|
}
|
|
|
|
|
|
|
|
type StaticFileInfoWrapper struct {
|
|
|
|
os.FileInfo
|
|
|
|
fixedModTime time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *StaticFileInfoWrapper) ModTime() time.Time {
|
|
|
|
return f.fixedModTime
|
|
|
|
}
|
|
|
|
|
2024-05-12 10:12:27 +00:00
|
|
|
func main() { //nolint:cyclop
|
2024-05-12 10:02:27 +00:00
|
|
|
var (
|
|
|
|
logLevel = new(slog.LevelVar)
|
|
|
|
logHandler slog.Handler
|
|
|
|
logger *slog.Logger
|
2023-07-29 15:46:33 +00:00
|
|
|
)
|
2024-05-12 10:02:27 +00:00
|
|
|
|
|
|
|
logHandler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel})
|
|
|
|
logger = slog.New(logHandler)
|
|
|
|
slog.SetDefault(logger)
|
|
|
|
|
|
|
|
config, err := services.ConfigureApplication("RESOURCE_APP", services.DefaultConfiguration)
|
2021-09-11 11:37:31 +00:00
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Error("error loading configuration", "error", err)
|
|
|
|
os.Exit(1)
|
2021-09-11 11:37:31 +00:00
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
if level := config.Bytes("log.level"); level != nil {
|
|
|
|
if err := logLevel.UnmarshalText(level); err != nil {
|
|
|
|
logger.Error("could not parse log level", "error", err)
|
|
|
|
os.Exit(1)
|
2023-07-29 15:46:33 +00:00
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
slog.SetLogLoggerLevel(logLevel.Level())
|
2023-07-29 15:46:33 +00:00
|
|
|
}
|
|
|
|
|
2023-07-29 15:58:09 +00:00
|
|
|
if config.Bool("log.json") {
|
2024-05-12 10:02:27 +00:00
|
|
|
logHandler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: logLevel})
|
|
|
|
logger = slog.New(logHandler)
|
|
|
|
slog.SetDefault(logger)
|
2023-07-29 15:58:09 +00:00
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
logLogger := slog.NewLogLogger(logger.Handler(), logLevel.Level())
|
|
|
|
|
2024-05-12 10:12:27 +00:00
|
|
|
oidcServer := config.MustString("oidc.server")
|
|
|
|
oidcClientID := config.MustString("oidc.client-id")
|
|
|
|
oidcClientSecret := config.MustString("oidc.client-secret")
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Info(
|
|
|
|
"Starting CAcert OpenID Connect demo application",
|
|
|
|
"version", version, "commit", commit, "date", date,
|
|
|
|
)
|
|
|
|
logger.Info("Server is starting")
|
2023-07-29 16:34:40 +00:00
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
bundle, catalog := services.InitI18n(logger, config.Strings("i18n.languages"))
|
|
|
|
|
|
|
|
services.AddMessages(catalog)
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
tlsClientConfig, err := getTLSConfig(config)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("error loading tls config", "error", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2021-09-11 11:37:31 +00:00
|
|
|
|
|
|
|
apiTransport := &http.Transport{TLSClientConfig: tlsClientConfig}
|
|
|
|
apiClient := &http.Client{Transport: apiTransport}
|
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
oidcInfo, err := services.DiscoverOIDC(logger, &services.OidcParams{
|
2021-09-11 11:37:31 +00:00
|
|
|
OidcServer: oidcServer,
|
2023-07-29 15:46:33 +00:00
|
|
|
OidcClientID: oidcClientID,
|
2021-09-11 11:37:31 +00:00
|
|
|
OidcClientSecret: oidcClientSecret,
|
|
|
|
APIClient: apiClient,
|
2023-07-29 15:46:33 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Error("OpenID Connect discovery failed", "error", err)
|
|
|
|
os.Exit(1)
|
2021-09-11 11:37:31 +00:00
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
sessionPath, sessionAuthKey, sessionEncKey, err := configureSessionParameters(logger, config)
|
2024-05-12 10:12:27 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Error("error configuring session parameters", "error", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2024-05-12 10:02:27 +00:00
|
|
|
|
2024-05-12 10:12:27 +00:00
|
|
|
if err := services.InitSessionStore(sessionPath, sessionAuthKey, sessionEncKey); err != nil {
|
|
|
|
logger.Error("could not initialize session store", "error", err)
|
2024-05-12 10:02:27 +00:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
authMiddleware := handlers.Authenticate(logger, oidcInfo.OAuth2Config)
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
publicURL := buildPublicURL(config.MustString("server.name"), config.MustInt("server.port"))
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2023-08-03 14:46:28 +00:00
|
|
|
tokenInfoService, err := services.InitTokenInfoService(logger, oidcInfo)
|
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Error("could not initialize token info service", "error", err)
|
|
|
|
os.Exit(1)
|
2023-08-03 14:46:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
indexHandler, err := handlers.NewIndexHandler(logger, bundle, catalog, oidcInfo, publicURL, tokenInfoService)
|
2021-09-11 11:37:31 +00:00
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Error("could not initialize index handler", "error", err)
|
|
|
|
os.Exit(1)
|
2021-09-11 11:37:31 +00:00
|
|
|
}
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2023-08-03 14:46:28 +00:00
|
|
|
protectedResource, err := handlers.NewProtectedResourceHandler(
|
|
|
|
logger, bundle, catalog, oidcInfo, publicURL, tokenInfoService,
|
|
|
|
)
|
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Error("could not initialize protected resource handler", "error", err)
|
2023-08-03 14:46:28 +00:00
|
|
|
}
|
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
callbackHandler := handlers.NewCallbackHandler(logger, oidcInfo.KeySet, oidcInfo.OAuth2Config)
|
2021-09-11 11:37:31 +00:00
|
|
|
afterLogoutHandler := handlers.NewAfterLogoutHandler(logger)
|
2023-08-03 14:46:28 +00:00
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
staticFiles, err := staticFileHandler()
|
|
|
|
if err != nil {
|
|
|
|
logger.Error("could not initialize static file handler", "error", err)
|
|
|
|
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2021-09-11 11:37:31 +00:00
|
|
|
|
|
|
|
router := http.NewServeMux()
|
2023-08-03 14:46:28 +00:00
|
|
|
router.Handle("/", indexHandler)
|
|
|
|
router.Handle("/login", authMiddleware(handlers.NewLoginHandler()))
|
|
|
|
router.Handle("/protected", authMiddleware(protectedResource))
|
2021-09-11 11:37:31 +00:00
|
|
|
router.Handle("/callback", callbackHandler)
|
|
|
|
router.Handle("/after-logout", afterLogoutHandler)
|
|
|
|
router.Handle("/health", handlers.NewHealthHandler())
|
2023-08-03 14:46:28 +00:00
|
|
|
router.HandleFunc("/images/", staticFiles)
|
|
|
|
router.HandleFunc("/css/", staticFiles)
|
|
|
|
router.HandleFunc("/js/", staticFiles)
|
2021-09-11 11:37:31 +00:00
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
nextRequestID := func() string {
|
2021-09-11 11:37:31 +00:00
|
|
|
return fmt.Sprintf("%d", time.Now().UnixNano())
|
|
|
|
}
|
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
tracing := handlers.Tracing(nextRequestID)
|
2024-05-12 10:02:27 +00:00
|
|
|
logging := handlers.Logging(logLogger)
|
2021-09-11 11:37:31 +00:00
|
|
|
hsts := handlers.EnableHSTS()
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2023-07-30 14:48:26 +00:00
|
|
|
errorMiddleware, err := handlers.ErrorHandling(logger, bundle, catalog)
|
2021-09-11 11:37:31 +00:00
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Error("could not initialize request error handling", "error", err)
|
|
|
|
os.Exit(1)
|
2021-09-11 11:37:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
tlsConfig := &tls.Config{
|
|
|
|
ServerName: config.String("server.name"),
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
}
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2021-09-11 11:37:31 +00:00
|
|
|
server := &http.Server{
|
2023-07-29 15:46:33 +00:00
|
|
|
Addr: fmt.Sprintf("%s:%d", config.String("server.bind_address"), config.Int("server.port")),
|
2021-09-11 11:37:31 +00:00
|
|
|
Handler: tracing(logging(hsts(errorMiddleware(router)))),
|
2023-07-29 15:46:33 +00:00
|
|
|
ReadTimeout: defaultReadTimeout,
|
|
|
|
WriteTimeout: defaultWriteTimeout,
|
|
|
|
IdleTimeout: defaultIdleTimeout,
|
2021-09-11 11:37:31 +00:00
|
|
|
TLSConfig: tlsConfig,
|
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
if err := handlers.StartApplication(context.Background(), logger, server, publicURL, config); err != nil {
|
|
|
|
logger.Error("could not start application", "error", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
2023-07-29 15:46:33 +00:00
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
func staticFileHandler() (func(w http.ResponseWriter, r *http.Request), error) {
|
2023-08-03 14:46:28 +00:00
|
|
|
stat, err := os.Stat(os.Args[0])
|
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
return nil, fmt.Errorf("could not use stat on binary: %w", err)
|
2023-08-03 14:46:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fileServer := http.FileServer(&StaticFSWrapper{FileSystem: http.FS(ui.Static), ModTime: stat.ModTime()})
|
|
|
|
|
|
|
|
staticFiles := func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Del("Expires")
|
|
|
|
w.Header().Del("Pragma")
|
|
|
|
w.Header().Set("Cache-Control", "max-age=3600")
|
|
|
|
|
|
|
|
fileServer.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
return staticFiles, nil
|
2023-08-03 14:46:28 +00:00
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
func getTLSConfig(config *koanf.Koanf) (*tls.Config, error) {
|
2023-08-03 14:46:28 +00:00
|
|
|
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 {
|
2024-05-12 10:02:27 +00:00
|
|
|
return nil, fmt.Errorf("could not read CA certificate file: %w", err)
|
2023-08-03 14:46:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
caCertPool.AppendCertsFromPEM(pemBytes)
|
|
|
|
tlsClientConfig.RootCAs = caCertPool
|
|
|
|
}
|
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
return tlsClientConfig, nil
|
2023-08-03 14:46:28 +00:00
|
|
|
}
|
|
|
|
|
2023-07-29 15:46:33 +00:00
|
|
|
func buildPublicURL(hostname string, port int) string {
|
|
|
|
const defaultHTTPSPort = 443
|
|
|
|
|
|
|
|
if port != defaultHTTPSPort {
|
|
|
|
return fmt.Sprintf("https://%s:%d", hostname, port)
|
|
|
|
}
|
|
|
|
|
|
|
|
return fmt.Sprintf("https://%s", hostname)
|
2021-09-11 11:37:31 +00:00
|
|
|
}
|
2021-09-19 17:55:00 +00:00
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
func configureSessionParameters(logger *slog.Logger, config *koanf.Koanf) (string, []byte, []byte, error) {
|
2021-09-19 17:55:00 +00:00
|
|
|
sessionPath := config.MustString("session.path")
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2021-09-19 17:55:00 +00:00
|
|
|
sessionAuthKey, err := base64.StdEncoding.DecodeString(config.String("session.auth-key"))
|
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
return "", nil, nil, fmt.Errorf("could not decode session authentication key: %w", err)
|
2021-09-19 17:55:00 +00:00
|
|
|
}
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2021-09-19 17:55:00 +00:00
|
|
|
sessionEncKey, err := base64.StdEncoding.DecodeString(config.String("session.enc-key"))
|
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
return "", nil, nil, fmt.Errorf("could not decode session encryption key: %w", err)
|
2021-09-19 17:55:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
generated := false
|
2023-07-29 15:46:33 +00:00
|
|
|
|
|
|
|
if len(sessionAuthKey) != sessionAuthKeyLength {
|
2024-05-12 10:02:27 +00:00
|
|
|
sessionAuthKey, err = services.GenerateKey(sessionAuthKeyLength)
|
|
|
|
if err != nil {
|
|
|
|
return "", nil, nil, fmt.Errorf("could not generate session authentication key: %w", err)
|
|
|
|
}
|
|
|
|
|
2021-09-19 17:55:00 +00:00
|
|
|
generated = true
|
|
|
|
}
|
2023-07-29 15:46:33 +00:00
|
|
|
|
|
|
|
if len(sessionEncKey) != sessionKeyLength {
|
2024-05-12 10:02:27 +00:00
|
|
|
sessionEncKey, err = services.GenerateKey(sessionKeyLength)
|
|
|
|
if err != nil {
|
|
|
|
return "", nil, nil, fmt.Errorf("could not generate session encryption key: %w", err)
|
|
|
|
}
|
|
|
|
|
2021-09-19 17:55:00 +00:00
|
|
|
generated = true
|
|
|
|
}
|
|
|
|
|
|
|
|
if generated {
|
|
|
|
_ = config.Load(confmap.Provider(map[string]interface{}{
|
|
|
|
"session.auth-key": sessionAuthKey,
|
|
|
|
"session.enc-key": sessionEncKey,
|
|
|
|
}, "."), nil)
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2021-09-19 17:55:00 +00:00
|
|
|
tomlData, err := config.Marshal(toml.Parser())
|
|
|
|
if err != nil {
|
2024-05-12 10:02:27 +00:00
|
|
|
return "", nil, nil, fmt.Errorf("could not encode session configuration: %w", err)
|
2021-09-19 17:55:00 +00:00
|
|
|
}
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
logger.Info("put the following in your resource_app.toml")
|
|
|
|
fmt.Print(string(tomlData)) //nolint:forbidigo
|
2021-09-19 17:55:00 +00:00
|
|
|
}
|
2023-07-29 15:46:33 +00:00
|
|
|
|
2024-05-12 10:02:27 +00:00
|
|
|
return sessionPath, sessionAuthKey, sessionEncKey, nil
|
2021-09-19 17:55:00 +00:00
|
|
|
}
|