From c2b1c197de068dfbe9084cd37a0c905e9ff88471 Mon Sep 17 00:00:00 2001 From: Stefan Majewsky Date: Wed, 8 Nov 2023 16:49:58 +0100 Subject: [PATCH] GenerateRandomKey: do not swallow errors The requirement to check for nil returns is so unexpected that even other Gorilla libraries get it wrong: Since a malfunction of the system random number generator is pretty unrecoverable for most security-sensitive applications, I consider it fine to use a panic here. Most callers will have no better option than to just die anyway. If callers need a more specific behavior, they can implement these three lines of code themselves with application-specific error handling. --- securecookie.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/securecookie.go b/securecookie.go index 4d5ea86..177eb58 100644 --- a/securecookie.go +++ b/securecookie.go @@ -510,12 +510,12 @@ func decode(value []byte) ([]byte, error) { // persisted. New keys will be created when the application is restarted, and // previously issued cookies will not be able to be decoded. // -// Callers should explicitly check for the possibility of a nil return, treat -// it as a failure of the system random number generator, and not continue. +// Panics if the system random number generator cannot come up with the requested +// amount of randomness. func GenerateRandomKey(length int) []byte { k := make([]byte, length) if _, err := io.ReadFull(rand.Reader, k); err != nil { - return nil + panic(fmt.Sprintf("could not generate %d bytes of randomness: %s", length, err.Error())) } return k }