Refactor CSRF secret handling to validate key length and improve error messaging

This commit is contained in:
2025-04-29 03:34:01 -05:00
parent 1581fbca4b
commit 83b38498c8
2 changed files with 24 additions and 21 deletions

View File

@ -1,6 +1,7 @@
package middleware
import (
"fmt"
"html/template"
"net/http"
@ -137,3 +138,18 @@ func CSRFToken(r *http.Request) string {
func CSRFTemplateField(r *http.Request) template.HTML {
return csrf.TemplateField(r)
}
// ParseCSRFKey validates and converts a CSRF secret string to the required 32-byte key
// It returns the key as a byte slice and an error if the key is invalid
func ParseCSRFKey(secret string) ([]byte, error) {
if secret == "" {
return nil, fmt.Errorf("csrf secret is required and must be exactly 32 bytes")
}
key := []byte(secret)
if len(key) != 32 {
return nil, fmt.Errorf("csrf secret must be exactly 32 bytes (got %d bytes)", len(key))
}
return key, nil
}