oidc-demo-app/cmd/app/main.go

301 lines
8.2 KiB
Go
Raw Normal View History

/*
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"
"os"
"time"
2021-09-19 17:55:00 +00:00
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/toml"
"github.com/knadh/koanf/providers/confmap"
log "github.com/sirupsen/logrus"
"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"
)
const (
defaultReadTimeout = 5 * time.Second
defaultWriteTimeout = 10 * time.Second
defaultIdleTimeout = 15 * time.Second
sessionKeyLength = 32
sessionAuthKeyLength = 64
)
2023-07-29 16:34:40 +00:00
var (
version = "local"
commit = "unknown"
date = "unknown"
)
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
}
func main() {
logger := log.New()
config, err := services.ConfigureApplication(
logger,
"RESOURCE_APP",
services.DefaultConfiguration,
)
if err != nil {
log.Fatalf("error loading configuration: %v", err)
}
oidcServer := config.MustString("oidc.server")
oidcClientID := config.MustString("oidc.client-id")
oidcClientSecret := config.MustString("oidc.client-secret")
if level := config.String("log.level"); level != "" {
logLevel, err := log.ParseLevel(level)
if err != nil {
logger.WithError(err).Fatal("could not parse log level")
}
logger.SetLevel(logLevel)
}
2023-07-29 15:58:09 +00:00
if config.Bool("log.json") {
logger.SetFormatter(&log.JSONFormatter{})
}
2023-07-29 16:34:40 +00:00
logger.WithFields(log.Fields{
"version": version, "commit": commit, "date": date,
2023-07-29 18:23:55 +00:00
}).Info("Starting CAcert OpenID Connect demo application")
2023-07-29 16:34:40 +00:00
logger.Infoln("Server is starting")
bundle, catalog := services.InitI18n(logger, config.Strings("i18n.languages"))
services.AddMessages(catalog)
tlsClientConfig := getTLSConfig(config)
apiTransport := &http.Transport{TLSClientConfig: tlsClientConfig}
apiClient := &http.Client{Transport: apiTransport}
oidcInfo, err := services.DiscoverOIDC(logger, &services.OidcParams{
OidcServer: oidcServer,
OidcClientID: oidcClientID,
OidcClientSecret: oidcClientSecret,
APIClient: apiClient,
})
if err != nil {
logger.WithError(err).Fatal("OpenID Connect discovery failed")
}
2022-01-16 13:02:20 +00:00
sessionPath, sessionAuthKey, sessionEncKey := configureSessionParameters(config)
services.InitSessionStore(logger, sessionPath, sessionAuthKey, sessionEncKey)
authMiddleware := handlers.Authenticate(logger, oidcInfo.OAuth2Config, oidcClientID)
publicURL := buildPublicURL(config.MustString("server.name"), config.MustInt("server.port"))
tokenInfoService, err := services.InitTokenInfoService(logger, oidcInfo)
if err != nil {
logger.WithError(err).Fatal("could not initialize token info service")
}
indexHandler, err := handlers.NewIndexHandler(logger, bundle, catalog, oidcInfo, publicURL, tokenInfoService)
if err != nil {
2023-07-29 16:34:40 +00:00
logger.WithError(err).Fatal("could not initialize index handler")
}
protectedResource, err := handlers.NewProtectedResourceHandler(
logger, bundle, catalog, oidcInfo, publicURL, tokenInfoService,
)
if err != nil {
logger.WithError(err).Fatal("could not initialize protected resource handler")
}
callbackHandler := handlers.NewCallbackHandler(logger, oidcInfo.KeySet, oidcInfo.OAuth2Config)
afterLogoutHandler := handlers.NewAfterLogoutHandler(logger)
staticFiles := staticFileHandler(logger)
router := http.NewServeMux()
router.Handle("/", indexHandler)
router.Handle("/login", authMiddleware(handlers.NewLoginHandler()))
router.Handle("/protected", authMiddleware(protectedResource))
router.Handle("/callback", callbackHandler)
router.Handle("/after-logout", afterLogoutHandler)
router.Handle("/health", handlers.NewHealthHandler())
router.HandleFunc("/images/", staticFiles)
router.HandleFunc("/css/", staticFiles)
router.HandleFunc("/js/", staticFiles)
nextRequestID := func() string {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
tracing := handlers.Tracing(nextRequestID)
logging := handlers.Logging(logger)
hsts := handlers.EnableHSTS()
errorMiddleware, err := handlers.ErrorHandling(logger, bundle, catalog)
if err != nil {
2023-07-29 16:34:40 +00:00
logger.WithError(err).Fatal("could not initialize request error handling")
}
tlsConfig := &tls.Config{
ServerName: config.String("server.name"),
MinVersion: tls.VersionTLS12,
}
server := &http.Server{
Addr: fmt.Sprintf("%s:%d", config.String("server.bind_address"), config.Int("server.port")),
Handler: tracing(logging(hsts(errorMiddleware(router)))),
ReadTimeout: defaultReadTimeout,
WriteTimeout: defaultWriteTimeout,
IdleTimeout: defaultIdleTimeout,
TLSConfig: tlsConfig,
}
handlers.StartApplication(context.Background(), logger, server, publicURL, config)
}
func staticFileHandler(logger *log.Logger) func(w http.ResponseWriter, r *http.Request) {
stat, err := os.Stat(os.Args[0])
if err != nil {
logger.WithError(err).Fatal("could not use stat on binary")
}
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)
}
return staticFiles
}
func getTLSConfig(config *koanf.Koanf) *tls.Config {
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
}
return tlsClientConfig
}
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-19 17:55:00 +00:00
2022-01-16 13:02:20 +00:00
func configureSessionParameters(config *koanf.Koanf) (string, []byte, []byte) {
2021-09-19 17:55:00 +00:00
sessionPath := config.MustString("session.path")
2021-09-19 17:55:00 +00:00
sessionAuthKey, err := base64.StdEncoding.DecodeString(config.String("session.auth-key"))
if err != nil {
log.WithError(err).Fatal("could not decode session auth key")
2021-09-19 17:55:00 +00:00
}
2021-09-19 17:55:00 +00:00
sessionEncKey, err := base64.StdEncoding.DecodeString(config.String("session.enc-key"))
if err != nil {
log.WithError(err).Fatal("could not decode session encryption key")
2021-09-19 17:55:00 +00:00
}
generated := false
if len(sessionAuthKey) != sessionAuthKeyLength {
sessionAuthKey = services.GenerateKey(sessionAuthKeyLength)
2021-09-19 17:55:00 +00:00
generated = true
}
if len(sessionEncKey) != sessionKeyLength {
sessionEncKey = services.GenerateKey(sessionKeyLength)
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)
2021-09-19 17:55:00 +00:00
tomlData, err := config.Marshal(toml.Parser())
if err != nil {
log.WithError(err).Fatal("could not encode session config")
2021-09-19 17:55:00 +00:00
}
2021-09-19 17:55:00 +00:00
log.Infof("put the following in your resource_app.toml:\n%s", string(tomlData))
}
2021-09-19 17:55:00 +00:00
return sessionPath, sessionAuthKey, sessionEncKey
}