feat(mail): add MailSender port and explicit provider selection
This commit is contained in:
1 parent
e7d0d92ef9
commit
6153887eb5
26 files changed
+1253
-29
No files matched your search
@@ -0,0 +1,181 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxMailIdempotencyKeyLength follows the Resend Idempotency-Key limit of
|
||||
// 256 characters; SMTP has no such key, so the strictest provider rule
|
||||
// applies.
|
||||
maxMailIdempotencyKeyLength = 256
|
||||
redactedOutgoingMail = "[redacted outgoing mail]"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrMailChannelUnavailable reports that no mail transport is active
|
||||
// (EMAIL_PROVIDER=disabled). Nothing was sent and nothing was handed to a
|
||||
// provider. Callers must record the message as not sent; it is never a
|
||||
// delivery, and it never confirms an email address or satisfies an
|
||||
// account check.
|
||||
ErrMailChannelUnavailable = errors.New("mail channel unavailable")
|
||||
|
||||
// ErrInvalidOutgoingMail reports a message that fails
|
||||
// OutgoingMail.Validate. It is a caller bug, not a provider rejection, and
|
||||
// nothing was sent.
|
||||
ErrInvalidOutgoingMail = errors.New("invalid outgoing mail")
|
||||
)
|
||||
|
||||
// MailOutcome is what one transport attempt established about a message. The
|
||||
// zero value is not an outcome and must never be read as acceptance.
|
||||
type MailOutcome string
|
||||
|
||||
const (
|
||||
// MailOutcomeAccepted means the provider accepted the request and returned
|
||||
// a message ID. It does not mean the message was delivered or read.
|
||||
MailOutcomeAccepted MailOutcome = "accepted"
|
||||
|
||||
// MailOutcomeRejected means the provider answered and refused the
|
||||
// request; it did not take the message. Rejection says why.
|
||||
MailOutcomeRejected MailOutcome = "rejected"
|
||||
|
||||
// MailOutcomeUnknown means the request may have reached the provider but
|
||||
// no conclusive answer came back, for example a timeout or a connection
|
||||
// lost after the request was written. The message may or may not have
|
||||
// been accepted (delivery_uncertain). It is not a failure: a retry must
|
||||
// reuse the same IdempotencyKey so a provider that supports keys can
|
||||
// deduplicate it.
|
||||
MailOutcomeUnknown MailOutcome = "unknown"
|
||||
)
|
||||
|
||||
// MailRejection is a provider-independent reason for MailOutcomeRejected that
|
||||
// the delivery layer can map to its retry policy. It never carries provider
|
||||
// text, recipients, or message content.
|
||||
type MailRejection string
|
||||
|
||||
const (
|
||||
// MailRejectionPermanent means the provider will not accept this message,
|
||||
// for example an unverified sender domain or a suppressed recipient.
|
||||
MailRejectionPermanent MailRejection = "permanent"
|
||||
|
||||
// MailRejectionInvalidRequest means the provider rejected the request
|
||||
// shape or credentials; retrying the same request cannot help.
|
||||
MailRejectionInvalidRequest MailRejection = "invalid_request"
|
||||
|
||||
// MailRejectionRateLimited means a short-term rate limit; RetryAfter may
|
||||
// say when to try again.
|
||||
MailRejectionRateLimited MailRejection = "rate_limited"
|
||||
|
||||
// MailRejectionQuotaExhausted means a daily or monthly sending quota is
|
||||
// used up; retrying before the quota resets cannot help.
|
||||
MailRejectionQuotaExhausted MailRejection = "quota_exhausted"
|
||||
|
||||
// MailRejectionTemporary means a transient provider-side refusal, such as
|
||||
// a 5xx answer or an SMTP 4xx reply, that a later attempt may overcome.
|
||||
MailRejectionTemporary MailRejection = "temporary"
|
||||
)
|
||||
|
||||
// OutgoingMail is one rendered message. The sender address comes from the
|
||||
// transport configuration (EMAIL_FROM), so usecases and templates never choose
|
||||
// or depend on it, nor on the provider.
|
||||
//
|
||||
// String, GoString, Format, and LogValue redact the whole message, because the
|
||||
// recipient and the bodies are personal data and a body can carry a
|
||||
// verification link. Read the fields directly where they are needed.
|
||||
type OutgoingMail struct {
|
||||
To domain.EmailAddress
|
||||
Subject string
|
||||
TextBody string
|
||||
HTMLBody string
|
||||
|
||||
// IdempotencyKey is stable for one logical delivery across every retry,
|
||||
// for example "email_verification/<token id>". A transport that supports
|
||||
// provider-side deduplication sends it; others ignore it. It must not
|
||||
// contain personal data.
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
// Validate reports a message that no transport could send. Errors wrap
|
||||
// ErrInvalidOutgoingMail and name only the field, never its value.
|
||||
func (mail OutgoingMail) Validate() error {
|
||||
if mail.To.IsZero() {
|
||||
return invalidOutgoingMail("recipient must be set")
|
||||
}
|
||||
if strings.TrimSpace(mail.Subject) == "" {
|
||||
return invalidOutgoingMail("subject must not be empty")
|
||||
}
|
||||
// A control character in the subject could inject header lines.
|
||||
if strings.ContainsFunc(mail.Subject, isControlCharacter) {
|
||||
return invalidOutgoingMail("subject must not contain control characters")
|
||||
}
|
||||
if strings.TrimSpace(mail.TextBody) == "" && strings.TrimSpace(mail.HTMLBody) == "" {
|
||||
return invalidOutgoingMail("text or HTML body must not be empty")
|
||||
}
|
||||
if length := len(mail.IdempotencyKey); length == 0 || length > maxMailIdempotencyKeyLength {
|
||||
return invalidOutgoingMail("idempotency key must have 1 to 256 characters")
|
||||
}
|
||||
for index := range len(mail.IdempotencyKey) {
|
||||
if character := mail.IdempotencyKey[index]; character <= ' ' || character > '~' {
|
||||
return invalidOutgoingMail("idempotency key must contain printable ASCII characters without spaces")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mail OutgoingMail) String() string { return redactedOutgoingMail }
|
||||
|
||||
func (mail OutgoingMail) GoString() string { return redactedOutgoingMail }
|
||||
|
||||
// Format redacts every verb; without it %+v would print the fields.
|
||||
func (mail OutgoingMail) Format(state fmt.State, _ rune) {
|
||||
_, _ = state.Write([]byte(redactedOutgoingMail))
|
||||
}
|
||||
|
||||
func (mail OutgoingMail) LogValue() slog.Value { return slog.StringValue(redactedOutgoingMail) }
|
||||
|
||||
func isControlCharacter(character rune) bool {
|
||||
return character < ' ' || character == 0x7f
|
||||
}
|
||||
|
||||
func invalidOutgoingMail(reason string) error {
|
||||
return fmt.Errorf("OutgoingMail.Validate - %s: %w", reason, ErrInvalidOutgoingMail)
|
||||
}
|
||||
|
||||
// SendResult is the outcome of one attempt that may have reached a provider.
|
||||
type SendResult struct {
|
||||
Outcome MailOutcome
|
||||
|
||||
// ProviderMessageID is set only for MailOutcomeAccepted.
|
||||
ProviderMessageID string
|
||||
|
||||
// Rejection is set only for MailOutcomeRejected.
|
||||
Rejection MailRejection
|
||||
|
||||
// RetryAfter is the provider's requested wait for a rejected attempt, or
|
||||
// zero when the provider gave none.
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
// MailSender hands one message to the configured transport.
|
||||
//
|
||||
// Send makes exactly one attempt and never retries; retries, backoff, and
|
||||
// deduplication belong to the delivery layer, which also records outcomes.
|
||||
// A nil error comes with an Outcome of accepted, rejected, or unknown. A
|
||||
// non-nil error means the message certainly did not leave the process: it
|
||||
// wraps ErrMailChannelUnavailable when no transport is active,
|
||||
// ErrInvalidOutgoingMail for an invalid message, or the context error when
|
||||
// ctx ended before the request was sent. The returned SendResult is then
|
||||
// zero and must be ignored.
|
||||
//
|
||||
// Errors and logs never include recipients, subjects, bodies, credentials, or
|
||||
// raw provider responses.
|
||||
type MailSender interface {
|
||||
Send(ctx context.Context, mail OutgoingMail) (SendResult, error)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package outbound_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
testRecipient = "Private.Person@example.com"
|
||||
testSubject = "Confirm your address"
|
||||
testTextBody = "Open https://lincodex.example/verify?token=raw-token-value"
|
||||
testHTMLBody = "<a href=\"https://lincodex.example/verify?token=raw-token-value\">Confirm</a>"
|
||||
)
|
||||
|
||||
func validOutgoingMail(t *testing.T) outbound.OutgoingMail {
|
||||
t.Helper()
|
||||
recipient, err := domain.NewEmailAddress(testRecipient)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailAddress() error = %v", err)
|
||||
}
|
||||
return outbound.OutgoingMail{
|
||||
To: recipient,
|
||||
Subject: testSubject,
|
||||
TextBody: testTextBody,
|
||||
HTMLBody: testHTMLBody,
|
||||
IdempotencyKey: "email_verification/0190d3f4-0000-7000-8000-000000000001",
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutgoingMailValidateAcceptsOneBody(t *testing.T) {
|
||||
textOnly := validOutgoingMail(t)
|
||||
textOnly.HTMLBody = ""
|
||||
htmlOnly := validOutgoingMail(t)
|
||||
htmlOnly.TextBody = ""
|
||||
longestKey := validOutgoingMail(t)
|
||||
longestKey.IdempotencyKey = strings.Repeat("k", 256)
|
||||
for name, mail := range map[string]outbound.OutgoingMail{"text only": textOnly, "HTML only": htmlOnly, "256-character key": longestKey} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if err := mail.Validate(); err != nil {
|
||||
t.Fatalf("Validate() error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutgoingMailValidateRejectsUnsendableMail(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*outbound.OutgoingMail)
|
||||
}{
|
||||
{name: "missing recipient", change: func(mail *outbound.OutgoingMail) { mail.To = domain.EmailAddress{} }},
|
||||
{name: "blank subject", change: func(mail *outbound.OutgoingMail) { mail.Subject = " " }},
|
||||
{name: "subject header injection", change: func(mail *outbound.OutgoingMail) { mail.Subject = testSubject + "\r\nBcc: other@example.com" }},
|
||||
{name: "no body", change: func(mail *outbound.OutgoingMail) { mail.TextBody, mail.HTMLBody = " ", "" }},
|
||||
{name: "missing idempotency key", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "" }},
|
||||
{name: "idempotency key too long", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = strings.Repeat("k", 257) }},
|
||||
{name: "idempotency key with space", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "email verification" }},
|
||||
{name: "idempotency key non-ASCII", change: func(mail *outbound.OutgoingMail) { mail.IdempotencyKey = "письмо/1" }},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
mail := validOutgoingMail(t)
|
||||
test.change(&mail)
|
||||
err := mail.Validate()
|
||||
if !errors.Is(err, outbound.ErrInvalidOutgoingMail) {
|
||||
t.Fatalf("Validate() error = %v, want ErrInvalidOutgoingMail", err)
|
||||
}
|
||||
if !strings.HasPrefix(err.Error(), "OutgoingMail.Validate - ") {
|
||||
t.Fatalf("Validate() error = %q, want the OutgoingMail.Validate location", err)
|
||||
}
|
||||
for _, private := range []string{testRecipient, testSubject, "raw-token-value", "other@example.com"} {
|
||||
if strings.Contains(err.Error(), private) {
|
||||
t.Fatalf("Validate() error exposes message content: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutgoingMailIsRedacted(t *testing.T) {
|
||||
mail := validOutgoingMail(t)
|
||||
wrapper := struct{ Mail outbound.OutgoingMail }{Mail: mail}
|
||||
var logs bytes.Buffer
|
||||
slog.New(slog.NewJSONHandler(&logs, nil)).Info("redaction", "mail", mail, slog.Group("nested", "mail", mail))
|
||||
formatted := fmt.Sprintf("%v %+v %#v %s %q %x %d %+v %#v", mail, mail, mail, mail, mail, mail, mail, wrapper, wrapper) + logs.String()
|
||||
for _, private := range []string{"Private.Person", "private.person", testSubject, "raw-token-value", "Confirm"} {
|
||||
if strings.Contains(formatted, private) {
|
||||
t.Fatalf("formatted output exposes message content: %s", formatted)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user