-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathvalidation.go
74 lines (62 loc) · 2.08 KB
/
validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package rfc5322
import (
"errors"
"fmt"
"github.com/ProtonMail/gluon/rfc822"
)
var ErrInvalidMessage = errors.New("invalid rfc5322 message")
// ValidateMessageHeaderFields checks the headers of message to verify that:
// * From and Date are present.
// * If From has multiple addresses, a Sender field must be present.
// * If Both From and Sender are present and they contain one address, they must not be equal.
func ValidateMessageHeaderFields(literal []byte) error {
headerBytes, _ := rfc822.Split(literal)
header, err := rfc822.NewHeader(headerBytes)
if err != nil {
return err
}
// Check for date.
{
value := header.Get("Date")
if len(value) == 0 {
return fmt.Errorf("%w: Required header field 'Date' not found or empty", ErrInvalidMessage)
}
}
// Check for from.
{
value := header.Get("From")
if len(value) == 0 {
return fmt.Errorf("%w: Required header field 'From' not found or empty", ErrInvalidMessage)
}
// Check if From is a multi address. If so, a sender filed must be present and non-empty.
addresses, err := ParseAddressList(value)
if err != nil {
return fmt.Errorf("%w: failed to parse From header: %v", ErrInvalidMessage, err)
}
if len(addresses) > 1 {
senderValue := header.Get("Sender")
if len(senderValue) == 0 {
return fmt.Errorf("%w: Required header field 'Sender' not found or empty", ErrInvalidMessage)
}
_, err := ParseAddress(senderValue)
if err != nil {
return fmt.Errorf("%w: failed to parse Sender header: %v", ErrInvalidMessage, err)
}
} else {
senderValue, ok := header.GetChecked("Sender")
if ok {
if len(senderValue) == 0 {
return fmt.Errorf("%w: Required header field 'Sender' should not be empty", ErrInvalidMessage)
}
senderAddr, err := ParseAddress(senderValue)
if err != nil {
return fmt.Errorf("%w: failed to parse Sender header: %v", ErrInvalidMessage, err)
}
if len(senderAddr) == 1 && senderAddr[0].Address == addresses[0].Address {
return fmt.Errorf("%w: `Sender` should not be present if equal to `From`", ErrInvalidMessage)
}
}
}
}
return nil
}