feat(mail): add MailSender port and explicit provider selection

This commit is contained in:
shira committed 2026-10-06 00:38:58 +03:00
1 parent e7d0d92ef9
commit 6153887eb5
26 files changed
+1253 -29

No files matched your search

Whitespace-only changes.
@@ -0,0 +1,30 @@
// Package disabled provides the mail transport for EMAIL_PROVIDER=disabled.
package disabled
import (
"context"
"fmt"
"lincodex/backend/internal/port/outbound"
)
// Sender sends nothing. Every valid message is reported as
// outbound.ErrMailChannelUnavailable, never as an accepted or delivered
// message, so a caller cannot mistake the disabled mode for a delivery.
type Sender struct{}
var _ outbound.MailSender = (*Sender)(nil)
func NewSender() *Sender {
return &Sender{}
}
// Send validates the message first so that local runs without a transport
// still expose invalid messages, then reports the channel as unavailable. It
// logs nothing and keeps no copy of the recipient or the content.
func (sender *Sender) Send(_ context.Context, mail outbound.OutgoingMail) (outbound.SendResult, error) {
if err := mail.Validate(); err != nil {
return outbound.SendResult{}, fmt.Errorf("Sender.Send - validate mail: %w", err)
}
return outbound.SendResult{}, fmt.Errorf("Sender.Send - EMAIL_PROVIDER is disabled: %w", outbound.ErrMailChannelUnavailable)
}
@@ -0,0 +1,57 @@
package disabled_test
import (
"context"
"errors"
"strings"
"testing"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const testRecipient = "candidate@example.com"
func TestSenderReportsChannelUnavailableAndNeverAcceptance(t *testing.T) {
recipient, err := domain.NewEmailAddress(testRecipient)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
mail := outbound.OutgoingMail{
To: recipient,
Subject: "Confirm your address",
TextBody: "verification link with raw-token-value",
IdempotencyKey: "email_verification/1",
}
canceled, cancel := context.WithCancel(context.Background())
cancel()
for name, ctx := range map[string]context.Context{"active context": context.Background(), "canceled context": canceled} {
t.Run(name, func(t *testing.T) {
result, err := disabled.NewSender().Send(ctx, mail)
if !errors.Is(err, outbound.ErrMailChannelUnavailable) {
t.Fatalf("Send() error = %v, want ErrMailChannelUnavailable", err)
}
// Delivery and email verification code reads Outcome and
// ProviderMessageID; neither may suggest that a provider took the
// message.
if result != (outbound.SendResult{}) || result.Outcome == outbound.MailOutcomeAccepted || result.ProviderMessageID != "" {
t.Fatalf("Send() result = %+v, want the zero result", result)
}
if strings.Contains(err.Error(), testRecipient) || strings.Contains(err.Error(), "raw-token-value") {
t.Fatalf("Send() error exposes message content: %v", err)
}
})
}
}
func TestSenderRejectsInvalidMailBeforeReportingUnavailability(t *testing.T) {
result, err := disabled.NewSender().Send(context.Background(), outbound.OutgoingMail{})
if !errors.Is(err, outbound.ErrInvalidOutgoingMail) || errors.Is(err, outbound.ErrMailChannelUnavailable) {
t.Fatalf("Send() error = %v, want only ErrInvalidOutgoingMail", err)
}
if result != (outbound.SendResult{}) {
t.Fatalf("Send() result = %+v, want the zero result", result)
}
}
+29 -9
View File
@@ -16,6 +16,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
)
const (
@@ -28,6 +29,9 @@ type Application struct {
apiHandler http.Handler
metrics *prometheus.Metrics
logger *slog.Logger
// mailSender is the transport selected by EMAIL_PROVIDER. No usecase
// sends mail yet; the delivery layer will take it from here.
mailSender outbound.MailSender
}
func NewApplication(
@@ -35,8 +39,9 @@ func NewApplication(
apiHandler http.Handler,
metrics *prometheus.Metrics,
logger *slog.Logger,
mailSender outbound.MailSender,
) *Application {
return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger}
return &Application{config: config, apiHandler: apiHandler, metrics: metrics, logger: logger, mailSender: mailSender}
}
func Run() (runErr error) {
@@ -69,20 +74,35 @@ func Run() (runErr error) {
}
func run(ctx context.Context, config config.Config, logger *slog.Logger) error {
if err := config.Validate(); err != nil {
return fmt.Errorf("bootstrap.run - validate configuration: %w", err)
}
if err := migrateDatabase(ctx, config, logger); err != nil {
return fmt.Errorf("bootstrap.run - migrate database: %w", err)
}
application, cleanup, err := initialize(ctx, config, logger)
application, cleanup, err := start(ctx, config, logger)
if err != nil {
return fmt.Errorf("bootstrap.run - initialize application: %w", err)
return err
}
defer cleanup()
return application.run(ctx)
}
// start prepares the application without opening listeners. The mail
// transport is selected before migrations, so a configuration that cannot
// start never changes the database.
func start(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) {
if err := config.Validate(); err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - validate configuration: %w", err)
}
mailSender, err := newMailSender(config, logger)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - select mail transport: %w", err)
}
if err := migrateDatabase(ctx, config, logger); err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - migrate database: %w", err)
}
application, cleanup, err := initialize(ctx, config, logger, mailSender)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.start - initialize application: %w", err)
}
return application, cleanup, nil
}
func logLevel(value string) logkit.Level {
switch value {
case "debug":
+48
View File
@@ -0,0 +1,48 @@
package bootstrap
import (
"errors"
"fmt"
"log/slog"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/port/outbound"
)
// errMailTransportNotBuilt reports a valid EMAIL_PROVIDER whose transport has
// no adapter in this build yet. Startup fails instead of falling back to
// another transport.
var errMailTransportNotBuilt = errors.New("mail transport is not available in this build")
// newMailSender binds the MailSender port to the one transport that
// EMAIL_PROVIDER selects. Each provider maps to exactly one constructor, and
// a failure never falls back to another transport. A transport task replaces
// the errMailTransportNotBuilt return in its case with its constructor; until
// then resend and smtp fail startup after their settings are validated.
func newMailSender(settings config.Config, logger *slog.Logger) (outbound.MailSender, error) {
if err := settings.ValidateMail(); err != nil {
return nil, fmt.Errorf("bootstrap.newMailSender - validate mail settings: %w", err)
}
var sender outbound.MailSender
switch settings.EmailProvider {
case config.EmailProviderDisabled:
sender = disabled.NewSender()
case config.EmailProviderResend:
return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", errMailTransportNotBuilt)
case config.EmailProviderSMTP:
return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=smtp: %w", errMailTransportNotBuilt)
default:
// ValidateMail rejects unknown providers; this guards a new constant
// that has no case here yet.
return nil, errors.New("bootstrap.newMailSender - EMAIL_PROVIDER has no transport")
}
// Only the provider name is logged, never the sender, keys, or hosts.
logger.Info("mail transport selected", slog.String("email_provider", string(settings.EmailProvider)))
if settings.EmailProvider == config.EmailProviderDisabled {
logger.Warn("mail delivery is disabled; every send is reported as channel unavailable and nothing is sent")
}
return sender, nil
}
+186
View File
@@ -0,0 +1,186 @@
package bootstrap
import (
"bytes"
"errors"
"log/slog"
"strings"
"testing"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
testSenderAddress = "no-reply@example.com"
testResendAPIKey = "re_bootstrap-test-key"
testSMTPPassword = "bootstrap-smtp-password"
// unreachableDatabaseURL fails as soon as migrations try to use it, so a
// startup error that is not a migration error proves that the mail
// transport was selected before the database was touched.
unreachableDatabaseURL = "postgres://app:db-password@db:not-a-port/app"
)
// loadMailConfig loads the full process configuration with the given mail
// settings, as Run does from the environment.
func loadMailConfig(t *testing.T, mail map[string]string) config.Config {
t.Helper()
values := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_FROM": "Lincodex <" + testSenderAddress + ">",
"APP_PUBLIC_URL": "http://localhost:8080",
// Settings of every transport are present so that each case also
// shows that only the selected transport's settings are used.
"RESEND_API_KEY": testResendAPIKey,
"SMTP_HOST": "smtp.example.com",
"SMTP_PORT": "587",
"SMTP_USERNAME": "mailer",
"SMTP_PASSWORD": testSMTPPassword,
"SMTP_TLS_MODE": "starttls",
}
for key, value := range mail {
values[key] = value
}
settings, err := config.LoadFromEnv(func(key string) (string, bool) {
value, ok := values[key]
return value, ok
})
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
return settings
}
func captureLogs() (*slog.Logger, *bytes.Buffer) {
var logs bytes.Buffer
return slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})), &logs
}
func assertNoMailSecrets(t *testing.T, output string) {
t.Helper()
for _, secret := range []string{testSenderAddress, testResendAPIKey, testSMTPPassword, "smtp.example.com", "db-password"} {
if strings.Contains(output, secret) {
t.Fatalf("startup output exposes a mail setting: %s", output)
}
}
}
func TestStartWithDisabledMailSelectsTheDisabledTransport(t *testing.T) {
settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled"})
logger, logs := captureLogs()
application, cleanup, err := start(t.Context(), settings, logger)
if err != nil {
t.Fatalf("start() error = %v", err)
}
t.Cleanup(cleanup)
if _, ok := application.mailSender.(*disabled.Sender); !ok {
t.Fatalf("mail sender = %T, want *disabled.Sender", application.mailSender)
}
recipient, err := domain.NewEmailAddress("candidate@example.com")
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
result, err := application.mailSender.Send(t.Context(), outbound.OutgoingMail{
To: recipient,
Subject: "Confirm your address",
TextBody: "Confirm your address",
IdempotencyKey: "email_verification/harness",
})
if !errors.Is(err, outbound.ErrMailChannelUnavailable) {
t.Fatalf("Send() error = %v, want ErrMailChannelUnavailable", err)
}
if result.Outcome == outbound.MailOutcomeAccepted || result.ProviderMessageID != "" {
t.Fatalf("Send() result = %+v, disabled mode must never report acceptance", result)
}
output := logs.String()
if !strings.Contains(output, `msg="mail transport selected" email_provider=disabled`) {
t.Fatalf("startup did not log the selected provider: %s", output)
}
if !strings.Contains(output, "level=WARN msg=\"mail delivery is disabled") {
t.Fatalf("startup did not warn that mail is disabled: %s", output)
}
assertNoMailSecrets(t, output)
}
func TestStartRejectsTransportsThatThisBuildDoesNotProvide(t *testing.T) {
tests := []struct {
provider string
want string
}{
{provider: "resend", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=resend: mail transport is not available in this build"},
{provider: "smtp", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=smtp: mail transport is not available in this build"},
}
for _, test := range tests {
t.Run(test.provider, func(t *testing.T) {
settings := loadMailConfig(t, map[string]string{
"EMAIL_PROVIDER": test.provider,
"DATABASE_URL": unreachableDatabaseURL,
})
logger, logs := captureLogs()
application, cleanup, err := start(t.Context(), settings, logger)
if err == nil {
cleanup()
t.Fatalf("start() = %v, want a startup error", application)
}
if err.Error() != test.want || !errors.Is(err, errMailTransportNotBuilt) {
t.Fatalf("start() error = %q, want %q", err, test.want)
}
if strings.Contains(logs.String(), "mail transport selected") {
t.Fatalf("startup logged a selected transport after failing: %s", logs.String())
}
assertNoMailSecrets(t, err.Error()+logs.String())
})
}
}
func TestStartRejectsInvalidMailSettingsBeforeMigrations(t *testing.T) {
valid := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled", "DATABASE_URL": unreachableDatabaseURL})
tests := []struct {
name string
change func(*config.Config)
want string
}{
{name: "unknown provider", change: func(settings *config.Config) { settings.EmailProvider = "sendgrid" }, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled"},
{name: "missing provider", change: func(settings *config.Config) { settings.EmailProvider = "" }, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"},
{name: "missing sender", change: func(settings *config.Config) { settings.EmailFrom = "" }, want: "config.validateEmailFrom - EMAIL_FROM must be set"},
{name: "plain HTTP public URL", change: func(settings *config.Config) { settings.AppPublicURL = "http://lincodex.example" }, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https; http is allowed only for localhost, 127.0.0.1, or [::1]"},
{name: "timeout out of range", change: func(settings *config.Config) { settings.EmailTimeout = 0 }, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"},
{name: "Resend without key", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderResend }, want: "config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend"},
{name: "SMTP without settings", change: func(settings *config.Config) { settings.EmailProvider = config.EmailProviderSMTP }, want: "Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
settings := valid
test.change(&settings)
logger, logs := captureLogs()
_, _, err := start(t.Context(), settings, logger)
want := "bootstrap.start - validate configuration: " + test.want
if err == nil || err.Error() != want {
t.Fatalf("start() error = %v, want %q", err, want)
}
assertNoMailSecrets(t, err.Error()+logs.String())
})
}
}
func TestNewMailSenderValidatesSettingsItself(t *testing.T) {
settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "disabled"})
settings.EmailFrom = "not a mailbox"
logger, logs := captureLogs()
sender, err := newMailSender(settings, logger)
if sender != nil || err == nil || !strings.HasPrefix(err.Error(), "bootstrap.newMailSender - validate mail settings: config.validateEmailFrom - ") {
t.Fatalf("newMailSender() = (%v, %v), want a validation error", sender, err)
}
if logs.Len() != 0 {
t.Fatalf("newMailSender() logged a selection for invalid settings: %s", logs.String())
}
}
+9 -1
View File
@@ -19,10 +19,18 @@ import (
redisadapter "lincodex/backend/internal/adapter/secondary/redis"
"lincodex/backend/internal/adapter/secondary/seaweedfs"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/health"
)
func initialize(ctx context.Context, config config.Config, logger *slog.Logger) (*Application, func(), error) {
// initialize receives the mail sender that start selected, so an unusable
// EMAIL_PROVIDER fails before any dependency is created.
func initialize(
ctx context.Context,
config config.Config,
logger *slog.Logger,
mailSender outbound.MailSender,
) (*Application, func(), error) {
wire.Build(
wire.NewSet(
postgres.NewHealthChecker,
+5 -2
View File
@@ -17,13 +17,16 @@ import (
"lincodex/backend/internal/adapter/secondary/redis"
"lincodex/backend/internal/adapter/secondary/seaweedfs"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/health"
"log/slog"
)
// Injectors from wire.go:
func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger) (*Application, func(), error) {
// initialize receives the mail sender that start selected, so an unusable
// EMAIL_PROVIDER fails before any dependency is created.
func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, mailSender outbound.MailSender) (*Application, func(), error) {
healthChecker, cleanup, err := postgres.NewHealthChecker(ctx, config2)
if err != nil {
return nil, nil, err
@@ -52,7 +55,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger)
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger)
application := NewApplication(config2, httpHandler, metrics, logger, mailSender)
return application, func() {
cleanup3()
cleanup2()
+181
View File
@@ -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)
}
}
}