From 40bef361ff80cffcf6a8fc7d51cecc8334fa55d0 Mon Sep 17 00:00:00 2001 From: Daniel Bae <157205701+MrBeldum@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:22:23 -0700 Subject: [PATCH] fix: return nil from GenerateRandomKey for non-positive length make([]byte, n) panics when n is negative, and a zero-length key is not useful as a cookie secret. Return nil for length <= 0, matching the existing failure path when reading from crypto/rand fails. --- securecookie.go | 3 +++ securecookie_test.go | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/securecookie.go b/securecookie.go index 4d5ea86..08412a6 100644 --- a/securecookie.go +++ b/securecookie.go @@ -513,6 +513,9 @@ func decode(value []byte) ([]byte, error) { // 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. func GenerateRandomKey(length int) []byte { + if length <= 0 { + return nil + } k := make([]byte, length) if _, err := io.ReadFull(rand.Reader, k); err != nil { return nil diff --git a/securecookie_test.go b/securecookie_test.go index 72905ae..e278afb 100644 --- a/securecookie_test.go +++ b/securecookie_test.go @@ -342,3 +342,15 @@ func FuzzEncodeDecode(f *testing.F) { } }) } + +func TestGenerateRandomKeyNonPositive(t *testing.T) { + if got := GenerateRandomKey(0); got != nil { + t.Fatalf("GenerateRandomKey(0)=%v, want nil", got) + } + if got := GenerateRandomKey(-1); got != nil { + t.Fatalf("GenerateRandomKey(-1)=%v, want nil", got) + } + if got := GenerateRandomKey(16); got == nil || len(got) != 16 { + t.Fatalf("GenerateRandomKey(16)=%v, want 16-byte key", got) + } +}