1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00

chore: reuse securecookie keys in dev mode (resolve #463)

This commit is contained in:
Ferdinand Mütsch 2023-03-03 21:44:13 +01:00
parent a6ef735ba1
commit 6c75bb5d21
2 changed files with 53 additions and 4 deletions

View File

@ -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, "/") {

41
config/key_utils.go Normal file
View File

@ -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]
}