Files
lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go
T

398 lines
12 KiB
Go

// Package resendfixture is a local stand-in for the Resend HTTP API, for
// tests of the delivery layer. It speaks the part of the API that the
// resend transport uses: POST /emails with a bearer key and an
// Idempotency-Key, answered with {"id": ...} or a Resend error object. It
// keeps what it receives so a test can check the recipient, the key, and the
// number of provider calls, and it deduplicates a repeated key the way
// Resend does, so a test can tell a second call from a second message.
//
// It is a test fixture only; production keeps the real Resend transport and
// never imports this package.
package resendfixture
import (
"crypto/subtle"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
)
// APIKey is the key the fixture accepts.
const APIKey = "re_fixture_key" //nolint:gosec // A key of the local fixture, not a credential.
const (
maxRequestBytes = 32 << 10
maxStoredRequests = 256
maxStoredMessages = 64
)
// InboxToken is a synthetic credential for the isolated browser E2E fixture.
const InboxToken = "local-e2e-mailbox-token" //nolint:gosec // Synthetic bearer token for the local E2E inbox.
// Request is one call that reached the fixture.
type Request struct {
IdempotencyKey string
To []string
Subject string
Text string
HTML string
// Replayed is set when the key was already used with the same body: the
// fixture answered with the original message and created no new one.
Replayed bool
}
// InboxMessage is an accepted fixture message without provider idempotency
// metadata.
type InboxMessage struct {
ID string `json:"id"`
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text,omitempty"`
HTML string `json:"html,omitempty"`
}
// Reply is a scripted answer.
type Reply struct {
Status int
// Name is the Resend error name for a non-2xx answer, for example
// "daily_quota_exceeded".
Name string
// RetryAfter is copied to the response header for a rate-limit fixture.
RetryAfter string
// DropAfterAccept stores the message and closes the connection without an
// HTTP answer, like a provider accepting the request before the response
// is lost.
DropAfterAccept bool
}
// Server is the fixture. Create it with New.
type Server struct {
http *httptest.Server
// arrivals counts calls from the moment they are received, before the
// delay, so a test can tell that a call is in flight.
arrivals atomic.Int64
delay atomic.Int64 // nanoseconds
mu sync.Mutex
requests []Request
messages map[string]message // by idempotency key
inbox []InboxMessage
received int
accepted int
scripted []Reply
clock func() time.Time
}
type message struct {
id string
body string
acceptedAt time.Time
}
const providerIdempotencyWindow = 24 * time.Hour
// New starts the fixture on a loopback address.
func New() *Server {
server := NewService()
server.http = httptest.NewServer(server.Handler())
return server
}
// NewService creates the in-memory fixture for the standalone Compose server.
func NewService() *Server {
return &Server{messages: make(map[string]message), clock: time.Now}
}
// Handler exposes the Resend-compatible endpoint and the authenticated E2E
// inbox. The inbox is intentionally limited to this test fixture package.
func (server *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/emails", server.serve)
mux.HandleFunc("/__e2e/inbox", server.serveInbox)
mux.HandleFunc("/healthz", serveHealth)
return mux
}
// URL is the endpoint to give the loopback transport.
func (server *Server) URL() string { return server.http.URL + "/emails" }
// Close stops the fixture.
func (server *Server) Close() {
if server.http != nil {
server.http.Close()
}
}
// Script queues answers for the next calls, in order; calls after them are
// accepted as usual.
func (server *Server) Script(replies ...Reply) {
server.mu.Lock()
defer server.mu.Unlock()
server.scripted = append(server.scripted, replies...)
}
// ClearScript drops the queued answers that no call has used and returns
// their number, so a test that stops early does not hand them to the next one.
func (server *Server) ClearScript() int {
server.mu.Lock()
defer server.mu.Unlock()
left := len(server.scripted)
server.scripted = nil
return left
}
// SetDelay makes the fixture wait before it answers every later call, so a
// test can act while a send is in flight.
func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) }
// SetClock replaces the provider clock so tests can expire idempotency keys
// without waiting in real time.
func (server *Server) SetClock(clock func() time.Time) {
server.mu.Lock()
defer server.mu.Unlock()
if clock == nil {
server.clock = time.Now
return
}
server.clock = clock
}
// Arrivals returns how many calls the fixture has received, answered or
// not yet.
func (server *Server) Arrivals() int { return int(server.arrivals.Load()) }
// Requests returns every call received, in order.
func (server *Server) Requests() []Request {
server.mu.Lock()
defer server.mu.Unlock()
return append([]Request(nil), server.requests...)
}
// Messages returns the number of distinct messages the fixture accepted: a
// replayed key does not add one.
func (server *Server) Messages() int {
server.mu.Lock()
defer server.mu.Unlock()
return server.accepted
}
func (server *Server) serve(response http.ResponseWriter, request *http.Request) {
server.arrivals.Add(1)
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
writeError(response, http.StatusNotFound, "not_found")
return
}
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
writeError(response, http.StatusUnauthorized, "invalid_api_key")
return
}
server.mu.Lock()
if server.received >= maxStoredRequests {
server.mu.Unlock()
writeError(response, http.StatusServiceUnavailable, "fixture_capacity_exhausted")
return
}
server.received++
server.mu.Unlock()
if delay := time.Duration(server.delay.Load()); delay > 0 {
time.Sleep(delay)
}
payload, record, ok := readRequest(response, request)
if !ok {
return
}
server.handleEmail(response, payload, record)
}
func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, Request, bool) {
if request.Method != http.MethodPost || request.URL.Path != "/emails" {
writeError(response, http.StatusNotFound, "not_found")
return nil, Request{}, false
}
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 {
writeError(response, http.StatusUnauthorized, "invalid_api_key")
return nil, Request{}, false
}
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes+1))
if err != nil {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return nil, Request{}, false
}
if len(payload) > maxRequestBytes {
writeError(response, http.StatusRequestEntityTooLarge, "payload_too_large")
return nil, Request{}, false
}
var body struct {
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text"`
HTML string `json:"html"`
}
if err := json.Unmarshal(payload, &body); err != nil {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return nil, Request{}, false
}
key := request.Header.Get("Idempotency-Key")
if strings.TrimSpace(key) == "" {
writeError(response, http.StatusBadRequest, "invalid_parameter")
return nil, Request{}, false
}
return payload, Request{
IdempotencyKey: key,
To: body.To,
Subject: body.Subject,
Text: body.Text,
HTML: body.HTML,
}, true
}
func (server *Server) handleEmail(response http.ResponseWriter, payload []byte, record Request) {
server.mu.Lock()
reply := Reply{}
if len(server.scripted) > 0 {
reply = server.scripted[0]
server.scripted = server.scripted[1:]
}
now := server.clock()
known, seen := server.messages[record.IdempotencyKey]
if seen && now.Sub(known.acceptedAt) >= providerIdempotencyWindow {
delete(server.messages, record.IdempotencyKey)
seen = false
}
if reply.Status != 0 {
server.requests = append(server.requests, record)
server.mu.Unlock()
if reply.RetryAfter != "" {
response.Header().Set("Retry-After", reply.RetryAfter)
}
writeError(response, reply.Status, reply.Name)
return
}
if !seen && server.accepted >= maxStoredMessages {
server.requests = append(server.requests, record)
server.mu.Unlock()
writeError(response, http.StatusServiceUnavailable, "fixture_capacity_exhausted")
return
}
messageID, replayed, conflict := server.recordAcceptanceLocked(record.IdempotencyKey, string(payload), now, known, seen)
record.Replayed = replayed
server.requests = append(server.requests, record)
if !replayed && !conflict {
server.inbox = append(server.inbox, InboxMessage{
ID: messageID,
To: append([]string(nil), record.To...),
Subject: record.Subject,
Text: record.Text,
HTML: record.HTML,
})
}
server.mu.Unlock()
if conflict {
writeError(response, http.StatusConflict, "invalid_idempotent_request")
return
}
if reply.DropAfterAccept {
dropConnection(response)
return
}
writeAccepted(response, messageID)
}
func (server *Server) serveInbox(response http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet || request.URL.Path != "/__e2e/inbox" {
writeError(response, http.StatusNotFound, "not_found")
return
}
if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+InboxToken)) != 1 {
writeError(response, http.StatusUnauthorized, "invalid_inbox_token")
return
}
recipient := strings.ToLower(strings.TrimSpace(request.URL.Query().Get("to")))
if recipient == "" || len(recipient) > 254 {
writeError(response, http.StatusBadRequest, "invalid_recipient")
return
}
messages := server.InboxMessages(recipient)
response.Header().Set("Cache-Control", "no-store")
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
_ = json.NewEncoder(response).Encode(struct {
Messages []InboxMessage `json:"messages"`
}{Messages: messages})
}
// InboxMessages returns accepted messages for one exact case-insensitive
// recipient. It never includes provider idempotency keys.
func (server *Server) InboxMessages(recipient string) []InboxMessage {
wanted := strings.ToLower(strings.TrimSpace(recipient))
server.mu.Lock()
defer server.mu.Unlock()
messages := make([]InboxMessage, 0)
for _, message := range server.inbox {
for _, address := range message.To {
if strings.ToLower(address) == wanted {
messages = append(messages, message)
break
}
}
}
return messages
}
func serveHealth(response http.ResponseWriter, request *http.Request) {
if request.Method != http.MethodGet || request.URL.Path != "/healthz" {
writeError(response, http.StatusNotFound, "not_found")
return
}
response.WriteHeader(http.StatusNoContent)
}
func (server *Server) recordAcceptanceLocked(key, body string, now time.Time, known message, seen bool) (string, bool, bool) {
if seen {
if known.body != body {
return "", false, true
}
return known.id, true, false
}
accepted := message{id: uuid.NewString(), body: body, acceptedAt: now}
if key != "" {
server.messages[key] = accepted
} else {
server.messages[accepted.id] = accepted
}
server.accepted++
return accepted.id, false, false
}
func dropConnection(response http.ResponseWriter) {
if hijacker, ok := response.(http.Hijacker); ok {
connection, _, err := hijacker.Hijack()
if err == nil {
_ = connection.Close()
}
}
}
func writeAccepted(response http.ResponseWriter, id string) {
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
_ = json.NewEncoder(response).Encode(map[string]string{"id": id})
}
func writeError(response http.ResponseWriter, status int, name string) {
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(status)
_ = json.NewEncoder(response).Encode(map[string]any{"statusCode": status, "name": name, "message": "fixture " + strconv.Itoa(status)})
}