286 lines
12 KiB
Go
286 lines
12 KiB
Go
package domain
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"regexp"
|
|
"strings"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
const (
|
|
// maxMailSubjectRunes matches the rendered subject bound of the mail
|
|
// templates; a longer stored subject is not a rendering.
|
|
maxMailSubjectRunes = 150
|
|
// maxMailPartBytes bounds one stored body part. Rendered service mail is
|
|
// a few kilobytes; the bound keeps a broken renderer from filling a row.
|
|
maxMailPartBytes = 256 << 10
|
|
// MailContentHashSize is the size of the SHA-256 content digest.
|
|
MailContentHashSize = sha256.Size
|
|
)
|
|
|
|
var (
|
|
// ErrInvalidMailContent reports content that no transport could send or
|
|
// that does not belong to its kind. Errors name the rule, never the text.
|
|
ErrInvalidMailContent = errors.New("invalid mail content")
|
|
|
|
// ErrMailContentIntegrity reports stored content whose parts no longer
|
|
// match the stored digest: the row was changed outside the application.
|
|
ErrMailContentIntegrity = errors.New("mail content does not match its hash")
|
|
|
|
// "<kind>.v<N>", the template version naming of the mail templates.
|
|
mailTemplateVersionPattern = regexp.MustCompile(`^[a-z][a-z_]*\.v[1-9][0-9]{0,8}$`)
|
|
)
|
|
|
|
// MailKind names what a message is for. The values equal the template kinds
|
|
// of the mail templates.
|
|
type MailKind string
|
|
|
|
const (
|
|
MailKindVerification MailKind = "verification"
|
|
MailKindPasswordReset MailKind = "password_reset"
|
|
MailKindNotification MailKind = "notification"
|
|
)
|
|
|
|
// ParseMailKind accepts a known kind.
|
|
func ParseMailKind(value string) (MailKind, error) {
|
|
switch kind := MailKind(value); kind {
|
|
case MailKindVerification, MailKindPasswordReset, MailKindNotification:
|
|
return kind, nil
|
|
default:
|
|
return "", fmt.Errorf("domain.ParseMailKind - unknown mail kind: %w", ErrInvalidMailContent)
|
|
}
|
|
}
|
|
|
|
// ServiceMailKinds lists the kinds of service identity mail, the kinds the
|
|
// service sending worker claims and sends. The delivery metrics of due mail
|
|
// and the due index of the deliveries table follow this list; changing it
|
|
// changes the predicate of deliveries_due_idx too.
|
|
func ServiceMailKinds() []MailKind {
|
|
return []MailKind{MailKindVerification, MailKindPasswordReset}
|
|
}
|
|
|
|
// ProductMailKinds lists the kinds of product notifications, the kinds the
|
|
// notification sending worker claims. Its claim has its own partial index,
|
|
// deliveries_product_due_idx, which follows this list.
|
|
func ProductMailKinds() []MailKind {
|
|
return []MailKind{MailKindNotification}
|
|
}
|
|
|
|
// IsServiceMail reports a kind of service identity mail.
|
|
func (kind MailKind) IsServiceMail() bool { return kind.CarriesBearerToken() }
|
|
|
|
// CarriesBearerToken reports kinds whose body holds a one-time bearer token
|
|
// in a link. Their stored bodies are secrets until the token expires.
|
|
func (kind MailKind) CarriesBearerToken() bool {
|
|
return kind == MailKindVerification || kind == MailKindPasswordReset
|
|
}
|
|
|
|
// TokenPurpose returns the email token purpose that the link of a mail of
|
|
// this kind carries, and false for a kind without a bearer token.
|
|
func (kind MailKind) TokenPurpose() (EmailTokenPurpose, bool) {
|
|
switch kind {
|
|
case MailKindVerification:
|
|
return EmailTokenPurposeEmailVerification, true
|
|
case MailKindPasswordReset:
|
|
return EmailTokenPurposePasswordReset, true
|
|
case MailKindNotification:
|
|
return "", false
|
|
default:
|
|
return "", false
|
|
}
|
|
}
|
|
|
|
// MailContentHash is SHA-256 over the template version, subject, text part,
|
|
// and HTML part, each encoded as a netstring ("<len>:<part>,"), so moving
|
|
// bytes from one part to the next changes the digest. The mail templates and
|
|
// stored deliveries use this one definition.
|
|
func MailContentHash(templateVersion, subject, text, html string) [MailContentHashSize]byte {
|
|
digest := sha256.New()
|
|
for _, part := range []string{templateVersion, subject, text, html} {
|
|
// hash.Hash.Write never returns an error.
|
|
_, _ = fmt.Fprintf(digest, "%d:", len(part))
|
|
_, _ = io.WriteString(digest, part)
|
|
_, _ = io.WriteString(digest, ",")
|
|
}
|
|
var sum [MailContentHashSize]byte
|
|
copy(sum[:], digest.Sum(nil))
|
|
return sum
|
|
}
|
|
|
|
// MailContent is one immutable rendered message: its kind, template version,
|
|
// subject, plain-text part, HTML part, and content hash. A body of a kind
|
|
// that CarriesBearerToken holds a live token.
|
|
//
|
|
// The parts sit behind a pointer with read-only accessors, so printing an
|
|
// enclosing struct shows only an address. String, GoString, Format, and
|
|
// LogValue show the kind, version, and hash, never the subject or bodies.
|
|
type MailContent struct {
|
|
value *mailContentValue
|
|
}
|
|
|
|
type mailContentValue struct {
|
|
kind MailKind
|
|
templateVersion string
|
|
subject string
|
|
text string
|
|
html string
|
|
hash [MailContentHashSize]byte
|
|
// redacted is set for the content of a terminal token mail whose bodies
|
|
// were cleared; only the subject and the hash remain.
|
|
redacted bool
|
|
}
|
|
|
|
// NewMailContent validates a rendering and computes its hash. The template
|
|
// version must name the kind ("<kind>.v<N>"), the subject must be one line
|
|
// of 1 to 150 characters, and at least one body part must be non-blank.
|
|
func NewMailContent(kind MailKind, templateVersion, subject, text, html string) (MailContent, error) {
|
|
if _, err := ParseMailKind(string(kind)); err != nil {
|
|
return MailContent{}, fmt.Errorf("domain.NewMailContent - validate kind: %w", err)
|
|
}
|
|
if err := validateMailContent(kind, templateVersion, subject, text, html); err != nil {
|
|
return MailContent{}, err
|
|
}
|
|
return MailContent{value: &mailContentValue{
|
|
kind: kind,
|
|
templateVersion: templateVersion,
|
|
subject: subject,
|
|
text: text,
|
|
html: html,
|
|
hash: MailContentHash(templateVersion, subject, text, html),
|
|
}}, nil
|
|
}
|
|
|
|
// RestoreMailContent rebuilds stored content and checks it against the
|
|
// stored hash. A mismatch wraps ErrMailContentIntegrity.
|
|
func RestoreMailContent(kind MailKind, templateVersion, subject, text, html string, hash []byte) (MailContent, error) {
|
|
content, err := NewMailContent(kind, templateVersion, subject, text, html)
|
|
if err != nil {
|
|
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - validate stored content: %w", err)
|
|
}
|
|
stored := content.value.hash
|
|
if subtle.ConstantTimeCompare(hash, stored[:]) != 1 {
|
|
return MailContent{}, fmt.Errorf("domain.RestoreMailContent - %w", ErrMailContentIntegrity)
|
|
}
|
|
return content, nil
|
|
}
|
|
|
|
// RestoreRedactedMailContent rebuilds the content of a token mail whose bodies
|
|
// were cleared after it reached a terminal status. Nothing can be checked
|
|
// against the hash any more, so the stored hash is kept as it is; the content
|
|
// has no bodies and can never be sent.
|
|
func RestoreRedactedMailContent(kind MailKind, templateVersion, subject string, hash []byte) (MailContent, error) {
|
|
const location = "domain.RestoreRedactedMailContent"
|
|
if _, err := ParseMailKind(string(kind)); err != nil || !kind.CarriesBearerToken() {
|
|
return MailContent{}, invalidMailContent("only a token mail has redacted content")
|
|
}
|
|
return restoreRedactedContent(location, kind, templateVersion, subject, hash)
|
|
}
|
|
|
|
// RestoreRedactedNotificationContent rebuilds the content of a notification
|
|
// whose bodies were cleared when it was cancelled. Like a redacted token mail,
|
|
// it keeps the subject and the hash and can never be sent.
|
|
func RestoreRedactedNotificationContent(templateVersion, subject string, hash []byte) (MailContent, error) {
|
|
return restoreRedactedContent("domain.RestoreRedactedNotificationContent", MailKindNotification, templateVersion, subject, hash)
|
|
}
|
|
|
|
func restoreRedactedContent(location string, kind MailKind, templateVersion, subject string, hash []byte) (MailContent, error) {
|
|
if !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v") ||
|
|
strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes {
|
|
return MailContent{}, fmt.Errorf("%s - stored version or subject is invalid: %w", location, ErrInvalidMailContent)
|
|
}
|
|
if len(hash) != MailContentHashSize {
|
|
return MailContent{}, fmt.Errorf("%s - stored hash has the wrong size: %w", location, ErrInvalidMailContent)
|
|
}
|
|
value := &mailContentValue{kind: kind, templateVersion: templateVersion, subject: subject, redacted: true}
|
|
copy(value.hash[:], hash)
|
|
return MailContent{value: value}, nil
|
|
}
|
|
|
|
// Redacted reports content whose bodies were cleared after the mail ended.
|
|
func (content MailContent) Redacted() bool { return content.read().redacted }
|
|
|
|
func validateMailContent(kind MailKind, templateVersion, subject, text, html string) error {
|
|
switch {
|
|
case !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v"):
|
|
return invalidMailContent("template version must be <kind>.v<N> of the content kind")
|
|
case !utf8.ValidString(subject) || !utf8.ValidString(text) || !utf8.ValidString(html):
|
|
return invalidMailContent("subject and body parts must be valid UTF-8")
|
|
case strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes:
|
|
return invalidMailContent(fmt.Sprintf("subject must have 1 to %d characters", maxMailSubjectRunes))
|
|
// A control character in the subject could inject header lines.
|
|
case strings.ContainsFunc(subject, isMailControlCharacter):
|
|
return invalidMailContent("subject must not contain control characters")
|
|
case strings.TrimSpace(text) == "" && strings.TrimSpace(html) == "":
|
|
return invalidMailContent("text or HTML part must not be blank")
|
|
case len(text) > maxMailPartBytes || len(html) > maxMailPartBytes:
|
|
return invalidMailContent("body parts must have at most 256 KiB each")
|
|
// PostgreSQL text cannot store NUL.
|
|
case strings.ContainsRune(text, 0) || strings.ContainsRune(html, 0):
|
|
return invalidMailContent("body parts must not contain NUL characters")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func isMailControlCharacter(character rune) bool {
|
|
return character < ' ' || character == 0x7f
|
|
}
|
|
|
|
func invalidMailContent(reason string) error {
|
|
return fmt.Errorf("domain.NewMailContent - %s: %w", reason, ErrInvalidMailContent)
|
|
}
|
|
|
|
// IsZero reports content not built by NewMailContent or RestoreMailContent.
|
|
func (content MailContent) IsZero() bool { return content.value == nil }
|
|
|
|
func (content MailContent) Kind() MailKind { return content.read().kind }
|
|
|
|
func (content MailContent) TemplateVersion() string { return content.read().templateVersion }
|
|
|
|
func (content MailContent) Subject() string { return content.read().subject }
|
|
|
|
// Text returns the plain-text part. It may hold a bearer token; never log it.
|
|
func (content MailContent) Text() string { return content.read().text }
|
|
|
|
// HTML returns the HTML part. It may hold a bearer token; never log it.
|
|
func (content MailContent) HTML() string { return content.read().html }
|
|
|
|
// Hash returns the SHA-256 content digest. It is not secret: a digest over a
|
|
// body that holds a 256-bit token cannot be reversed.
|
|
func (content MailContent) Hash() [MailContentHashSize]byte { return content.read().hash }
|
|
|
|
func (content MailContent) read() mailContentValue {
|
|
if content.value == nil {
|
|
return mailContentValue{}
|
|
}
|
|
return *content.value
|
|
}
|
|
|
|
func (content MailContent) String() string {
|
|
if content.value == nil {
|
|
return "[empty mail content]"
|
|
}
|
|
return fmt.Sprintf("[mail content %s %s, redacted]", content.value.templateVersion, hex.EncodeToString(content.value.hash[:]))
|
|
}
|
|
|
|
func (content MailContent) GoString() string { return content.String() }
|
|
|
|
// Format applies String to every verb; without it %+v would print the fields.
|
|
func (content MailContent) Format(state fmt.State, _ rune) {
|
|
_, _ = state.Write([]byte(content.String()))
|
|
}
|
|
|
|
func (content MailContent) LogValue() slog.Value {
|
|
value := content.read()
|
|
return slog.GroupValue(
|
|
slog.String("kind", string(value.kind)),
|
|
slog.String("template_version", value.templateVersion),
|
|
slog.String("content_hash", hex.EncodeToString(value.hash[:])),
|
|
)
|
|
}
|