feat(mail): add Resend API transport
This commit is contained in:
1 parent
1aa7a9feaf
commit
c85b642d32
13 files changed
+1387
-63
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user