From f806f82d27683b980dad5dec8c78dee8b35b1993 Mon Sep 17 00:00:00 2001 From: Charlie Tonneslan Date: Mon, 18 May 2026 15:28:30 -0400 Subject: [PATCH] Add SecureCookie.Err for surfacing deferred configuration errors New stores configuration errors (missing hash key, bad block key, etc.) on the returned SecureCookie and only returns them later from Encode or Decode. Callers that want to fail fast had no way to read that state. Add an Err accessor that returns the stored error, leaving the existing Encode/Decode behavior unchanged. Closes #89 Signed-off-by: Charlie Tonneslan --- securecookie.go | 8 ++++++++ securecookie_test.go | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/securecookie.go b/securecookie.go index 4d5ea86..bc440b5 100644 --- a/securecookie.go +++ b/securecookie.go @@ -244,6 +244,14 @@ func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie { return s } +// Err returns the deferred error stored on s during New or BlockFunc. It's +// the same error every subsequent Encode or Decode call would surface. This +// lets callers fail fast when configuration is wrong instead of waiting for +// the first cookie to be processed. +func (s *SecureCookie) Err() error { + return s.err +} + // Encode encodes a cookie value. // // It serializes, optionally encrypts, signs with a message authentication code, diff --git a/securecookie_test.go b/securecookie_test.go index 72905ae..3f3883d 100644 --- a/securecookie_test.go +++ b/securecookie_test.go @@ -88,6 +88,19 @@ func TestSecureCookieNilKey(t *testing.T) { } } +func TestErr(t *testing.T) { + if err := New([]byte("hashkey"), nil).Err(); err != nil { + t.Fatalf("expected nil Err for a valid hash key, got %v", err) + } + if err := New(nil, nil).Err(); err != errHashKeyNotSet { + t.Fatalf("expected errHashKeyNotSet from Err, got %v", err) + } + // Invalid block key (wrong size) is surfaced via BlockFunc. + if err := New([]byte("hashkey"), []byte{1, 2, 3}).Err(); err == nil { + t.Fatal("expected non-nil Err for an invalid block key") + } +} + func TestDecodeInvalid(t *testing.T) { // List of invalid cookies, which must not be accepted, base64-decoded // (they will be encoded before passing to Decode).