Files
lincodex/backend/internal/domain/email_address.go
T

175 lines
6.7 KiB
Go

package domain
import (
"errors"
"fmt"
"log/slog"
"strings"
)
const (
// Bounds follow the EmailAddress schema in the public contract (3 to 254
// characters) and the RFC 5321 local-part limit of 64 octets. Addresses
// are ASCII, so characters and bytes coincide.
minEmailAddressLength = 3
maxEmailAddressLength = 254
maxEmailLocalPartSize = 64
maxEmailDomainLabel = 63
redactedEmailAddress = "[redacted email]"
asciiWhitespace = " \t\n\v\f\r"
)
var ErrInvalidEmailAddress = errors.New("invalid email address")
// EmailAddress is a syntactically valid ASCII account email in two forms.
//
// Address is the delivery form: the input with surrounding ASCII whitespace
// removed, in the letter case the user typed, because RFC 5321 allows a
// case-sensitive local part. The account view returns it.
//
// Normalized is the comparison key: the address with A-Z lowercased. Storage
// keeps it unique, so addresses that differ only in letter case conflict. Go
// owns this rule; the database never recomputes the key, because PostgreSQL
// lower() depends on the collation.
//
// Only ASCII addresses are accepted because the mailer does not support
// SMTPUTF8. Internationalized domains are accepted in their ASCII (punycode)
// form. Accepting Unicode addresses is future work: it needs IDNA ToASCII for
// the domain, a rule for Unicode local parts, and SMTPUTF8 delivery.
//
// String, GoString, Format, and LogValue redact the address so it does not
// reach logs by accident; Address returns the real value. Both forms sit
// behind a pointer: fmt cannot call Format on an unexported field of an
// enclosing struct and prints its contents instead, but for a pointer it
// prints only the address. A nil pointer is the zero, invalid value.
type EmailAddress struct {
value *emailAddressValue
}
type emailAddressValue struct {
address string
normalized string
}
// NewEmailAddress validates raw and returns both forms. It rejects non-ASCII
// characters, display names, quoted local parts, comments, whitespace or
// control characters inside the address, IP-literal domains, and domains
// without a dot. The outcome depends only on raw, never on stored accounts.
func NewEmailAddress(raw string) (EmailAddress, error) {
// Only ASCII whitespace is trimmed; any other character is validated.
address := strings.Trim(raw, asciiWhitespace)
for index := range len(address) {
if address[index] <= ' ' || address[index] > '~' {
return EmailAddress{}, invalidEmailAddress("address must contain printable ASCII characters only")
}
}
if length := len(address); length < minEmailAddressLength || length > maxEmailAddressLength {
return EmailAddress{}, invalidEmailAddress("address must have 3 to 254 characters")
}
localPart, domainPart, found := strings.Cut(address, "@")
if !found || strings.Contains(domainPart, "@") {
return EmailAddress{}, invalidEmailAddress("address must contain exactly one @")
}
if err := validateEmailLocalPart(localPart); err != nil {
return EmailAddress{}, err
}
if err := validateEmailDomain(domainPart); err != nil {
return EmailAddress{}, err
}
return EmailAddress{value: &emailAddressValue{address: address, normalized: normalizeEmailKey(address)}}, nil
}
// RestoreEmailAddress rebuilds an EmailAddress from storage. It checks only
// that the stored key matches the stored address, so a later, stricter
// NewEmailAddress rule does not make existing accounts unreadable.
func RestoreEmailAddress(address, normalized string) (EmailAddress, error) {
if address == "" || normalized != normalizeEmailKey(address) {
return EmailAddress{}, fmt.Errorf("domain.RestoreEmailAddress - stored key does not match the stored address: %w", ErrInvalidEmailAddress)
}
return EmailAddress{value: &emailAddressValue{address: address, normalized: normalized}}, nil
}
// normalizeEmailKey lowercases A-Z only, independent of locale and Unicode
// case rules.
func normalizeEmailKey(address string) string {
return strings.Map(func(character rune) rune {
if 'A' <= character && character <= 'Z' {
return character + ('a' - 'A')
}
return character
}, address)
}
func validateEmailLocalPart(localPart string) error {
if localPart == "" || len(localPart) > maxEmailLocalPartSize {
return invalidEmailAddress("local part must have 1 to 64 characters")
}
if strings.HasPrefix(localPart, ".") || strings.HasSuffix(localPart, ".") || strings.Contains(localPart, "..") {
return invalidEmailAddress("local part must not start or end with a dot or contain consecutive dots")
}
for _, character := range localPart {
if !isASCIILetterOrDigit(character) && !strings.ContainsRune(".!#$%&'*+-/=?^_`{|}~", character) {
return invalidEmailAddress("local part contains a character outside an unquoted dot-atom")
}
}
return nil
}
func validateEmailDomain(domainPart string) error {
labels := strings.Split(domainPart, ".")
if len(labels) < 2 {
return invalidEmailAddress("domain must contain at least two labels")
}
for _, label := range labels {
if label == "" || len(label) > maxEmailDomainLabel {
return invalidEmailAddress("domain labels must have 1 to 63 characters")
}
if strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
return invalidEmailAddress("domain labels must not start or end with a hyphen")
}
for _, character := range label {
if !isASCIILetterOrDigit(character) && character != '-' {
return invalidEmailAddress("domain contains a character outside letters, digits, and hyphens")
}
}
}
return nil
}
func isASCIILetterOrDigit(character rune) bool {
return ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z') || ('0' <= character && character <= '9')
}
func invalidEmailAddress(reason string) error {
return fmt.Errorf("domain.NewEmailAddress - %s: %w", reason, ErrInvalidEmailAddress)
}
// Address returns the delivery form. Use it only where the address is needed:
// storage, mail delivery, and the account view.
func (email EmailAddress) Address() string {
if email.value == nil {
return ""
}
return email.value.address
}
// Normalized returns the comparison key that storage keeps unique.
func (email EmailAddress) Normalized() string {
if email.value == nil {
return ""
}
return email.value.normalized
}
// IsZero reports an EmailAddress not built by NewEmailAddress.
func (email EmailAddress) IsZero() bool { return email.value == nil }
func (email EmailAddress) String() string { return redactedEmailAddress }
func (email EmailAddress) GoString() string { return redactedEmailAddress }
// Format redacts every verb; without it %d would print the struct fields.
func (email EmailAddress) Format(state fmt.State, _ rune) { writeRedacted(state, redactedEmailAddress) }
func (email EmailAddress) LogValue() slog.Value { return slog.StringValue(redactedEmailAddress) }