Skip to content

Commit

Permalink
GenerateRandomKey: do not swallow errors
Browse files Browse the repository at this point in the history
The requirement to check for nil returns is so unexpected that even
other Gorilla libraries get it wrong:

<https://github.com/gorilla/sessions/blob/3eed1c4ffcde6f23b6f88068c63c1ef6190df331/store.go#L225>

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.
  • Loading branch information
majewsky committed Nov 8, 2023
1 parent eae3c18 commit c2b1c19
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions securecookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit c2b1c19

Please sign in to comment.