From b984a598cb62b51ff8e810c4a8ac3d9f5a6e5377 Mon Sep 17 00:00:00 2001 From: boreq Date: Tue, 20 Jun 2023 14:05:57 +0200 Subject: [PATCH] Fix panic in ParseMessage There is a chance the function can panic if a comma is included in the input which is invalid. --- envelopes.go | 2 ++ envelopes_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/envelopes.go b/envelopes.go index f6638f9..92dcc01 100644 --- a/envelopes.go +++ b/envelopes.go @@ -35,6 +35,8 @@ func ParseMessage(message []byte) Envelope { case bytes.Contains(label, []byte("CLOSE")): x := CloseEnvelope("") v = &x + default: + return nil } if err := v.UnmarshalJSON(message); err != nil { diff --git a/envelopes_test.go b/envelopes_test.go index 4c73bd5..8812411 100644 --- a/envelopes_test.go +++ b/envelopes_test.go @@ -2,6 +2,7 @@ package nostr import ( "encoding/json" + "reflect" "testing" ) @@ -110,3 +111,36 @@ func TestAuthEnvelopeEncodingAndDecoding(t *testing.T) { } } } + +func TestParseMessage(t *testing.T) { + testCases := []struct { + Name string + Message []byte + ExpectedEnvelope interface{} + }{ + { + Name: "nil", + Message: nil, + ExpectedEnvelope: nil, + }, + { + Name: "invalid string", + Message: []byte("invalid input"), + ExpectedEnvelope: nil, + }, + { + Name: "invalid string with a comma", + Message: []byte("invalid, input"), + ExpectedEnvelope: nil, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.Name, func(t *testing.T) { + envelope := ParseMessage(testCase.Message) + if !reflect.DeepEqual(testCase.ExpectedEnvelope, envelope) { + t.Fatal("unexpected output") + } + }) + } +}