// 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" "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 = 1 << 20 // 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 } // 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 } // 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 scripted []Reply } type message struct { id string body string } // New starts the fixture on a loopback address. func New() *Server { server := &Server{messages: make(map[string]message)} server.http = httptest.NewServer(http.HandlerFunc(server.serve)) return server } // 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() { 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...) } // 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)) } // 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 len(server.messages) } func (server *Server) serve(response http.ResponseWriter, request *http.Request) { server.arrivals.Add(1) if delay := time.Duration(server.delay.Load()); delay > 0 { time.Sleep(delay) } 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 } payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes)) if err != nil { writeError(response, http.StatusBadRequest, "invalid_parameter") return } 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 } key := request.Header.Get("Idempotency-Key") record := Request{IdempotencyKey: key, To: body.To, Subject: body.Subject, Text: body.Text, HTML: body.HTML} server.mu.Lock() defer server.mu.Unlock() if len(server.scripted) > 0 { reply := server.scripted[0] server.scripted = server.scripted[1:] server.requests = append(server.requests, record) writeError(response, reply.Status, reply.Name) return } known, seen := server.messages[key] switch { case seen && known.body != string(payload): // The key was used with another body: Resend refuses it. server.requests = append(server.requests, record) writeError(response, http.StatusConflict, "invalid_idempotent_request") return case seen: record.Replayed = true server.requests = append(server.requests, record) writeAccepted(response, known.id) return } accepted := message{id: uuid.NewString(), body: string(payload)} if key != "" { server.messages[key] = accepted } else { server.messages[accepted.id] = accepted } server.requests = append(server.requests, record) writeAccepted(response, accepted.id) } 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)}) }