Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

added unit tests. fixed bugs.

Jack488aaecaa7c7
diff --git a/core/internal/service/maillog_stat/encryption.go b/core/internal/service/maillog_stat/encryption.go
index 12f55447..ae6a8d10 100644
--- a/core/internal/service/maillog_stat/encryption.go
+++ b/core/internal/service/maillog_stat/encryption.go
@@ -1,7 +1,6 @@
package maillog_stat
import (
- "bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
@@ -13,6 +12,7 @@ import (
func Encrypt(data interface{}) string {
dataJSON, _ := json.Marshal(data)
+
key := grand.B(16)
iv := grand.B(16)
@@ -34,6 +34,7 @@ func Encrypt(data interface{}) string {
}
resultBytes := append(keyiv[:16], append(ciphertext, keyiv[16:]...)...)
+
result := base64.URLEncoding.EncodeToString(resultBytes)
return strings.TrimRight(result, "=")
}
@@ -55,7 +56,10 @@ func Decrypt(data string, result interface{}) (err error) {
return
}
- keyiv := append(dataAes[:16], dataAes[len(dataAes)-16:]...)
+ dataAesLen := len(dataAes)
+ keyiv := make([]byte, 0, 32)
+ keyiv = append(keyiv, dataAes[:16]...)
+ keyiv = append(keyiv, dataAes[dataAesLen-16:]...)
var key, iv []byte
for i := 0; i < 32; i++ {
@@ -72,11 +76,12 @@ func Decrypt(data string, result interface{}) (err error) {
}
mode := cipher.NewCBCDecrypter(block, iv)
- ciphertext := dataAes[16 : len(dataAes)-16]
+ ciphertext := dataAes[16 : dataAesLen-16]
+
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
- unpaddedData := PKCS7Unpadding(plaintext)
+ unpaddedData := PKCS7UnPadding(plaintext, block.BlockSize())
err = json.Unmarshal(unpaddedData, &result)
if err != nil {
@@ -87,16 +92,30 @@ func Decrypt(data string, result interface{}) (err error) {
}
func PKCS7Padding(data []byte, blockSize int) []byte {
- padding := blockSize - len(data)%blockSize
- padText := bytes.Repeat([]byte{byte(padding)}, padding)
- return append(data, padText...)
+ length := len(data)
+
+ amountToPad := blockSize - (length % blockSize)
+
+ if amountToPad == 0 {
+ amountToPad = blockSize
+ }
+
+ pad := byte(amountToPad)
+
+ for i := 0; i < amountToPad; i++ {
+ data = append(data, pad)
+ }
+
+ return data
}
-func PKCS7Unpadding(data []byte) []byte {
+func PKCS7UnPadding(data []byte, blockSize int) []byte {
length := len(data)
- if length == 0 {
- return data
+ pad := int(data[length-1])
+
+ if pad < 1 || pad > blockSize {
+ pad = 0
}
- unpadding := int(data[length-1])
- return data[:(length - unpadding)]
+
+ return data[:(length - pad)]
}
diff --git a/core/internal/service/maillog_stat/encryption_test.go b/core/internal/service/maillog_stat/encryption_test.go
new file mode 100644
index 00000000..d61869cf
--- /dev/null
+++ b/core/internal/service/maillog_stat/encryption_test.go
@@ -0,0 +1,81 @@
+package maillog_stat
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestEncrypt(t *testing.T) {
+ type args struct {
+ data interface{}
+ }
+ tests := []struct {
+ name string
+ args args
+ }{
+ {
+ name: "Test Encrypt String",
+ args: args{
+ data: "Test String 123",
+ },
+ },
+ {
+ name: "Test Encrypt Numbers",
+ args: args{
+ data: 123456,
+ },
+ },
+ {
+ name: "Test Encrypt Map",
+ args: args{
+ data: map[string]interface{}{
+ "id": 1001,
+ "email": "[email protected]",
+ "event_type": "click",
+ "timestamp": 1623456789,
+ "metadata": map[string]interface{}{
+ "campaign_id": 5678,
+ "url": "https://example.com/page",
+ "ip": "192.168.1.1",
+ },
+ "tags": []string{"marketing", "newsletter"},
+ },
+ },
+ },
+ {
+ name: "Test Encrypt Empty String",
+ args: args{
+ data: "",
+ },
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ encrypted := Encrypt(tt.args.data)
+ if encrypted == "" {
+ t.Errorf("Encrypt() returned empty string")
+ return
+ }
+
+ if len(encrypted) < 10 {
+ t.Errorf("Invalid encrypt length: %v", encrypted)
+ }
+
+ // Test Decryption
+ var decrypted interface{}
+ err := Decrypt(encrypted, &decrypted)
+ if err != nil {
+ t.Errorf("Decrypt failed: %v", err)
+ return
+ }
+
+ // Marshal both original and decrypted data to JSON for comparison
+ originalJSON, _ := json.Marshal(tt.args.data)
+ decryptedJSON, _ := json.Marshal(decrypted)
+
+ if string(originalJSON) != string(decryptedJSON) {
+ t.Errorf("Decrypted data not match: origin=%v, decrypted=%v", string(originalJSON), string(decryptedJSON))
+ }
+ })
+ }
+}
diff --git a/core/internal/service/maillog_stat/tracker.go b/core/internal/service/maillog_stat/tracker.go
index 04e48a30..21f46d4f 100644
--- a/core/internal/service/maillog_stat/tracker.go
+++ b/core/internal/service/maillog_stat/tracker.go
@@ -134,7 +134,7 @@ func (t *MailTracker) TrackLinks() {
return fmt.Sprintf(`href="%s"`, t.GetTrackingURL(matches[1]))
})
- t.modified = true
+ t.modified = t.originalMailHTML != t.mailHTML
}
func (t *MailTracker) GetTrackingURL(url string) string {
diff --git a/core/internal/service/maillog_stat/tracker_test.go b/core/internal/service/maillog_stat/tracker_test.go
new file mode 100644
index 00000000..dfc0dd51
--- /dev/null
+++ b/core/internal/service/maillog_stat/tracker_test.go
@@ -0,0 +1,345 @@
+package maillog_stat
+
+import (
+ "reflect"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+func TestNewMailTracker(t *testing.T) {
+ type args struct {
+ mailHTML string
+ campaignID int
+ messageID string
+ recipient string
+ baseURL string
+ }
+ tests := []struct {
+ name string
+ args args
+ want *MailTracker
+ }{
+ {
+ name: "Basic email tracker creation",
+ args: args{
+ mailHTML: "<html><body>Test Mail</body></html>",
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://example.com",
+ },
+ want: &MailTracker{
+ originalMailHTML: "<html><body>Test Mail</body></html>",
+ modified: false,
+ mailHTML: "<html><body>Test Mail</body></html>",
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ },
+ {
+ name: "Email with slash in baseURL",
+ args: args{
+ mailHTML: "<html><body>Content</body></html>",
+ campaignID: 456,
+ messageID: "def456",
+ recipient: "[email protected]",
+ baseURL: "https://test.com/",
+ },
+ want: &MailTracker{
+ originalMailHTML: "<html><body>Content</body></html>",
+ modified: false,
+ mailHTML: "<html><body>Content</body></html>",
+ campaignID: 456,
+ messageID: "def456",
+ recipient: "[email protected]",
+ baseURL: "https://test.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ },
+ {
+ name: "Email with empty HTML",
+ args: args{
+ mailHTML: "",
+ campaignID: 789,
+ messageID: "ghi789",
+ recipient: "[email protected]",
+ baseURL: "https://empty.com",
+ },
+ want: &MailTracker{
+ originalMailHTML: "",
+ modified: false,
+ mailHTML: "",
+ campaignID: 789,
+ messageID: "ghi789",
+ recipient: "[email protected]",
+ baseURL: "https://empty.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := NewMailTracker(tt.args.mailHTML, tt.args.campaignID, tt.args.messageID, tt.args.recipient, tt.args.baseURL)
+
+ // Can't compare regexps directly, so we compare their string representations
+ if got.hrefPattern.String() != tt.want.hrefPattern.String() {
+ t.Errorf("NewMailTracker() hrefPattern = %v, want %v", got.hrefPattern, tt.want.hrefPattern)
+ }
+
+ // Set hrefPattern to nil for comparison
+ got.hrefPattern = nil
+ tt.want.hrefPattern = nil
+
+ if !reflect.DeepEqual(got, tt.want) {
+ t.Errorf("NewMailTracker() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestMailTracker_TrackLinks(t *testing.T) {
+ type fields struct {
+ originalMailHTML string
+ modified bool
+ mailHTML string
+ campaignID int
+ messageID string
+ recipient string
+ baseURL string
+ hrefPattern *regexp.Regexp
+ }
+ type test struct {
+ name string
+ fields fields
+ wantModified bool
+ wantContains string
+ wantNotContains string
+ }
+
+ tests := []test{
+ {
+ name: "Track links in HTML with href",
+ fields: fields{
+ originalMailHTML: `<html><body><a href="https://example.com">Link</a></body></html>`,
+ modified: false,
+ mailHTML: `<html><body><a href="https://example.com">Link</a></body></html>`,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: true,
+ wantContains: "https://track.example.com/pmta/",
+ wantNotContains: `href="https://example.com"`,
+ },
+ {
+ name: "No links to track",
+ fields: fields{
+ originalMailHTML: `<html><body>No links here</body></html>`,
+ modified: false,
+ mailHTML: `<html><body>No links here</body></html>`,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: false,
+ wantContains: `<html><body>No links here</body></html>`,
+ wantNotContains: "https://track.example.com/pmta/",
+ },
+ {
+ name: "Invalid URL in href",
+ fields: fields{
+ originalMailHTML: `<html><body><a href="javascript:void(0)">JS Link</a></body></html>`,
+ modified: false,
+ mailHTML: `<html><body><a href="javascript:void(0)">JS Link</a></body></html>`,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: false,
+ wantContains: `href="javascript:void(0)"`,
+ wantNotContains: "https://track.example.com/pmta/",
+ },
+ {
+ name: "Multiple links to track",
+ fields: fields{
+ originalMailHTML: `<html><body><a href="https://example1.com">Link1</a><a href="https://example2.com">Link2</a></body></html>`,
+ modified: false,
+ mailHTML: `<html><body><a href="https://example1.com">Link1</a><a href="https://example2.com">Link2</a></body></html>`,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: true,
+ wantContains: "https://track.example.com/pmta/",
+ wantNotContains: `href="https://example1.com"`,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ tracker := &MailTracker{
+ originalMailHTML: tt.fields.originalMailHTML,
+ modified: tt.fields.modified,
+ mailHTML: tt.fields.mailHTML,
+ campaignID: tt.fields.campaignID,
+ messageID: tt.fields.messageID,
+ recipient: tt.fields.recipient,
+ baseURL: tt.fields.baseURL,
+ hrefPattern: tt.fields.hrefPattern,
+ }
+
+ tracker.TrackLinks()
+
+ if tracker.IsModified() != tt.wantModified {
+ t.Errorf("TrackLinks() modified = %v, want %v", tracker.IsModified(), tt.wantModified)
+ }
+
+ if !strings.Contains(tracker.GetHTML(), tt.wantContains) {
+ t.Errorf("TrackLinks() HTML does not contain %q", tt.wantContains)
+ }
+
+ if tt.wantNotContains != "" && strings.Contains(tracker.GetHTML(), tt.wantNotContains) {
+ t.Errorf("TrackLinks() HTML contains %q when it should not", tt.wantNotContains)
+ }
+ })
+ }
+}
+
+func TestMailTracker_AppendTrackingPixel(t *testing.T) {
+ type fields struct {
+ originalMailHTML string
+ modified bool
+ mailHTML string
+ campaignID int
+ messageID string
+ recipient string
+ baseURL string
+ hrefPattern *regexp.Regexp
+ }
+ type test struct {
+ name string
+ fields fields
+ wantModified bool
+ wantContains string
+ wantNotContains string
+ }
+
+ tests := []test{
+ {
+ name: "Append tracking pixel to HTML with body tag",
+ fields: fields{
+ originalMailHTML: `<html><body>Test content</body></html>`,
+ modified: false,
+ mailHTML: `<html><body>Test content</body></html>`,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: true,
+ wantContains: `<img src="https://track.example.com/pmta/`,
+ wantNotContains: `</body><img src=`,
+ },
+ {
+ name: "Append tracking pixel to HTML with html tag but no body tag",
+ fields: fields{
+ originalMailHTML: `<html>Test content</html>`,
+ modified: false,
+ mailHTML: `<html>Test content</html>`,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: true,
+ wantContains: `<img src="https://track.example.com/pmta/`,
+ wantNotContains: `</html><img src=`,
+ },
+ {
+ name: "Append tracking pixel to HTML without body or html tag",
+ fields: fields{
+ originalMailHTML: `Just plain text content`,
+ modified: false,
+ mailHTML: `Just plain text content`,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: true,
+ wantContains: `Just plain text content<img src="https://track.example.com/pmta/`,
+ },
+ {
+ name: "Empty HTML content",
+ fields: fields{
+ originalMailHTML: ``,
+ modified: false,
+ mailHTML: ``,
+ campaignID: 123,
+ messageID: "abc123",
+ recipient: "[email protected]",
+ baseURL: "https://track.example.com/pmta",
+ hrefPattern: regexp.MustCompile(`href\s*=\s*"([^"]+)"`),
+ },
+ wantModified: true,
+ wantContains: `<img src="https://track.example.com/pmta/`,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ tracker := &MailTracker{
+ originalMailHTML: tt.fields.originalMailHTML,
+ modified: tt.fields.modified,
+ mailHTML: tt.fields.mailHTML,
+ campaignID: tt.fields.campaignID,
+ messageID: tt.fields.messageID,
+ recipient: tt.fields.recipient,
+ baseURL: tt.fields.baseURL,
+ hrefPattern: tt.fields.hrefPattern,
+ }
+
+ tracker.AppendTrackingPixel()
+
+ if tracker.IsModified() != tt.wantModified {
+ t.Errorf("AppendTrackingPixel() modified = %v, want %v", tracker.IsModified(), tt.wantModified)
+ }
+
+ if !strings.Contains(tracker.GetHTML(), tt.wantContains) {
+ t.Errorf("AppendTrackingPixel() HTML does not contain %q", tt.wantContains)
+ }
+
+ if tt.wantNotContains != "" && strings.Contains(tracker.GetHTML(), tt.wantNotContains) {
+ t.Errorf("AppendTrackingPixel() HTML contains %q when it should not", tt.wantNotContains)
+ }
+
+ if strings.Contains(tt.fields.originalMailHTML, "</body>") {
+ if !strings.Contains(tracker.GetHTML(), `<img src="https://track.example.com/pmta/`) ||
+ !strings.Contains(tracker.GetHTML(), `</body>`) {
+ t.Errorf("Tracking pixel not correctly inserted before </body>")
+ }
+ } else if strings.Contains(tt.fields.originalMailHTML, "</html>") {
+ if !strings.Contains(tracker.GetHTML(), `<img src="https://track.example.com/pmta/`) ||
+ !strings.Contains(tracker.GetHTML(), `</html>`) {
+ t.Errorf("Tracking pixel not correctly inserted before </html>")
+ }
+ }
+ })
+ }
+}