feat(mail): add Resend API transport

This commit is contained in:
shira committed 2026-10-06 02:38:17 +03:00
1 parent 1aa7a9feaf
commit c85b642d32
13 files changed
+1387 -63

No files matched your search

@@ -0,0 +1,21 @@
package resend
import (
"bytes"
"fmt"
"log/slog"
"strings"
"testing"
)
func TestCredentialRedactsItself(t *testing.T) {
const key = "re_credential-test-key"
value := credential{authorization: "Bearer " + key}
var logs bytes.Buffer
slog.New(slog.NewTextHandler(&logs, nil)).Info("credential", slog.Any("value", value), slog.Any("pointer", &value))
output := fmt.Sprintf("%v %+v %#v %s %q", value, value, value, value, value) + fmt.Sprint(&value) + logs.String()
if strings.Contains(output, key) {
t.Fatalf("printed credential exposes the API key: %s", output)
}
}
@@ -0,0 +1,9 @@
package resend
import "time"
// NewSenderWithEndpoint lets tests point the sender at a local fake and fix
// the clock. Production code can only use the documented endpoint.
func NewSenderWithEndpoint(apiKey, from string, timeout time.Duration, endpoint string, now func() time.Time) (*Sender, error) {
return newSender(apiKey, from, timeout, endpoint, now)
}
@@ -0,0 +1,268 @@
package resend
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
"lincodex/backend/internal/port/outbound"
)
// Error names that change the outcome. Other known names are classified by
// status alone.
const (
errorNameValidation = "validation_error"
errorNameInvalidIdempotent = "invalid_idempotent_request"
errorNameResourceLocked = "resource_locked"
errorNameDailyQuota = "daily_quota_exceeded"
errorNameMonthlyQuota = "monthly_quota_exceeded"
errorNameServiceUnavailable = "service_unavailable"
)
// knownErrorNames is the fixed set of Resend error names that may become
// SendResult.ProviderCode: the names on
// https://resend.com/docs/api-reference/errors plus the older names that the
// official Node SDK still lists (invalid_api_key, invalid_from_address,
// invalid_access, invalid_region, security_error, internal_server_error). A
// name outside the set is treated as no name, so provider text never leaves
// the adapter.
var knownErrorNames = map[string]struct{}{
"invalid_idempotency_key": {},
errorNameValidation: {},
"missing_api_key": {},
"restricted_api_key": {},
"invalid_api_key": {},
"suspended_api_key": {},
"invalid_permission": {},
"invalid_access": {},
"invalid_from_address": {},
"invalid_region": {},
"email_above_quota": {},
"not_found": {},
"method_not_allowed": {},
"concurrent_idempotent_requests": {},
errorNameInvalidIdempotent: {},
errorNameResourceLocked: {},
"invalid_attachment": {},
"invalid_parameter": {},
"missing_required_field": {},
"missing_required_parameter": {},
errorNameDailyQuota: {},
errorNameMonthlyQuota: {},
"rate_limit_exceeded": {},
"security_error": {},
"application_error": {},
"internal_server_error": {},
errorNameServiceUnavailable: {},
}
const (
// maxProviderMessageIDLength bounds the stored ID. Resend returns UUIDs.
maxProviderMessageIDLength = 128
// maxRetryAfter caps a provider wait hint so that a malformed header
// cannot park a delivery for longer than a daily quota reset.
maxRetryAfter = 24 * time.Hour
)
// providerAnswer is an HTTP answer. body is set only when complete is true:
// the body was read without error and within maxResponseBodyBytes.
type providerAnswer struct {
status int
header http.Header
body []byte
complete bool
}
// classifyResponse maps an HTTP answer to the port outcome. The body is only
// parsed for the message ID or the error name; neither the body nor the
// provider's message is kept. A rejected or unknown result carries the error
// name as ProviderCode when it is in knownErrorNames.
//
// - 2xx with a valid ID: accepted. Without one the request may still have
// been accepted, so the outcome is unknown.
// - 3xx: rejected invalid_request. The API documents no redirect, the
// request did not reach the send handler, and repeating it gets the same
// redirect.
// - 403 validation_error (unverified sender domain; without one Resend
// sends only testing emails to the account's own address): rejected
// permanent.
// - 408 and 409 resource_locked: rejected temporary.
// - 409 concurrent_idempotent_requests: unknown. Another request with the
// same key is in progress and may be accepted; a later retry with the
// same key gets its result.
// - 409 invalid_idempotent_request: unknown. The key was used with another
// body in the last 24 hours, so an earlier request under this key may
// have been accepted. Repeating cannot succeed and a new key could send
// the message twice: the delivery layer stops and escalates on this code.
// - 409 without a known name: unknown, since it may be either of the above.
// - 429 daily_quota_exceeded: quota_exhausted until the next midnight UTC;
// 429 monthly_quota_exceeded: quota_exhausted without a wait hint, the
// reset depends on the billing cycle; other 429: rate_limited with
// Retry-After or RateLimit-Reset.
// - other 4xx (validation, key, permission, not found): invalid_request.
// - 503 service_unavailable: rejected temporary; the API refused the
// request as a whole.
// - other 5xx, including 500 application_error and internal_server_error:
// unknown. The API failed while handling the request, or a proxy or
// gateway answered, so the message may have been accepted.
func classifyResponse(answer providerAnswer, now time.Time) outbound.SendResult {
status := answer.status
switch {
case status >= 200 && status < 300:
if id, ok := parseMessageID(answer); ok {
return outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: id}
}
return unknownResult(0)
case status >= 300 && status < 400:
return rejected(outbound.MailRejectionInvalidRequest, 0)
}
name := parseErrorName(answer)
result := classifyError(status, name, answer.header, now)
result.ProviderCode = outbound.MailProviderCode(name)
return result
}
func classifyError(status int, name string, header http.Header, now time.Time) outbound.SendResult {
if status >= 500 {
if status == http.StatusServiceUnavailable && name == errorNameServiceUnavailable {
return rejected(outbound.MailRejectionTemporary, retryAfter(header, now))
}
return unknownResult(0)
}
switch status {
case http.StatusForbidden:
if name == errorNameValidation {
return rejected(outbound.MailRejectionPermanent, 0)
}
case http.StatusRequestTimeout:
return rejected(outbound.MailRejectionTemporary, retryAfter(header, now))
case http.StatusConflict:
if name == errorNameResourceLocked {
return rejected(outbound.MailRejectionTemporary, retryAfter(header, now))
}
return unknownResult(retryAfter(header, now))
case http.StatusTooManyRequests:
return classifyTooManyRequests(name, header, now)
}
return rejected(outbound.MailRejectionInvalidRequest, 0)
}
func classifyTooManyRequests(name string, header http.Header, now time.Time) outbound.SendResult {
switch name {
case errorNameDailyQuota:
// The daily quota resets at midnight UTC, not after a rolling day.
return rejected(outbound.MailRejectionQuotaExhausted, untilNextUTCMidnight(now))
case errorNameMonthlyQuota:
return rejected(outbound.MailRejectionQuotaExhausted, 0)
default:
return rejected(outbound.MailRejectionRateLimited, rateLimitWait(header, now))
}
}
func rejected(reason outbound.MailRejection, wait time.Duration) outbound.SendResult {
return outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: reason, RetryAfter: wait}
}
func unknownResult(wait time.Duration) outbound.SendResult {
return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, RetryAfter: wait}
}
// parseMessageID reads {"id": "..."} and accepts only an ID that is safe to
// store and log.
func parseMessageID(answer providerAnswer) (string, bool) {
if !answer.complete {
return "", false
}
var success struct {
ID string `json:"id"`
}
if err := json.Unmarshal(answer.body, &success); err != nil {
return "", false
}
if len(success.ID) == 0 || len(success.ID) > maxProviderMessageIDLength || strings.ContainsFunc(success.ID, isNotIDCharacter) {
return "", false
}
return success.ID, true
}
// parseErrorName reads the name of {"statusCode", "name", "message"}. It
// returns "" for any name outside knownErrorNames, so provider text never
// flows further.
func parseErrorName(answer providerAnswer) string {
if !answer.complete {
return ""
}
var failure struct {
Name string `json:"name"`
}
if err := json.Unmarshal(answer.body, &failure); err != nil {
return ""
}
if _, known := knownErrorNames[failure.Name]; !known {
return ""
}
return failure.Name
}
// rateLimitWait prefers Retry-After and falls back to RateLimit-Reset, the
// seconds until the rate limit window resets.
func rateLimitWait(header http.Header, now time.Time) time.Duration {
if wait := retryAfter(header, now); wait > 0 {
return wait
}
return parseSeconds(header.Get("Ratelimit-Reset"))
}
// retryAfter reads Retry-After as delta seconds or as an HTTP date.
func retryAfter(header http.Header, now time.Time) time.Duration {
value := strings.TrimSpace(header.Get("Retry-After"))
if value == "" {
return 0
}
if wait := parseSeconds(value); wait > 0 {
return wait
}
date, err := http.ParseTime(value)
if err != nil {
return 0
}
return capWait(date.Sub(now))
}
func parseSeconds(value string) time.Duration {
seconds, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64)
if err != nil || seconds <= 0 {
return 0
}
if seconds > int64(maxRetryAfter/time.Second) {
return maxRetryAfter
}
return time.Duration(seconds) * time.Second
}
func untilNextUTCMidnight(now time.Time) time.Duration {
current := now.UTC()
midnight := time.Date(current.Year(), current.Month(), current.Day()+1, 0, 0, 0, 0, time.UTC)
return capWait(midnight.Sub(current))
}
func capWait(wait time.Duration) time.Duration {
switch {
case wait <= 0:
return 0
case wait > maxRetryAfter:
return maxRetryAfter
default:
return wait
}
}
func isNotIDCharacter(character rune) bool {
isLetter := (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z')
isDigit := character >= '0' && character <= '9'
return !isLetter && !isDigit && character != '-' && character != '_'
}
@@ -0,0 +1,272 @@
// Package resend provides the mail transport for EMAIL_PROVIDER=resend: one
// POST /emails request to the Resend HTTP API per Send, built with net/http
// and no provider SDK.
package resend
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptrace"
"net/url"
"strings"
"sync/atomic"
"time"
"lincodex/backend/internal/port/outbound"
)
const (
// defaultEndpoint is the documented send endpoint. Only tests replace it,
// through export_test.go, so a deployment cannot point the API key at
// another host.
defaultEndpoint = "https://api.resend.com/emails"
// userAgent identifies the backend; Resend refuses requests without a
// User-Agent header.
userAgent = "lincodex-backend"
// maxResponseBodyBytes bounds what is read from any answer. A success is a
// small {"id": ...} object and an error a short {statusCode, name,
// message} object, so a larger body is not a Resend answer.
maxResponseBodyBytes = 64 << 10
// maxResponseHeaderBytes bounds the response headers the same way.
maxResponseHeaderBytes = 64 << 10
)
// Sender implements outbound.MailSender with the Resend API.
//
// Each Send makes exactly one HTTP request: the client follows no redirects,
// the transport never replays a request, and the adapter itself has no retry
// loop. Retries belong to the delivery layer, which repeats the same
// IdempotencyKey and the same content so Resend can deduplicate them.
//
// The adapter logs nothing. Its errors and results never contain the API
// key, the recipient, the subject, the bodies, or the provider's response
// body.
type Sender struct {
client *http.Client
endpoint string
from string
timeout time.Duration
now func() time.Time
// credential is behind a pointer so that printing a Sender, even with
// %+v or %#v, shows an address instead of the API key.
credential *credential
}
const redactionMarker = "[redacted Resend API key]"
// credential holds the Authorization header value. It redacts itself in fmt
// and slog output in case it is ever printed directly.
type credential struct {
authorization string
}
func (credential) String() string { return redactionMarker }
func (credential) GoString() string { return redactionMarker }
// Format redacts every verb; without it %+v would print the field.
func (credential) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactionMarker))
}
func (credential) LogValue() slog.Value { return slog.StringValue(redactionMarker) }
var _ outbound.MailSender = (*Sender)(nil)
// NewSender builds the transport. It validates its arguments and makes no
// network call, so startup does not depend on the provider being reachable.
// timeout bounds one whole attempt: connecting, writing the request, and
// reading the answer.
func NewSender(apiKey, from string, timeout time.Duration) (*Sender, error) {
return newSender(apiKey, from, timeout, defaultEndpoint, time.Now)
}
func newSender(apiKey, from string, timeout time.Duration, endpoint string, now func() time.Time) (*Sender, error) {
// Messages name the argument but never echo its value.
if apiKey == "" || strings.ContainsFunc(apiKey, isNotHeaderSafe) {
return nil, errors.New("resend.NewSender - API key must be non-empty printable ASCII without whitespace")
}
if strings.TrimSpace(from) == "" || strings.ContainsFunc(from, isControlCharacter) {
return nil, errors.New("resend.NewSender - sender address must be set and contain no control characters")
}
if timeout <= 0 {
return nil, errors.New("resend.NewSender - timeout must be positive")
}
target, err := url.Parse(endpoint)
if err != nil || (target.Scheme != "https" && target.Scheme != "http") || target.Host == "" {
return nil, errors.New("resend.NewSender - endpoint must be an absolute http or https URL")
}
return &Sender{
client: newHTTPClient(timeout),
endpoint: endpoint,
from: from,
timeout: timeout,
now: now,
credential: &credential{authorization: "Bearer " + apiKey},
}, nil
}
// newHTTPClient builds a client that sends one request per call.
//
// Redirects are returned instead of followed: the API documents none, and
// following one would resend the API key and the message to another URL.
// Every send opens a fresh HTTP/1.1 connection. A kept-alive connection that
// the server closed while idle fails after the request was handed to it, so
// the transport could not tell "never seen" from "maybe accepted" and would
// report a false unknown; net/http also never replays a request on a fresh
// connection. Mail volume is low, so the extra TLS handshake is cheap. Proxy
// settings follow the standard HTTPS_PROXY and NO_PROXY environment, as with
// any Go HTTP client.
func newHTTPClient(timeout time.Duration) *http.Client {
protocols := new(http.Protocols)
protocols.SetHTTP1(true)
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: timeout}).DialContext,
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
TLSHandshakeTimeout: timeout,
ResponseHeaderTimeout: timeout,
MaxResponseHeaderBytes: maxResponseHeaderBytes,
DisableKeepAlives: true,
Protocols: protocols,
}
return &http.Client{
Transport: transport,
Timeout: timeout,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
// sendRequest is the documented POST /emails body. A blank text or HTML part
// is omitted; Validate guarantees that at least one part is not blank.
type sendRequest struct {
From string `json:"from"`
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text,omitempty"`
HTML string `json:"html,omitempty"`
}
// Send hands one message to Resend with one HTTP request.
//
// A nil error comes with an accepted, rejected, or unknown result; see
// classifyResponse for the mapping of answers. When the request failed
// before it was completely written, no complete request reached the
// provider: the result is a temporary rejection, or the context error if the
// caller's context ended. When it failed after that, the provider may have
// accepted the message, so the result is unknown (delivery_uncertain).
func (sender *Sender) Send(ctx 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)
}
if err := ctx.Err(); err != nil {
return outbound.SendResult{}, fmt.Errorf("Sender.Send - context ended before the request was sent: %w", err)
}
body, err := json.Marshal(sendRequest{
From: sender.from,
To: []string{mail.To.Address()},
Subject: mail.Subject,
Text: nonBlank(mail.TextBody),
HTML: nonBlank(mail.HTMLBody),
})
if err != nil {
// Marshaling plain strings cannot fail; the cause is dropped because a
// JSON error could quote the content.
return outbound.SendResult{}, errors.New("Sender.Send - encode request body")
}
attemptCtx, cancel := context.WithTimeout(ctx, sender.timeout)
defer cancel()
var written atomic.Bool
attemptCtx = httptrace.WithClientTrace(attemptCtx, &httptrace.ClientTrace{
WroteRequest: func(info httptrace.WroteRequestInfo) {
if info.Err == nil {
written.Store(true)
}
},
})
request, err := http.NewRequestWithContext(attemptCtx, http.MethodPost, sender.endpoint, bytes.NewReader(body))
if err != nil {
// The endpoint was validated by the constructor; the cause would
// include the URL.
return outbound.SendResult{}, errors.New("Sender.Send - build request")
}
// Without GetBody the transport cannot replay the body. net/http treats a
// POST with an Idempotency-Key header and a GetBody as replayable and
// would silently resend it on a reused connection that broke after the
// request was written. Keep-alives are off as well; this keeps the rule
// even if connection reuse is ever turned back on.
request.GetBody = nil
request.Header.Set("Authorization", sender.credential.authorization)
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", userAgent)
request.Header.Set("Idempotency-Key", mail.IdempotencyKey)
response, err := sender.client.Do(request)
if err != nil {
// The error is not wrapped: it can contain the URL, and the result
// already says everything the delivery layer may act on.
return failedAttempt(ctx, written.Load())
}
defer func() {
// The body was read already; a close error cannot change the outcome.
_ = response.Body.Close()
}()
payload, readErr := io.ReadAll(io.LimitReader(response.Body, maxResponseBodyBytes+1))
answer := providerAnswer{status: response.StatusCode, header: response.Header}
if readErr == nil && len(payload) <= maxResponseBodyBytes {
answer.body = payload
answer.complete = true
}
return classifyResponse(answer, sender.now()), nil
}
// failedAttempt maps a request that got no HTTP answer.
func failedAttempt(ctx context.Context, written bool) (outbound.SendResult, error) {
if written {
return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, nil
}
if err := ctx.Err(); err != nil {
return outbound.SendResult{}, fmt.Errorf("Sender.Send - context ended before the request was sent: %w", err)
}
// DNS, connect, and TLS failures, or the attempt timeout before the
// request was written: no complete request reached Resend, and a later
// attempt may succeed.
return outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary}, nil
}
// nonBlank drops a part that holds only whitespace, so Resend does not get
// an empty text or HTML alternative.
func nonBlank(part string) string {
if strings.TrimSpace(part) == "" {
return ""
}
return part
}
// isNotHeaderSafe reports a character that cannot appear in the
// Authorization header value.
func isNotHeaderSafe(character rune) bool {
return character <= ' ' || character > '~'
}
func isControlCharacter(character rune) bool {
return character < ' ' || character == 0x7f
}
@@ -0,0 +1,618 @@
package resend_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
testAPIKey = "re_test-secret-api-key"
testFrom = "Lincodex <no-reply@example.com>"
testRecipient = "candidate@example.com"
testSubject = "Confirm your address"
testTextBody = "Open the link: https://lincodex.example/verify-email#token=raw-token-value"
testHTMLBody = "<p>Open <a href=\"https://lincodex.example/verify-email#token=raw-token-value\">the link</a></p>"
testIdempotencyKey = "email_verification/0190a5e4-7c1b-7d2e-9f00-1a2b3c4d5e6f"
testMessageID = "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794"
testTimeout = 2 * time.Second
// shortTimeout keeps the timeout cases fast; the configured minimum
// (EMAIL_TIMEOUT=1s) is enforced by config, not by the adapter.
shortTimeout = 200 * time.Millisecond
)
// fixedNow is 21:30 UTC, two and a half hours before the daily quota reset.
var fixedNow = time.Date(2026, time.October, 6, 21, 30, 0, 0, time.UTC)
// secrets must never appear in a result, an error, or a printed sender.
var secrets = []string{testAPIKey, testRecipient, testSubject, "raw-token-value", "the link"}
type capturedRequest struct {
method string
path string
header http.Header
body []byte
}
// fakeResend counts every request that reaches it and records the first.
type fakeResend struct {
server *httptest.Server
requests atomic.Int32
mu sync.Mutex
captured []capturedRequest
}
func newFakeResend(t *testing.T, respond http.HandlerFunc) *fakeResend {
t.Helper()
fake := &fakeResend{}
fake.server = httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
fake.requests.Add(1)
body, _ := io.ReadAll(request.Body)
fake.mu.Lock()
fake.captured = append(fake.captured, capturedRequest{method: request.Method, path: request.URL.Path, header: request.Header.Clone(), body: body})
fake.mu.Unlock()
respond(writer, request)
}))
t.Cleanup(fake.server.Close)
return fake
}
func (fake *fakeResend) sender(t *testing.T, timeout time.Duration) *resend.Sender {
t.Helper()
sender, err := resend.NewSenderWithEndpoint(testAPIKey, testFrom, timeout, fake.server.URL+"/emails", func() time.Time { return fixedNow })
if err != nil {
t.Fatalf("NewSenderWithEndpoint() error = %v", err)
}
return sender
}
func (fake *fakeResend) lastRequest(t *testing.T) capturedRequest {
t.Helper()
fake.mu.Lock()
defer fake.mu.Unlock()
if len(fake.captured) == 0 {
t.Fatal("the fake received no request")
}
return fake.captured[len(fake.captured)-1]
}
func testMail(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: testIdempotencyKey,
}
}
func respondJSON(status int, body string, headers map[string]string) http.HandlerFunc {
return func(writer http.ResponseWriter, _ *http.Request) {
for key, value := range headers {
writer.Header().Set(key, value)
}
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(status)
_, _ = io.WriteString(writer, body)
}
}
// providerError is the documented error shape. The message deliberately
// echoes secrets to prove that provider text never leaves the adapter.
func providerError(status int, name string) string {
return fmt.Sprintf(`{"statusCode":%d,"name":%q,"message":"rejected %s for %s with %s"}`, status, name, testSubject, testRecipient, testAPIKey)
}
// assertNoLeak checks every way the delivery layer could print what Send
// returned.
func assertNoLeak(t *testing.T, result outbound.SendResult, err error) {
t.Helper()
var logs bytes.Buffer
slog.New(slog.NewTextHandler(&logs, nil)).Info("send", slog.Any("result", result), slog.Any("error", err))
output := fmt.Sprintf("%v %+v %#v %v", result, result, result, err) + logs.String()
for _, secret := range secrets {
if strings.Contains(output, secret) {
t.Fatalf("Send() output exposes %q: %s", secret, output)
}
}
}
func TestSendPostsTheDocumentedRequestOnce(t *testing.T) {
fake := newFakeResend(t, respondJSON(http.StatusOK, `{"id":"`+testMessageID+`"}`, nil))
result, err := fake.sender(t, testTimeout).Send(t.Context(), testMail(t))
if err != nil {
t.Fatalf("Send() error = %v", err)
}
want := outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
if result != want {
t.Fatalf("Send() = %+v, want %+v", result, want)
}
if got := fake.requests.Load(); got != 1 {
t.Fatalf("requests = %d, want exactly 1", got)
}
request := fake.lastRequest(t)
if request.method != http.MethodPost || request.path != "/emails" {
t.Fatalf("request = %s %s, want POST /emails", request.method, request.path)
}
// The Authorization value is compared, never printed.
if request.header.Get("Authorization") != "Bearer "+testAPIKey {
t.Fatal("Authorization header is not the bearer API key")
}
for name, want := range map[string]string{
"Content-Type": "application/json",
"Idempotency-Key": testIdempotencyKey,
"User-Agent": "lincodex-backend",
} {
if got := request.header.Get(name); got != want {
t.Fatalf("%s = %q, want %q", name, got, want)
}
}
var payload map[string]any
if err := json.Unmarshal(request.body, &payload); err != nil {
t.Fatalf("request body is not JSON: %v", err)
}
wantPayload := map[string]any{
"from": testFrom,
"to": []any{testRecipient},
"subject": testSubject,
"text": testTextBody,
"html": testHTMLBody,
}
if fmt.Sprint(payload) != fmt.Sprint(wantPayload) {
t.Fatalf("request body = %v, want %v", payload, wantPayload)
}
assertNoLeak(t, result, err)
}
func TestSendOmitsABlankBodyPart(t *testing.T) {
fake := newFakeResend(t, respondJSON(http.StatusOK, `{"id":"`+testMessageID+`"}`, nil))
mail := testMail(t)
mail.TextBody = " \n\t"
if _, err := fake.sender(t, testTimeout).Send(t.Context(), mail); err != nil {
t.Fatalf("Send() error = %v", err)
}
var payload map[string]any
if err := json.Unmarshal(fake.lastRequest(t).body, &payload); err != nil {
t.Fatalf("request body is not JSON: %v", err)
}
if _, ok := payload["text"]; ok {
t.Fatalf("request body has a blank text part: %v", payload)
}
if payload["html"] != testHTMLBody {
t.Fatalf("request body html = %v, want the HTML part", payload["html"])
}
}
func TestSendClassifiesProviderAnswers(t *testing.T) {
rejectedAs := func(reason outbound.MailRejection, wait time.Duration, code outbound.MailProviderCode) outbound.SendResult {
return outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: reason, RetryAfter: wait, ProviderCode: code}
}
unknown := outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}
unknownAs := func(wait time.Duration, code outbound.MailProviderCode) outbound.SendResult {
return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, RetryAfter: wait, ProviderCode: code}
}
accepted := outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID}
tests := []struct {
name string
respond http.HandlerFunc
want outbound.SendResult
}{
{name: "201 with id", respond: respondJSON(http.StatusCreated, `{"id":"`+testMessageID+`"}`, nil), want: accepted},
{name: "200 without id", respond: respondJSON(http.StatusOK, `{}`, nil), want: unknown},
{name: "200 with garbage", respond: respondJSON(http.StatusOK, `<html>ok</html>`, nil), want: unknown},
{name: "200 with an unsafe id", respond: respondJSON(http.StatusOK, `{"id":"abc\ndef"}`, nil), want: unknown},
{name: "200 with an oversized body", respond: respondJSON(http.StatusOK, `{"id":"`+testMessageID+`","pad":"`+strings.Repeat("x", 70<<10)+`"}`, nil), want: unknown},
{name: "400 invalid idempotency key", respond: respondJSON(http.StatusBadRequest, providerError(400, "invalid_idempotency_key"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "invalid_idempotency_key")},
{name: "422 validation error", respond: respondJSON(http.StatusUnprocessableEntity, providerError(422, "validation_error"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "validation_error")},
{name: "401 missing API key", respond: respondJSON(http.StatusUnauthorized, providerError(401, "missing_api_key"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "missing_api_key")},
{name: "403 restricted API key", respond: respondJSON(http.StatusForbidden, providerError(403, "restricted_api_key"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "restricted_api_key")},
{name: "403 unverified domain", respond: respondJSON(http.StatusForbidden, providerError(403, "validation_error"), nil), want: rejectedAs(outbound.MailRejectionPermanent, 0, "validation_error")},
{name: "404 not found", respond: respondJSON(http.StatusNotFound, providerError(404, "not_found"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "not_found")},
{name: "408 request timeout", respond: respondJSON(http.StatusRequestTimeout, ``, nil), want: rejectedAs(outbound.MailRejectionTemporary, 0, "")},
{name: "409 concurrent idempotent requests", respond: respondJSON(http.StatusConflict, providerError(409, "concurrent_idempotent_requests"), map[string]string{"Retry-After": "1"}), want: unknownAs(time.Second, "concurrent_idempotent_requests")},
{name: "409 key reused with another body", respond: respondJSON(http.StatusConflict, providerError(409, "invalid_idempotent_request"), nil), want: unknownAs(0, "invalid_idempotent_request")},
{name: "429 rate limit with Retry-After", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "rate_limit_exceeded"), map[string]string{"Retry-After": "2", "Ratelimit-Reset": "9"}), want: rejectedAs(outbound.MailRejectionRateLimited, 2*time.Second, "rate_limit_exceeded")},
{name: "429 rate limit with RateLimit-Reset only", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "rate_limit_exceeded"), map[string]string{"Ratelimit-Reset": "5"}), want: rejectedAs(outbound.MailRejectionRateLimited, 5*time.Second, "rate_limit_exceeded")},
{name: "429 rate limit with an HTTP date", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "rate_limit_exceeded"), map[string]string{"Retry-After": fixedNow.Add(90 * time.Second).Format(http.TimeFormat)}), want: rejectedAs(outbound.MailRejectionRateLimited, 90*time.Second, "rate_limit_exceeded")},
{name: "429 rate limit with a huge Retry-After", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "rate_limit_exceeded"), map[string]string{"Retry-After": "99999999999"}), want: rejectedAs(outbound.MailRejectionRateLimited, 24*time.Hour, "rate_limit_exceeded")},
{name: "429 without a body", respond: respondJSON(http.StatusTooManyRequests, ``, nil), want: rejectedAs(outbound.MailRejectionRateLimited, 0, "")},
{name: "429 daily quota", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "daily_quota_exceeded"), map[string]string{"Retry-After": "1"}), want: rejectedAs(outbound.MailRejectionQuotaExhausted, 150*time.Minute, "daily_quota_exceeded")},
{name: "429 monthly quota", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "monthly_quota_exceeded"), nil), want: rejectedAs(outbound.MailRejectionQuotaExhausted, 0, "monthly_quota_exceeded")},
{name: "500 application error", respond: respondJSON(http.StatusInternalServerError, providerError(500, "application_error"), map[string]string{"Retry-After": "5"}), want: unknownAs(0, "application_error")},
{name: "503 service unavailable", respond: respondJSON(http.StatusServiceUnavailable, providerError(503, "service_unavailable"), map[string]string{"Retry-After": "30"}), want: rejectedAs(outbound.MailRejectionTemporary, 30*time.Second, "service_unavailable")},
{name: "401 invalid API key", respond: respondJSON(http.StatusUnauthorized, providerError(401, "invalid_api_key"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "invalid_api_key")},
{name: "422 with an undocumented name", respond: respondJSON(http.StatusUnprocessableEntity, providerError(422, "made_up_error"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "")},
{name: "429 with free text as the name", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "Slow down "+testRecipient), nil), want: rejectedAs(outbound.MailRejectionRateLimited, 0, "")},
{name: "500 internal server error", respond: respondJSON(http.StatusInternalServerError, providerError(500, "internal_server_error"), nil), want: unknownAs(0, "internal_server_error")},
{name: "500 with an undocumented name", respond: respondJSON(http.StatusInternalServerError, providerError(500, "made_up_error"), nil), want: unknown},
{name: "403 without a name", respond: respondJSON(http.StatusForbidden, `error code: 1010`, nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "")},
{name: "405 method not allowed", respond: respondJSON(http.StatusMethodNotAllowed, providerError(405, "method_not_allowed"), nil), want: rejectedAs(outbound.MailRejectionInvalidRequest, 0, "method_not_allowed")},
{name: "409 resource locked", respond: respondJSON(http.StatusConflict, providerError(409, "resource_locked"), map[string]string{"Retry-After": "3"}), want: rejectedAs(outbound.MailRejectionTemporary, 3*time.Second, "resource_locked")},
{name: "409 without a name", respond: respondJSON(http.StatusConflict, ``, nil), want: unknown},
{name: "429 rate limit with a past HTTP date", respond: respondJSON(http.StatusTooManyRequests, providerError(429, "rate_limit_exceeded"), map[string]string{"Retry-After": fixedNow.Add(-time.Minute).Format(http.TimeFormat)}), want: rejectedAs(outbound.MailRejectionRateLimited, 0, "rate_limit_exceeded")},
{name: "503 without a name", respond: respondJSON(http.StatusServiceUnavailable, ``, map[string]string{"Retry-After": "30"}), want: unknown},
{name: "503 with a truncated named body", respond: truncatedAnswer(http.StatusServiceUnavailable, providerError(503, "service_unavailable")), want: unknown},
{name: "500 with a truncated named body", respond: truncatedAnswer(http.StatusInternalServerError, providerError(500, "application_error")), want: unknown},
{name: "502 from a gateway", respond: respondJSON(http.StatusBadGateway, `<html>bad gateway</html>`, nil), want: unknown},
{name: "504 without a body", respond: respondJSON(http.StatusGatewayTimeout, ``, nil), want: unknown},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fake := newFakeResend(t, test.respond)
result, err := fake.sender(t, testTimeout).Send(t.Context(), testMail(t))
if err != nil {
t.Fatalf("Send() error = %v, want a result", err)
}
if result != test.want {
t.Fatalf("Send() = %+v, want %+v", result, test.want)
}
if got := fake.requests.Load(); got != 1 {
t.Fatalf("requests = %d, want exactly 1", got)
}
assertNoLeak(t, result, err)
})
}
}
func TestSendDoesNotFollowRedirects(t *testing.T) {
for _, status := range []int{http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
t.Run(strconv.Itoa(status), func(t *testing.T) {
var targetHits atomic.Int32
target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
targetHits.Add(1)
writer.WriteHeader(http.StatusOK)
_, _ = io.WriteString(writer, `{"id":"`+testMessageID+`"}`)
}))
t.Cleanup(target.Close)
fake := newFakeResend(t, func(writer http.ResponseWriter, request *http.Request) {
http.Redirect(writer, request, target.URL+"/emails", status)
})
result, err := fake.sender(t, testTimeout).Send(t.Context(), testMail(t))
if err != nil {
t.Fatalf("Send() error = %v", err)
}
want := outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionInvalidRequest}
if result != want {
t.Fatalf("Send() = %+v, want %+v", result, want)
}
if fake.requests.Load() != 1 || targetHits.Load() != 0 {
t.Fatalf("requests = %d, redirect target hits = %d, want 1 and 0", fake.requests.Load(), targetHits.Load())
}
})
}
}
// blockUntilCanceled holds the answer until the client gives up, so the
// request has certainly been written.
func blockUntilCanceled(received chan<- struct{}) http.HandlerFunc {
return func(_ http.ResponseWriter, request *http.Request) {
if received != nil {
received <- struct{}{}
}
<-request.Context().Done()
}
}
func TestSendReportsUnknownWhenTheAnswerDoesNotArriveInTime(t *testing.T) {
fake := newFakeResend(t, blockUntilCanceled(nil))
started := time.Now()
result, err := fake.sender(t, shortTimeout).Send(t.Context(), testMail(t))
elapsed := time.Since(started)
if err != nil || result != (outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}) {
t.Fatalf("Send() = (%+v, %v), want unknown without an error", result, err)
}
if elapsed < shortTimeout || elapsed > shortTimeout+time.Second {
t.Fatalf("Send() returned after %s, want about the %s timeout", elapsed, shortTimeout)
}
if got := fake.requests.Load(); got != 1 {
t.Fatalf("requests = %d, want exactly 1", got)
}
}
func TestSendReportsUnknownWhenTheCallerCancelsAfterTheRequestWasWritten(t *testing.T) {
received := make(chan struct{}, 1)
fake := newFakeResend(t, blockUntilCanceled(received))
ctx, cancel := context.WithCancel(t.Context())
go func() {
<-received
cancel()
}()
result, err := fake.sender(t, testTimeout).Send(ctx, testMail(t))
if err != nil || result != (outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}) {
t.Fatalf("Send() = (%+v, %v), want unknown without an error", result, err)
}
if got := fake.requests.Load(); got != 1 {
t.Fatalf("requests = %d, want exactly 1", got)
}
}
func TestSendReturnsTheContextErrorBeforeSending(t *testing.T) {
fake := newFakeResend(t, respondJSON(http.StatusOK, `{"id":"`+testMessageID+`"}`, nil))
ctx, cancel := context.WithCancel(t.Context())
cancel()
result, err := fake.sender(t, testTimeout).Send(ctx, testMail(t))
if !errors.Is(err, context.Canceled) || result != (outbound.SendResult{}) {
t.Fatalf("Send() = (%+v, %v), want the zero result and context.Canceled", result, err)
}
if got := fake.requests.Load(); got != 0 {
t.Fatalf("requests = %d, want none", got)
}
assertNoLeak(t, result, err)
}
func TestSendRejectsAsTemporaryWhenTheProviderIsUnreachable(t *testing.T) {
fake := newFakeResend(t, respondJSON(http.StatusOK, `{"id":"`+testMessageID+`"}`, nil))
sender := fake.sender(t, testTimeout)
// Closing the server leaves a port that refuses connections, so the
// request is never written.
fake.server.Close()
result, err := sender.Send(t.Context(), testMail(t))
want := outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary}
if err != nil || result != want {
t.Fatalf("Send() = (%+v, %v), want %+v", result, err, want)
}
assertNoLeak(t, result, err)
}
// TestSendDoesNotReplayWhenTheConnectionDropsAfterTheRequest covers the
// net/http rule that replays a POST with an Idempotency-Key when a
// connection breaks before the answer. The adapter must leave that decision
// to the delivery layer.
func TestSendDoesNotReplayWhenTheConnectionDropsAfterTheRequest(t *testing.T) {
var calls atomic.Int32
fake := newFakeResend(t, func(writer http.ResponseWriter, _ *http.Request) {
if calls.Add(1) == 1 {
respondJSON(http.StatusOK, `{"id":"`+testMessageID+`"}`, nil)(writer, nil)
return
}
// Drop the connection after the request was read and before any
// answer.
connection, _, err := http.NewResponseController(writer).Hijack()
if err != nil {
t.Errorf("Hijack() error = %v", err)
return
}
_ = connection.Close()
})
sender := fake.sender(t, testTimeout)
if result, err := sender.Send(t.Context(), testMail(t)); err != nil || result.Outcome != outbound.MailOutcomeAccepted {
t.Fatalf("first Send() = (%+v, %v), want accepted", result, err)
}
result, err := sender.Send(t.Context(), testMail(t))
if err != nil || result != (outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}) {
t.Fatalf("second Send() = (%+v, %v), want unknown without an error", result, err)
}
if got := fake.requests.Load(); got != 2 {
t.Fatalf("requests = %d, want 2: one per Send and no replay", got)
}
}
// TestSendIsNotFooledByConnectionsClosedByTheServer reproduces a server
// whose idle timeout closes a kept-alive connection just as the client hands
// it the next request: the answer keeps the connection open, and the server
// drops it as soon as the next request arrives, without processing it. A
// client that reused connections would report a false unknown for a message
// the provider never saw.
func TestSendIsNotFooledByConnectionsClosedByTheServer(t *testing.T) {
const sends = 20
body := `{"id":"` + testMessageID + `"}`
answer := "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + strconv.Itoa(len(body)) + "\r\n\r\n" + body
fake := newFakeResend(t, func(writer http.ResponseWriter, _ *http.Request) {
connection, buffered, err := http.NewResponseController(writer).Hijack()
if err != nil {
t.Errorf("Hijack() error = %v", err)
return
}
defer connection.Close()
_, _ = buffered.WriteString(answer)
_ = buffered.Flush()
// Wait for the next request on this connection, or for the client
// to close it, then drop the connection unanswered.
_ = connection.SetReadDeadline(time.Now().Add(testTimeout))
_, _ = buffered.Peek(1)
})
sender := fake.sender(t, testTimeout)
accepted := 0
for range sends {
result, err := sender.Send(t.Context(), testMail(t))
if err != nil || result.Outcome != outbound.MailOutcomeAccepted {
t.Fatalf("Send() after %d accepted = (%+v, %v), want accepted", accepted, result, err)
}
accepted++
}
if got := fake.requests.Load(); int(got) != accepted {
t.Fatalf("requests = %d, accepted = %d, want equal", got, accepted)
}
}
// stalledTLSEndpoint accepts TCP connections and never answers the TLS
// ClientHello, so a request to it can never be written.
func stalledTLSEndpoint(t *testing.T) (endpoint string, accepted <-chan struct{}) {
t.Helper()
listener, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("Listen() error = %v", err)
}
connections := make(chan struct{}, 1)
var held []net.Conn
var mu sync.Mutex
go func() {
for {
connection, err := listener.Accept()
if err != nil {
return
}
mu.Lock()
held = append(held, connection)
mu.Unlock()
select {
case connections <- struct{}{}:
default:
}
}
}()
t.Cleanup(func() {
_ = listener.Close()
mu.Lock()
defer mu.Unlock()
for _, connection := range held {
_ = connection.Close()
}
})
return "https://" + listener.Addr().String() + "/emails", connections
}
func TestSendBeforeTheRequestWasWritten(t *testing.T) {
t.Run("caller context canceled", func(t *testing.T) {
endpoint, accepted := stalledTLSEndpoint(t)
sender, err := resend.NewSenderWithEndpoint(testAPIKey, testFrom, testTimeout, endpoint, time.Now)
if err != nil {
t.Fatalf("NewSenderWithEndpoint() error = %v", err)
}
ctx, cancel := context.WithCancel(t.Context())
go func() {
<-accepted
cancel()
}()
result, err := sender.Send(ctx, testMail(t))
if !errors.Is(err, context.Canceled) || result != (outbound.SendResult{}) {
t.Fatalf("Send() = (%+v, %v), want the zero result and context.Canceled", result, err)
}
assertNoLeak(t, result, err)
})
t.Run("attempt timeout", func(t *testing.T) {
endpoint, _ := stalledTLSEndpoint(t)
sender, err := resend.NewSenderWithEndpoint(testAPIKey, testFrom, shortTimeout, endpoint, time.Now)
if err != nil {
t.Fatalf("NewSenderWithEndpoint() error = %v", err)
}
result, err := sender.Send(t.Context(), testMail(t))
want := outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary}
if err != nil || result != want {
t.Fatalf("Send() = (%+v, %v), want %+v", result, err, want)
}
})
}
// truncatedAnswer promises a longer body than it sends and then closes the
// connection, so the client reads an incomplete body.
func truncatedAnswer(status int, body string) http.HandlerFunc {
return func(writer http.ResponseWriter, _ *http.Request) {
writer.Header().Set("Content-Length", strconv.Itoa(len(body)+100))
writer.WriteHeader(status)
_, _ = io.WriteString(writer, body)
// Hijacking after a partial write closes the connection early.
if connection, _, err := http.NewResponseController(writer).Hijack(); err == nil {
_ = connection.Close()
}
}
}
func TestSendReportsUnknownForATruncatedSuccess(t *testing.T) {
fake := newFakeResend(t, truncatedAnswer(http.StatusOK, `{"id":"`+testMessageID+`"}`))
result, err := fake.sender(t, testTimeout).Send(t.Context(), testMail(t))
if err != nil || result != (outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}) {
t.Fatalf("Send() = (%+v, %v), want unknown without an error", result, err)
}
if got := fake.requests.Load(); got != 1 {
t.Fatalf("requests = %d, want exactly 1", got)
}
}
func TestSendRejectsInvalidMailWithoutARequest(t *testing.T) {
fake := newFakeResend(t, respondJSON(http.StatusOK, `{"id":"`+testMessageID+`"}`, nil))
mail := testMail(t)
mail.IdempotencyKey = ""
result, err := fake.sender(t, testTimeout).Send(t.Context(), mail)
if !errors.Is(err, outbound.ErrInvalidOutgoingMail) || result != (outbound.SendResult{}) {
t.Fatalf("Send() = (%+v, %v), want ErrInvalidOutgoingMail", result, err)
}
if got := fake.requests.Load(); got != 0 {
t.Fatalf("requests = %d, want none", got)
}
assertNoLeak(t, result, err)
}
func TestNewSenderValidatesArgumentsWithoutEchoingThem(t *testing.T) {
tests := []struct {
name string
apiKey string
from string
timeout time.Duration
}{
{name: "empty key", apiKey: "", from: testFrom, timeout: testTimeout},
{name: "key with whitespace", apiKey: testAPIKey + " x", from: testFrom, timeout: testTimeout},
{name: "key with a newline", apiKey: testAPIKey + "\r\nX-Injected: 1", from: testFrom, timeout: testTimeout},
{name: "empty sender", apiKey: testAPIKey, from: " ", timeout: testTimeout},
{name: "sender with a newline", apiKey: testAPIKey, from: testFrom + "\nBcc: x@example.com", timeout: testTimeout},
{name: "zero timeout", apiKey: testAPIKey, from: testFrom, timeout: 0},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
sender, err := resend.NewSender(test.apiKey, test.from, test.timeout)
if sender != nil || err == nil {
t.Fatalf("NewSender() = (%v, %v), want an error", sender, err)
}
if strings.Contains(err.Error(), testAPIKey) || strings.Contains(err.Error(), "no-reply@example.com") {
t.Fatalf("NewSender() error echoes an argument: %v", err)
}
})
}
if _, err := resend.NewSenderWithEndpoint(testAPIKey, testFrom, testTimeout, "ftp://api.resend.com/emails", time.Now); err == nil {
t.Fatal("NewSenderWithEndpoint() accepted a non-HTTP endpoint")
}
}
func TestPrintedSenderDoesNotExposeTheAPIKey(t *testing.T) {
sender, err := resend.NewSender(testAPIKey, testFrom, testTimeout)
if err != nil {
t.Fatalf("NewSender() error = %v", err)
}
var logs bytes.Buffer
slog.New(slog.NewTextHandler(&logs, nil)).Info("sender", slog.Any("sender", sender))
output := fmt.Sprintf("%v %+v %#v", sender, sender, *sender) + logs.String()
if strings.Contains(output, testAPIKey) {
t.Fatalf("printed sender exposes the API key: %s", output)
}
}
+8 -2
View File
@@ -7,6 +7,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/port/outbound"
)
@@ -19,7 +20,8 @@ var errMailTransportNotBuilt = errors.New("mail transport is not available in th
// 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.
// then smtp fails startup after its settings are validated. Constructors make
// no network call, so startup does not depend on the provider.
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)
@@ -30,7 +32,11 @@ func newMailSender(settings config.Config, logger *slog.Logger) (outbound.MailSe
case config.EmailProviderDisabled:
sender = disabled.NewSender()
case config.EmailProviderResend:
return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", errMailTransportNotBuilt)
resendSender, err := resend.NewSender(settings.ResendAPIKey, settings.EmailFrom, settings.EmailTimeout)
if err != nil {
return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", err)
}
sender = resendSender
case config.EmailProviderSMTP:
return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=smtp: %w", errMailTransportNotBuilt)
default:
+60 -28
View File
@@ -9,6 +9,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/mail/disabled"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
@@ -108,36 +109,67 @@ func TestStartWithDisabledMailSelectsTheDisabledTransport(t *testing.T) {
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()
func TestStartSelectsResendBeforeMigrations(t *testing.T) {
settings := loadMailConfig(t, map[string]string{
"EMAIL_PROVIDER": "resend",
"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())
})
application, cleanup, err := start(t.Context(), settings, logger)
if err == nil {
cleanup()
t.Fatalf("start() = %v, want the migration error of the unreachable database", application)
}
// Getting as far as the migrations proves that the Resend transport was
// built; building it makes no network call.
if !strings.HasPrefix(err.Error(), "bootstrap.start - migrate database: ") || errors.Is(err, errMailTransportNotBuilt) {
t.Fatalf("start() error = %v, want a migration error after the transport was selected", err)
}
output := logs.String()
if !strings.Contains(output, `msg="mail transport selected" email_provider=resend`) {
t.Fatalf("startup did not log the selected provider: %s", output)
}
if strings.Contains(output, "mail delivery is disabled") {
t.Fatalf("startup warned that mail is disabled for resend: %s", output)
}
assertNoMailSecrets(t, err.Error()+output)
}
func TestNewMailSenderBuildsTheResendTransport(t *testing.T) {
settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "resend"})
logger, logs := captureLogs()
sender, err := newMailSender(settings, logger)
if err != nil {
t.Fatalf("newMailSender() error = %v", err)
}
if _, ok := sender.(*resend.Sender); !ok {
t.Fatalf("mail sender = %T, want *resend.Sender", sender)
}
assertNoMailSecrets(t, logs.String())
}
func TestStartRejectsTransportsThatThisBuildDoesNotProvide(t *testing.T) {
settings := loadMailConfig(t, map[string]string{
"EMAIL_PROVIDER": "smtp",
"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)
}
want := "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=smtp: mail transport is not available in this build"
if err.Error() != want || !errors.Is(err, errMailTransportNotBuilt) {
t.Fatalf("start() error = %q, want %q", err, 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) {
+51 -13
View File
@@ -42,16 +42,30 @@ const (
// 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 means the provider did not take the message: either
// it answered and refused the request, or the transport failed before the
// request was completely written (DNS, connect, or TLS failure), so no
// complete request reached the provider. Rejection says why; the second case is
// always MailRejectionTemporary.
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.
// no conclusive answer came back, for example a timeout, a connection
// lost after the request was written, or a provider error raised while
// handling it. The message may or may not have been accepted
// (delivery_uncertain). It is not a "not sent" result: a retry must reuse
// the same IdempotencyKey and the same content so a provider that
// supports keys can deduplicate it. Deduplication has a window (24 hours
// for Resend); after it a retry may send the message twice, so the
// delivery layer must stop retrying and escalate to an operator instead.
//
// ProviderCode may name the reason. With Resend,
// "concurrent_idempotent_requests" means another request with the same
// key is still in progress: retry later with the same key. And
// "invalid_idempotent_request" means the key was already used with
// another body, so an earlier request under it may have been accepted;
// repeating cannot succeed and a new key could send the message twice, so
// the delivery layer must stop and escalate.
MailOutcomeUnknown MailOutcome = "unknown"
)
@@ -77,11 +91,24 @@ const (
// 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 means a transient condition that a later attempt
// may overcome: a provider-side refusal, such as a 5xx answer or an SMTP
// 4xx reply, or a failure before the request was completely written. In
// the second case no complete request reached the provider, so a retry
// cannot duplicate the message.
MailRejectionTemporary MailRejection = "temporary"
)
// MailProviderCode is the provider's machine-readable error name for a
// rejected or unknown attempt, for example Resend's
// "invalid_idempotent_request" or "daily_quota_exceeded". A transport sets it only to a name from its own
// fixed list of documented provider names and leaves it empty for anything
// else, so it never carries free text from the provider and is safe to log,
// store, and use as a metric label. Retry decisions follow Outcome and
// Rejection; the code adds operator detail, such as telling a wrong API key
// from a malformed request, or an idempotency key reused with another body.
type MailProviderCode string
// 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.
@@ -98,7 +125,8 @@ type OutgoingMail struct {
// 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.
// contain personal data. The provider keeps it only for a limited window
// (24 hours for Resend); see MailOutcomeUnknown.
IdempotencyKey string
}
@@ -158,8 +186,15 @@ type SendResult struct {
// 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.
// ProviderCode is set only for MailOutcomeRejected and MailOutcomeUnknown,
// and only when the provider answered with a documented error name; see
// MailProviderCode.
ProviderCode MailProviderCode
// RetryAfter is the wait before the next attempt for a rejected or
// unknown result: the provider's own hint (for example Retry-After), or a
// wait the transport derived from documented provider rules (for example
// the next daily quota reset). It is zero when there is neither.
RetryAfter time.Duration
}
@@ -172,7 +207,10 @@ type SendResult struct {
// 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.
// zero and must be ignored. A failure to reach the provider before the
// request was written while ctx is still active is not an error: it is
// MailOutcomeRejected with MailRejectionTemporary. A failure after the request
// may have been written is MailOutcomeUnknown.
//
// Errors and logs never include recipients, subjects, bodies, credentials, or
// raw provider responses.