test(identity): add isolated browser mail fixture

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:52:38 +03:00
1 parent 86f562f5b6
commit 24638d46d2
20 files changed
+885 -20

No files matched your search

@@ -17,6 +17,7 @@ import (
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
@@ -27,7 +28,14 @@ import (
// 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
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 {
@@ -41,6 +49,16 @@ type Request struct {
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
@@ -67,6 +85,8 @@ type Server struct {
mu sync.Mutex
requests []Request
messages map[string]message // by idempotency key
inbox []InboxMessage
received int
accepted int
scripted []Reply
clock func() time.Time
@@ -82,16 +102,35 @@ const providerIdempotencyWindow = 24 * time.Hour
// New starts the fixture on a loopback address.
func New() *Server {
server := &Server{messages: make(map[string]message), clock: time.Now}
server.http = httptest.NewServer(http.HandlerFunc(server.serve))
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() { server.http.Close() }
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.
@@ -138,6 +177,23 @@ func (server *Server) Messages() int {
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)
}
@@ -157,11 +213,15 @@ func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, R
writeError(response, http.StatusUnauthorized, "invalid_api_key")
return nil, Request{}, false
}
payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes))
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"`
@@ -172,8 +232,13 @@ func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, R
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: request.Header.Get("Idempotency-Key"),
IdempotencyKey: key,
To: body.To,
Subject: body.Subject,
Text: body.Text,
@@ -203,9 +268,24 @@ func (server *Server) handleEmail(response http.ResponseWriter, payload []byte,
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")
@@ -218,6 +298,56 @@ func (server *Server) handleEmail(response http.ResponseWriter, payload []byte,
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 {
@@ -1,6 +1,11 @@
package resendfixture_test
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"testing"
"time"
@@ -65,3 +70,184 @@ func TestLoopbackSenderRefusesAnyOtherHost(t *testing.T) {
}
}
}
func TestInboxRequiresAuthenticationAndReturnsOnlyAcceptedMessagesForRecipient(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "Lincodex <no-reply@example.com>", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
if _, err := sender.Send(t.Context(), newMail(t, "Confirm", "delivery/first")); err != nil {
t.Fatalf("Send() error = %v", err)
}
address := url.QueryEscape("fixture.user@example.com")
inboxURL := strings.TrimSuffix(fixture.URL(), "/emails") + "/__e2e/inbox?to=" + address
request, err := http.NewRequestWithContext(t.Context(), http.MethodGet, inboxURL, nil)
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
unauthorized, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("inbox request error = %v", err)
}
_ = unauthorized.Body.Close()
if unauthorized.StatusCode != http.StatusUnauthorized {
t.Fatalf("unauthenticated inbox status = %d, want %d", unauthorized.StatusCode, http.StatusUnauthorized)
}
request, err = http.NewRequestWithContext(t.Context(), http.MethodGet, inboxURL, nil)
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer "+resendfixture.InboxToken)
authorized, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("authenticated inbox request error = %v", err)
}
defer authorized.Body.Close()
if authorized.StatusCode != http.StatusOK {
t.Fatalf("authenticated inbox status = %d, want %d", authorized.StatusCode, http.StatusOK)
}
var result struct {
Messages []resendfixture.InboxMessage `json:"messages"`
}
if err := json.NewDecoder(authorized.Body).Decode(&result); err != nil {
t.Fatalf("decode inbox response error = %v", err)
}
if len(result.Messages) != 1 || result.Messages[0].Subject != "Confirm" {
t.Fatalf("inbox messages = %+v, want the accepted fixture message", result.Messages)
}
if strings.Contains(string(mustReadBody(t, result.Messages[0])), "delivery/first") {
t.Fatal("inbox response unexpectedly includes provider idempotency metadata")
}
otherURL := strings.TrimSuffix(fixture.URL(), "/emails") + "/__e2e/inbox?to=" + url.QueryEscape("other@example.com")
request, err = http.NewRequestWithContext(t.Context(), http.MethodGet, otherURL, nil)
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer "+resendfixture.InboxToken)
other, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("filtered inbox request error = %v", err)
}
defer other.Body.Close()
if err := json.NewDecoder(other.Body).Decode(&result); err != nil {
t.Fatalf("decode filtered inbox response error = %v", err)
}
if len(result.Messages) != 0 {
t.Fatalf("other recipient inbox = %+v, want no messages", result.Messages)
}
}
func TestFixtureBoundsAcceptedMessages(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
for index := range 64 {
mail := newMail(t, fmt.Sprintf("Message %d", index), fmt.Sprintf("delivery/%d", index))
if _, err := sender.Send(t.Context(), mail); err != nil {
t.Fatalf("Send(%d) error = %v", index, err)
}
}
if fixture.Messages() != 64 {
t.Fatalf("accepted messages = %d, want 64", fixture.Messages())
}
if _, err := sender.Send(t.Context(), newMail(t, "Overflow", "delivery/overflow")); err != nil {
t.Fatalf("overflow Send() error = %v", err)
}
if fixture.Messages() != 64 {
t.Fatalf("accepted messages after capacity refusal = %d, want 64", fixture.Messages())
}
}
func TestFixtureBoundsRecordedProviderRequests(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
mail := newMail(t, "Repeated message", "delivery/repeated")
for range 256 {
if _, err := sender.Send(t.Context(), mail); err != nil {
t.Fatalf("Send() error = %v", err)
}
}
if fixture.Messages() != 1 || len(fixture.Requests()) != 256 {
t.Fatalf("fixture state = %d messages and %d requests, want 1 and 256", fixture.Messages(), len(fixture.Requests()))
}
if _, err := sender.Send(t.Context(), mail); err != nil {
t.Fatalf("capacity refusal Send() error = %v", err)
}
if fixture.Messages() != 1 || len(fixture.Requests()) != 256 {
t.Fatalf("fixture state after capacity refusal = %d messages and %d requests", fixture.Messages(), len(fixture.Requests()))
}
}
func TestWrongProviderKeyDoesNotConsumeFixtureCapacity(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
for range 256 {
request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, fixture.URL(), strings.NewReader(`{}`))
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer wrong-key")
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("unauthorized provider request error = %v", err)
}
_ = response.Body.Close()
if response.StatusCode != http.StatusUnauthorized {
t.Fatalf("unauthorized provider status = %d, want %d", response.StatusCode, http.StatusUnauthorized)
}
}
sender, err := resend.NewLoopbackSender(resendfixture.APIKey, "no-reply@example.com", 5*time.Second, fixture.URL(), time.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
if _, err := sender.Send(t.Context(), newMail(t, "After unauthorized request", "delivery/authorized")); err != nil {
t.Fatalf("authorized Send() error = %v", err)
}
if fixture.Messages() != 1 {
t.Fatalf("accepted messages = %d, want 1", fixture.Messages())
}
}
func TestFixtureRejectsOversizedProviderRequest(t *testing.T) {
fixture := resendfixture.New()
defer fixture.Close()
payload := `{"to":["fixture.user@example.com"],"subject":"fixture","text":"` + strings.Repeat("x", (32<<10)+1) + `"}`
request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, fixture.URL(), strings.NewReader(payload))
if err != nil {
t.Fatalf("NewRequestWithContext() error = %v", err)
}
request.Header.Set("Authorization", "Bearer "+resendfixture.APIKey)
request.Header.Set("Idempotency-Key", "delivery/oversized")
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatalf("oversized provider request error = %v", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized request status = %d, want %d", response.StatusCode, http.StatusRequestEntityTooLarge)
}
if len(fixture.Requests()) != 0 {
t.Fatalf("oversized requests recorded = %d, want 0", len(fixture.Requests()))
}
}
func mustReadBody(t *testing.T, message resendfixture.InboxMessage) []byte {
t.Helper()
encoded, err := json.Marshal(message)
if err != nil {
t.Fatalf("marshal inbox message: %v", err)
}
return encoded
}
@@ -137,10 +137,14 @@ func newSender(apiKey, from string, timeout time.Duration, endpoint string, now
// 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: http.ProxyFromEnvironment,
Proxy: proxy,
DialContext: (&net.Dialer{Timeout: timeout}).DialContext,
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
TLSHandshakeTimeout: timeout,
@@ -0,0 +1,20 @@
//go:build e2e
package resend
import "time"
const e2eEndpoint = "http://mail-fixture:8025/emails"
// NewE2ESender is compiled only into the isolated registration E2E image. Its
// endpoint is fixed to the Compose fixture and cannot be selected at runtime.
func NewE2ESender(apiKey, from string, timeout time.Duration) (*Sender, error) {
sender, err := newSender(apiKey, from, timeout, e2eEndpoint, time.Now)
if err != nil {
return nil, err
}
// The local fixture must stay internal even when the host has proxy
// variables configured for ordinary provider traffic.
sender.client = newHTTPClientWithProxy(timeout, nil)
return sender, nil
}
@@ -0,0 +1,23 @@
//go:build e2e
package resend
import (
"net/http"
"testing"
"time"
)
func TestE2ESenderUsesOnlyTheComposeFixtureEndpoint(t *testing.T) {
sender, err := NewE2ESender("re_e2e_fixture_key", "no-reply@example.com", time.Second)
if err != nil {
t.Fatalf("NewE2ESender() error = %v", err)
}
if sender.endpoint != e2eEndpoint {
t.Fatalf("endpoint = %q, want the fixed Compose fixture endpoint", sender.endpoint)
}
transport, ok := sender.client.Transport.(*http.Transport)
if !ok || transport.Proxy != nil {
t.Fatalf("E2E transport proxy = %v, want no proxy", transport)
}
}