Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix large notifications panic #8

Merged
merged 2 commits into from
Dec 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions webpush.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (

const MaxRecordSize uint32 = 4096

var ErrMaxPadExceeded = errors.New("payload has exceeded the maximum length")

// saltFunc generates a salt of 16 bytes
var saltFunc = func() ([]byte, error) {
salt := make([]byte, 16)
Expand Down Expand Up @@ -166,7 +168,9 @@ func SendNotification(message []byte, s *Subscription, options *Options) (*http.
// Pad content to max record size - 16 - header
// Padding ending delimeter
dataBuf.Write([]byte("\x02"))
pad(dataBuf, recordLength-recordBuf.Len())
if err := pad(dataBuf, recordLength-recordBuf.Len()); err != nil {
return nil, err
}

// Compose the ciphertext
ciphertext := gcm.Seal([]byte{}, nonce, dataBuf.Bytes(), nil)
Expand Down Expand Up @@ -243,10 +247,16 @@ func getHKDFKey(hkdf io.Reader, length int) ([]byte, error) {
return key, nil
}

func pad(payload *bytes.Buffer, maxPadLen int) {
func pad(payload *bytes.Buffer, maxPadLen int) error {
payloadLen := payload.Len()
if payloadLen > maxPadLen {
return ErrMaxPadExceeded
}

padLen := maxPadLen - payloadLen

padding := make([]byte, padLen)
payload.Write(padding)

return nil
}
15 changes: 15 additions & 0 deletions webpush_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package webpush

import (
"net/http"
"strings"
"testing"
)

Expand Down Expand Up @@ -76,3 +77,17 @@ func TestSendNotificationToStandardEncodedSubscription(t *testing.T) {
)
}
}

func TestSendTooLargeNotification(t *testing.T) {
_, err := SendNotification([]byte(strings.Repeat("Test", int(MaxRecordSize))), getStandardEncodedTestSubscription(), &Options{
HTTPClient: &testHTTPClient{},
Subscriber: "<EMAIL@EXAMPLE.COM>",
Topic: "test_topic",
TTL: 0,
Urgency: "low",
VAPIDPrivateKey: "testKey",
})
if err == nil {
t.Fatalf("Error is nil, expected=%s", ErrMaxPadExceeded)
}
}