From dfb97405ed072ea98c2ea6707707afa66ae50707 Mon Sep 17 00:00:00 2001 From: Tom Wiesing Date: Mon, 20 Nov 2023 13:25:13 +0100 Subject: [PATCH] internal/config: Cache csrf secret --- internal/config/config.go | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 17b7531..cafdedd 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -7,6 +7,7 @@ import ( "reflect" "time" + "github.com/tkw1536/pkglib/lazy" "github.com/tkw1536/pkglib/reflectx" "github.com/tkw1536/pkglib/yamlx" "gopkg.in/yaml.v3" @@ -46,6 +47,9 @@ type Config struct { // ConfigPath is the path this configuration was loaded from (if any) ConfigPath string `yaml:"-"` + + // csrfSecret holds the cached csrf secret + csrfSecret lazy.Lazy[[]byte] } func zeroSensitive(v reflect.Value) { @@ -113,15 +117,17 @@ func Marshal(config *Config, previous []byte) ([]byte, error) { // CSRFSecret return the csrfSecret derived from the session secret func (config *Config) CSRFSecret() []byte { - // take the hash of the secret - h := fnv.New32a() - h.Write([]byte(config.SessionSecret)) + return config.csrfSecret.Get(func() []byte { + // take the hash of the secret + h := fnv.New32a() + h.Write([]byte(config.SessionSecret)) - // seed a random number generator - rand := rand.New(rand.NewSource(int64(h.Sum32()))) + // seed a random number generator + rand := rand.New(rand.NewSource(int64(h.Sum32()))) - // take a bunch of bytes from it - secret := make([]byte, 32) - rand.Read(secret) - return secret + // take a bunch of bytes from it + secret := make([]byte, 32) + rand.Read(secret) + return secret + }) }