Files

284 lines
11 KiB
Go

// 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]"
// IdempotencyWindow is how long Resend keeps an Idempotency-Key and answers
// a repeated request under it with the original result instead of sending
// again: 24 hours, per the Resend API documentation. Bootstrap passes it to
// notification.NewQuotaGate, so a retry inside the window does not count
// against the quota a second time.
const IdempotencyWindow = 24 * time.Hour
// 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 {
return newHTTPClientWithProxy(timeout, http.ProxyFromEnvironment)
}
func newHTTPClientWithProxy(timeout time.Duration, proxy func(*http.Request) (*url.URL, error)) *http.Client {
protocols := new(http.Protocols)
protocols.SetHTTP1(true)
transport := &http.Transport{
Proxy: proxy,
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
}