Rewiring CSRF protection and movign some functionality to the bootstrapping stage.

This commit is contained in:
2025-04-16 09:50:58 +01:00
parent 4bb3b58ddb
commit 2440b3a668
7 changed files with 123 additions and 109 deletions

View File

@@ -1,14 +1,25 @@
package bootstrap
import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"net/http"
"os"
securityhandlers "synlotto-website/handlers/security"
helpers "synlotto-website/helpers/session"
"synlotto-website/logging"
"synlotto-website/models"
"github.com/gorilla/sessions"
)
var (
sessionStore *sessions.CookieStore
sessionName string
authKey []byte
encryptKey []byte
)
func InitSession(cfg *models.Config) error {
@@ -41,7 +52,7 @@ func InitSession(cfg *models.Config) error {
}
}
return securityhandlers.LoadSessionKeys(
return loadSessionKeys(
authPath,
encPath,
cfg.Session.Name,
@@ -59,3 +70,41 @@ func generateRandomBytes(length int) ([]byte, error) {
}
return b, nil
}
func loadSessionKeys(authPath, encryptionPath, name string, isProduction bool) error {
var err error
rawAuth, err := os.ReadFile(authPath)
if err != nil {
return fmt.Errorf("error reading auth key: %w", err)
}
authKey, err = base64.StdEncoding.DecodeString(string(bytes.TrimSpace(rawAuth)))
if err != nil {
return fmt.Errorf("error decoding auth key: %w", err)
}
rawEnc, err := os.ReadFile(encryptionPath)
if err != nil {
return fmt.Errorf("error reading encryption key: %w", err)
}
encryptKey, err = base64.StdEncoding.DecodeString(string(bytes.TrimSpace(rawEnc)))
if err != nil {
return fmt.Errorf("error decoding encryption key: %w", err)
}
if len(authKey) != 32 || len(encryptKey) != 32 {
return fmt.Errorf("auth and encryption keys must be 32 bytes each (got auth=%d, enc=%d)", len(authKey), len(encryptKey))
}
sessionStore = sessions.NewCookieStore(authKey, encryptKey)
sessionStore.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 1,
HttpOnly: true,
Secure: isProduction,
SameSite: http.SameSiteLaxMode,
}
sessionName = name
return nil
}