From 6c75bb5d210b3bf8cc83bfbd3423b916957a172b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ferdinand=20M=C3=BCtsch?= Date: Fri, 3 Mar 2023 21:44:13 +0100 Subject: [PATCH] chore: reuse securecookie keys in dev mode (resolve #463) --- config/config.go | 16 ++++++++++++---- config/key_utils.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 config/key_utils.go diff --git a/config/config.go b/config/config.go index b55db4b..d579bb9 100644 --- a/config/config.go +++ b/config/config.go @@ -395,10 +395,18 @@ func Load(version string) *Config { config.InstanceId = uuid.NewV4().String() config.App.Colors = readColors() config.Db.Dialect = resolveDbDialect(config.Db.Type) - config.Security.SecureCookie = securecookie.New( - securecookie.GenerateRandomKey(64), - securecookie.GenerateRandomKey(32), - ) + + var hashKey []byte + var blockKey []byte + if IsDev(env) { + logbuch.Warn("using temporary keys to sign and encrypt cookies in dev mode, make sure to set env to production for real-world use") + hashKey, blockKey = getTemporarySecureKeys() + } else { + hashKey = securecookie.GenerateRandomKey(64) + blockKey = securecookie.GenerateRandomKey(64) + } + + config.Security.SecureCookie = securecookie.New(hashKey, blockKey) config.Security.SessionKey = securecookie.GenerateRandomKey(32) if strings.HasSuffix(config.Server.BasePath, "/") { diff --git a/config/key_utils.go b/config/key_utils.go new file mode 100644 index 0000000..664906b --- /dev/null +++ b/config/key_utils.go @@ -0,0 +1,41 @@ +package config + +import ( + "github.com/emvi/logbuch" + "github.com/gorilla/securecookie" + "io" + "os" + "path/filepath" +) + +func getTemporarySecureKeys() (hashKey, blockKey []byte) { + keyFile := filepath.Join(os.TempDir(), ".wakapi-dev-keys") + + // key file already exists + if _, err := os.Stat(keyFile); err == nil { + file, err := os.Open(keyFile) + if err != nil { + logbuch.Fatal("failed to open dev keys file, %v", err) + } + defer file.Close() + + combinedKey, err := io.ReadAll(file) + if err != nil { + logbuch.Fatal("failed to read key from file") + } + return combinedKey[:32], combinedKey[32:64] + } + + // otherwise, generate random keys and save them + file, err := os.OpenFile(keyFile, os.O_CREATE|os.O_WRONLY, 0600) + if err != nil { + logbuch.Fatal("failed to open dev keys file, %v", err) + } + defer file.Close() + + combinedKey := securecookie.GenerateRandomKey(64) + if _, err := file.Write(combinedKey); err != nil { + logbuch.Fatal("failed to write key to file") + } + return combinedKey[:32], combinedKey[32:64] +}