Archived
initial
This commit is contained in:
59 files changed
+11046
No files matched your search
@@ -0,0 +1,150 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/mail"
|
||||
"net/textproto"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Attachment struct{ Filename, ContentType, ContentBase64 string }
|
||||
type Message struct {
|
||||
From string
|
||||
To, CC, BCC []string
|
||||
ReplyTo, Subject, Text, HTML string
|
||||
Headers map[string]string
|
||||
Attachments []Attachment
|
||||
}
|
||||
|
||||
var allowedHeader = regexp.MustCompile(`(?i)^(X-[A-Za-z0-9-]{1,64}|List-Unsubscribe|List-Unsubscribe-Post)$`)
|
||||
|
||||
func Build(m Message, maxBytes int64) ([]byte, []string, error) {
|
||||
from, err := mail.ParseAddress(m.From)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid from address: %w", err)
|
||||
}
|
||||
recipients := append(append(append([]string{}, m.To...), m.CC...), m.BCC...)
|
||||
if len(recipients) == 0 {
|
||||
return nil, nil, fmt.Errorf("at least one recipient is required")
|
||||
}
|
||||
for i, value := range recipients {
|
||||
address, err := mail.ParseAddress(value)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid recipient %q", value)
|
||||
}
|
||||
recipients[i] = strings.ToLower(address.Address)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
boundary := randomBoundary()
|
||||
bodyBoundary := randomBoundary()
|
||||
headers := textproto.MIMEHeader{}
|
||||
headers.Set("From", from.String())
|
||||
headers.Set("To", strings.Join(m.To, ", "))
|
||||
if len(m.CC) > 0 {
|
||||
headers.Set("Cc", strings.Join(m.CC, ", "))
|
||||
}
|
||||
if m.ReplyTo != "" {
|
||||
if _, err = mail.ParseAddress(m.ReplyTo); err != nil {
|
||||
return nil, nil, fmt.Errorf("invalid reply-to")
|
||||
}
|
||||
headers.Set("Reply-To", m.ReplyTo)
|
||||
}
|
||||
headers.Set("Subject", mime.QEncoding.Encode("utf-8", m.Subject))
|
||||
headers.Set("Date", time.Now().Format(time.RFC1123Z))
|
||||
headers.Set("MIME-Version", "1.0")
|
||||
headers.Set("Message-ID", fmt.Sprintf("<%s@meovv.local>", strings.ToLower(randomBoundary())))
|
||||
for k, v := range m.Headers {
|
||||
if !allowedHeader.MatchString(k) || strings.ContainsAny(k+v, "\r\n") {
|
||||
return nil, nil, fmt.Errorf("header %q is not allowed", k)
|
||||
}
|
||||
headers.Set(k, v)
|
||||
}
|
||||
withAttachments := len(m.Attachments) > 0
|
||||
decodedBytes := int64(len([]byte(m.Text)) + len([]byte(m.HTML)))
|
||||
if withAttachments {
|
||||
headers.Set("Content-Type", fmt.Sprintf(`multipart/mixed; boundary="%s"`, boundary))
|
||||
} else {
|
||||
headers.Set("Content-Type", fmt.Sprintf(`multipart/alternative; boundary="%s"`, bodyBoundary))
|
||||
}
|
||||
keys := make([]string, 0, len(headers))
|
||||
for k := range headers {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
fmt.Fprintf(&out, "%s: %s\r\n", k, headers.Get(k))
|
||||
}
|
||||
out.WriteString("\r\n")
|
||||
if withAttachments {
|
||||
fmt.Fprintf(&out, "--%s\r\nContent-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", boundary, bodyBoundary)
|
||||
}
|
||||
writeAlternative(&out, bodyBoundary, m.Text, m.HTML)
|
||||
if withAttachments {
|
||||
for _, a := range m.Attachments {
|
||||
filename := filepath.Base(strings.ReplaceAll(a.Filename, "\\", "/"))
|
||||
if filename == "." || filename == "" {
|
||||
return nil, nil, fmt.Errorf("attachment filename is required")
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(a.ContentBase64)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("attachment %q is not valid base64", filename)
|
||||
}
|
||||
decodedBytes += int64(len(raw))
|
||||
if decodedBytes > maxBytes {
|
||||
return nil, nil, fmt.Errorf("decoded message exceeds %d bytes", maxBytes)
|
||||
}
|
||||
contentType := a.ContentType
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
fmt.Fprintf(&out, "--%s\r\nContent-Type: %s; name=%q\r\nContent-Disposition: attachment; filename=%q\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary, contentType, filename, filename)
|
||||
writeBase64(&out, raw)
|
||||
out.WriteString("\r\n")
|
||||
}
|
||||
fmt.Fprintf(&out, "--%s--\r\n", boundary)
|
||||
}
|
||||
if decodedBytes > maxBytes {
|
||||
return nil, nil, fmt.Errorf("decoded message exceeds %d bytes", maxBytes)
|
||||
}
|
||||
return out.Bytes(), recipients, nil
|
||||
}
|
||||
|
||||
func writeAlternative(out *bytes.Buffer, boundary, text, html string) {
|
||||
if text == "" {
|
||||
text = stripHTML(html)
|
||||
}
|
||||
fmt.Fprintf(out, "--%s\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary)
|
||||
writeBase64(out, []byte(text))
|
||||
out.WriteString("\r\n")
|
||||
if html != "" {
|
||||
fmt.Fprintf(out, "--%s\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n", boundary)
|
||||
writeBase64(out, []byte(html))
|
||||
out.WriteString("\r\n")
|
||||
}
|
||||
fmt.Fprintf(out, "--%s--\r\n", boundary)
|
||||
}
|
||||
func writeBase64(out *bytes.Buffer, data []byte) {
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
for len(encoded) > 76 {
|
||||
out.WriteString(encoded[:76])
|
||||
out.WriteString("\r\n")
|
||||
encoded = encoded[76:]
|
||||
}
|
||||
out.WriteString(encoded)
|
||||
}
|
||||
func randomBoundary() string {
|
||||
b := make([]byte, 18)
|
||||
_, _ = rand.Read(b)
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
func stripHTML(value string) string {
|
||||
return strings.TrimSpace(regexp.MustCompile(`<[^>]+>`).ReplaceAllString(value, " "))
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildMIMEAndProtectAttachmentFilename(t *testing.T) {
|
||||
raw, recipients, err := Build(Message{
|
||||
From: "MEOVV <sender@example.com>",
|
||||
To: []string{"Person <PERSON@example.net>"},
|
||||
Subject: "سلام — status",
|
||||
Text: "Hello",
|
||||
HTML: "<p>Hello</p>",
|
||||
Headers: map[string]string{"X-Campaign-ID": "welcome"},
|
||||
Attachments: []Attachment{{Filename: "../../private/statement.pdf", ContentType: "application/pdf", ContentBase64: base64.StdEncoding.EncodeToString([]byte("content"))}},
|
||||
}, 25<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recipients) != 1 || recipients[0] != "person@example.net" {
|
||||
t.Fatalf("unexpected recipients: %#v", recipients)
|
||||
}
|
||||
message := string(raw)
|
||||
if strings.Contains(message, "../") || !strings.Contains(message, `filename="statement.pdf"`) {
|
||||
t.Fatalf("unsafe or missing filename in MIME:\n%s", message)
|
||||
}
|
||||
if strings.Contains(message, "Bcc:") {
|
||||
t.Fatal("Bcc header leaked into MIME")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRejectsHeaderInjectionAndDecodedLimit(t *testing.T) {
|
||||
_, _, err := Build(Message{From: "sender@example.com", To: []string{"to@example.net"}, Text: "hello", Headers: map[string]string{"X-Test": "ok\r\nBcc: stolen@example.net"}}, 1024)
|
||||
if err == nil {
|
||||
t.Fatal("expected injected header to be rejected")
|
||||
}
|
||||
_, _, err = Build(Message{From: "sender@example.com", To: []string{"to@example.net"}, Text: strings.Repeat("x", 1025)}, 1024)
|
||||
if err == nil || !strings.Contains(err.Error(), "decoded message") {
|
||||
t.Fatalf("expected decoded size limit, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRequiresRecipient(t *testing.T) {
|
||||
_, _, err := Build(Message{From: "sender@example.com", Text: "hello"}, 1024)
|
||||
if err == nil {
|
||||
t.Fatal("expected recipient validation error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package mailer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/smtp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Sender interface {
|
||||
Send(context.Context, string, []string, []byte) (string, error)
|
||||
}
|
||||
|
||||
type SMTP struct {
|
||||
Address, Username, Password string
|
||||
TLSConfig *tls.Config
|
||||
}
|
||||
|
||||
func (s SMTP) Send(ctx context.Context, from string, to []string, raw []byte) (string, error) {
|
||||
host, _, err := net.SplitHostPort(s.Address)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dialer := net.Dialer{}
|
||||
conn, err := dialer.DialContext(ctx, "tcp", s.Address)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("connect to submission service: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
c, err := smtp.NewClient(conn, host)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer c.Close()
|
||||
tlsConfig := s.TLSConfig
|
||||
if tlsConfig == nil {
|
||||
tlsConfig = &tls.Config{ServerName: host, MinVersion: tls.VersionTLS12}
|
||||
}
|
||||
if ok, _ := c.Extension("STARTTLS"); ok {
|
||||
if err = c.StartTLS(tlsConfig); err != nil {
|
||||
return "", fmt.Errorf("start TLS: %w", err)
|
||||
}
|
||||
} else {
|
||||
return "", fmt.Errorf("submission service did not offer STARTTLS")
|
||||
}
|
||||
if s.Username != "" {
|
||||
auth := smtp.PlainAuth("", s.Username, s.Password, host)
|
||||
if err = c.Auth(auth); err != nil {
|
||||
return "", fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
}
|
||||
address, err := mailbox(from)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = c.Mail(address); err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, recipient := range to {
|
||||
if err = c.Rcpt(recipient); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
w, err := c.Data()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err = w.Write(raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = w.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = c.Quit(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "smtp-accepted", nil
|
||||
}
|
||||
|
||||
func mailbox(value string) (string, error) {
|
||||
start := strings.LastIndex(value, "<")
|
||||
end := strings.LastIndex(value, ">")
|
||||
if start >= 0 && end > start {
|
||||
return strings.TrimSpace(value[start+1 : end]), nil
|
||||
}
|
||||
if strings.Contains(value, "@") {
|
||||
return strings.TrimSpace(value), nil
|
||||
}
|
||||
return "", fmt.Errorf("invalid mailbox")
|
||||
}
|
||||
Reference in new issue
Block a user