diff --git a/.env.example b/.env.example index 78c866f..b8679df 100644 --- a/.env.example +++ b/.env.example @@ -20,17 +20,19 @@ SEAWEEDFS_BUCKET=lincodex KAFKA_CLUSTER_ID=SJv4PXUUSJGbK3eSPC57qA # Mail. EMAIL_PROVIDER is required and selects exactly one transport: -# resend, smtp, or disabled. The working stand uses resend; this build has no -# Resend or SMTP transport yet, so both fail startup after their settings are -# validated. disabled sends nothing and reports the mail channel as -# unavailable; it never confirms an address or skips an account check. +# resend, smtp, or disabled; there is no default. resend sends through the +# Resend HTTP API and the working stand sets it explicitly. This example sets +# disabled so that local runs need no key. This build has no SMTP transport +# yet, so smtp fails startup after its settings are validated. disabled sends +# nothing and reports the mail channel as unavailable; it never confirms an +# address or skips an account check. EMAIL_PROVIDER=disabled EMAIL_FROM=no-reply@example.com EMAIL_TIMEOUT=10s # Public origin for links in mail: https, or http only for a loopback host. APP_PUBLIC_URL=http://localhost:8080 -# Read only when EMAIL_PROVIDER=resend. Keep the real key in the server -# environment only. +# Read only when EMAIL_PROVIDER=resend, where it is required. Keep the real +# key in the server environment only; it is never logged. RESEND_API_KEY= # Read only when EMAIL_PROVIDER=smtp. SMTP_TLS_MODE is starttls or tls; # plaintext SMTP is not supported. diff --git a/backend/internal/adapter/secondary/mail/resend/credential_test.go b/backend/internal/adapter/secondary/mail/resend/credential_test.go new file mode 100644 index 0000000..b03a350 --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/credential_test.go @@ -0,0 +1,21 @@ +package resend + +import ( + "bytes" + "fmt" + "log/slog" + "strings" + "testing" +) + +func TestCredentialRedactsItself(t *testing.T) { + const key = "re_credential-test-key" + value := credential{authorization: "Bearer " + key} + + var logs bytes.Buffer + slog.New(slog.NewTextHandler(&logs, nil)).Info("credential", slog.Any("value", value), slog.Any("pointer", &value)) + output := fmt.Sprintf("%v %+v %#v %s %q", value, value, value, value, value) + fmt.Sprint(&value) + logs.String() + if strings.Contains(output, key) { + t.Fatalf("printed credential exposes the API key: %s", output) + } +} diff --git a/backend/internal/adapter/secondary/mail/resend/export_test.go b/backend/internal/adapter/secondary/mail/resend/export_test.go new file mode 100644 index 0000000..69d2c6b --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/export_test.go @@ -0,0 +1,9 @@ +package resend + +import "time" + +// NewSenderWithEndpoint lets tests point the sender at a local fake and fix +// the clock. Production code can only use the documented endpoint. +func NewSenderWithEndpoint(apiKey, from string, timeout time.Duration, endpoint string, now func() time.Time) (*Sender, error) { + return newSender(apiKey, from, timeout, endpoint, now) +} diff --git a/backend/internal/adapter/secondary/mail/resend/response.go b/backend/internal/adapter/secondary/mail/resend/response.go new file mode 100644 index 0000000..9a67efd --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/response.go @@ -0,0 +1,268 @@ +package resend + +import ( + "encoding/json" + "net/http" + "strconv" + "strings" + "time" + + "lincodex/backend/internal/port/outbound" +) + +// Error names that change the outcome. Other known names are classified by +// status alone. +const ( + errorNameValidation = "validation_error" + errorNameInvalidIdempotent = "invalid_idempotent_request" + errorNameResourceLocked = "resource_locked" + errorNameDailyQuota = "daily_quota_exceeded" + errorNameMonthlyQuota = "monthly_quota_exceeded" + errorNameServiceUnavailable = "service_unavailable" +) + +// knownErrorNames is the fixed set of Resend error names that may become +// SendResult.ProviderCode: the names on +// https://resend.com/docs/api-reference/errors plus the older names that the +// official Node SDK still lists (invalid_api_key, invalid_from_address, +// invalid_access, invalid_region, security_error, internal_server_error). A +// name outside the set is treated as no name, so provider text never leaves +// the adapter. +var knownErrorNames = map[string]struct{}{ + "invalid_idempotency_key": {}, + errorNameValidation: {}, + "missing_api_key": {}, + "restricted_api_key": {}, + "invalid_api_key": {}, + "suspended_api_key": {}, + "invalid_permission": {}, + "invalid_access": {}, + "invalid_from_address": {}, + "invalid_region": {}, + "email_above_quota": {}, + "not_found": {}, + "method_not_allowed": {}, + "concurrent_idempotent_requests": {}, + errorNameInvalidIdempotent: {}, + errorNameResourceLocked: {}, + "invalid_attachment": {}, + "invalid_parameter": {}, + "missing_required_field": {}, + "missing_required_parameter": {}, + errorNameDailyQuota: {}, + errorNameMonthlyQuota: {}, + "rate_limit_exceeded": {}, + "security_error": {}, + "application_error": {}, + "internal_server_error": {}, + errorNameServiceUnavailable: {}, +} + +const ( + // maxProviderMessageIDLength bounds the stored ID. Resend returns UUIDs. + maxProviderMessageIDLength = 128 + + // maxRetryAfter caps a provider wait hint so that a malformed header + // cannot park a delivery for longer than a daily quota reset. + maxRetryAfter = 24 * time.Hour +) + +// providerAnswer is an HTTP answer. body is set only when complete is true: +// the body was read without error and within maxResponseBodyBytes. +type providerAnswer struct { + status int + header http.Header + body []byte + complete bool +} + +// classifyResponse maps an HTTP answer to the port outcome. The body is only +// parsed for the message ID or the error name; neither the body nor the +// provider's message is kept. A rejected or unknown result carries the error +// name as ProviderCode when it is in knownErrorNames. +// +// - 2xx with a valid ID: accepted. Without one the request may still have +// been accepted, so the outcome is unknown. +// - 3xx: rejected invalid_request. The API documents no redirect, the +// request did not reach the send handler, and repeating it gets the same +// redirect. +// - 403 validation_error (unverified sender domain; without one Resend +// sends only testing emails to the account's own address): rejected +// permanent. +// - 408 and 409 resource_locked: rejected temporary. +// - 409 concurrent_idempotent_requests: unknown. Another request with the +// same key is in progress and may be accepted; a later retry with the +// same key gets its result. +// - 409 invalid_idempotent_request: unknown. The key was used with another +// body in the last 24 hours, so an earlier request under this key may +// have been accepted. Repeating cannot succeed and a new key could send +// the message twice: the delivery layer stops and escalates on this code. +// - 409 without a known name: unknown, since it may be either of the above. +// - 429 daily_quota_exceeded: quota_exhausted until the next midnight UTC; +// 429 monthly_quota_exceeded: quota_exhausted without a wait hint, the +// reset depends on the billing cycle; other 429: rate_limited with +// Retry-After or RateLimit-Reset. +// - other 4xx (validation, key, permission, not found): invalid_request. +// - 503 service_unavailable: rejected temporary; the API refused the +// request as a whole. +// - other 5xx, including 500 application_error and internal_server_error: +// unknown. The API failed while handling the request, or a proxy or +// gateway answered, so the message may have been accepted. +func classifyResponse(answer providerAnswer, now time.Time) outbound.SendResult { + status := answer.status + switch { + case status >= 200 && status < 300: + if id, ok := parseMessageID(answer); ok { + return outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: id} + } + return unknownResult(0) + case status >= 300 && status < 400: + return rejected(outbound.MailRejectionInvalidRequest, 0) + } + + name := parseErrorName(answer) + result := classifyError(status, name, answer.header, now) + result.ProviderCode = outbound.MailProviderCode(name) + return result +} + +func classifyError(status int, name string, header http.Header, now time.Time) outbound.SendResult { + if status >= 500 { + if status == http.StatusServiceUnavailable && name == errorNameServiceUnavailable { + return rejected(outbound.MailRejectionTemporary, retryAfter(header, now)) + } + return unknownResult(0) + } + switch status { + case http.StatusForbidden: + if name == errorNameValidation { + return rejected(outbound.MailRejectionPermanent, 0) + } + case http.StatusRequestTimeout: + return rejected(outbound.MailRejectionTemporary, retryAfter(header, now)) + case http.StatusConflict: + if name == errorNameResourceLocked { + return rejected(outbound.MailRejectionTemporary, retryAfter(header, now)) + } + return unknownResult(retryAfter(header, now)) + case http.StatusTooManyRequests: + return classifyTooManyRequests(name, header, now) + } + return rejected(outbound.MailRejectionInvalidRequest, 0) +} + +func classifyTooManyRequests(name string, header http.Header, now time.Time) outbound.SendResult { + switch name { + case errorNameDailyQuota: + // The daily quota resets at midnight UTC, not after a rolling day. + return rejected(outbound.MailRejectionQuotaExhausted, untilNextUTCMidnight(now)) + case errorNameMonthlyQuota: + return rejected(outbound.MailRejectionQuotaExhausted, 0) + default: + return rejected(outbound.MailRejectionRateLimited, rateLimitWait(header, now)) + } +} + +func rejected(reason outbound.MailRejection, wait time.Duration) outbound.SendResult { + return outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: reason, RetryAfter: wait} +} + +func unknownResult(wait time.Duration) outbound.SendResult { + return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, RetryAfter: wait} +} + +// parseMessageID reads {"id": "..."} and accepts only an ID that is safe to +// store and log. +func parseMessageID(answer providerAnswer) (string, bool) { + if !answer.complete { + return "", false + } + var success struct { + ID string `json:"id"` + } + if err := json.Unmarshal(answer.body, &success); err != nil { + return "", false + } + if len(success.ID) == 0 || len(success.ID) > maxProviderMessageIDLength || strings.ContainsFunc(success.ID, isNotIDCharacter) { + return "", false + } + return success.ID, true +} + +// parseErrorName reads the name of {"statusCode", "name", "message"}. It +// returns "" for any name outside knownErrorNames, so provider text never +// flows further. +func parseErrorName(answer providerAnswer) string { + if !answer.complete { + return "" + } + var failure struct { + Name string `json:"name"` + } + if err := json.Unmarshal(answer.body, &failure); err != nil { + return "" + } + if _, known := knownErrorNames[failure.Name]; !known { + return "" + } + return failure.Name +} + +// rateLimitWait prefers Retry-After and falls back to RateLimit-Reset, the +// seconds until the rate limit window resets. +func rateLimitWait(header http.Header, now time.Time) time.Duration { + if wait := retryAfter(header, now); wait > 0 { + return wait + } + return parseSeconds(header.Get("Ratelimit-Reset")) +} + +// retryAfter reads Retry-After as delta seconds or as an HTTP date. +func retryAfter(header http.Header, now time.Time) time.Duration { + value := strings.TrimSpace(header.Get("Retry-After")) + if value == "" { + return 0 + } + if wait := parseSeconds(value); wait > 0 { + return wait + } + date, err := http.ParseTime(value) + if err != nil { + return 0 + } + return capWait(date.Sub(now)) +} + +func parseSeconds(value string) time.Duration { + seconds, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64) + if err != nil || seconds <= 0 { + return 0 + } + if seconds > int64(maxRetryAfter/time.Second) { + return maxRetryAfter + } + return time.Duration(seconds) * time.Second +} + +func untilNextUTCMidnight(now time.Time) time.Duration { + current := now.UTC() + midnight := time.Date(current.Year(), current.Month(), current.Day()+1, 0, 0, 0, 0, time.UTC) + return capWait(midnight.Sub(current)) +} + +func capWait(wait time.Duration) time.Duration { + switch { + case wait <= 0: + return 0 + case wait > maxRetryAfter: + return maxRetryAfter + default: + return wait + } +} + +func isNotIDCharacter(character rune) bool { + isLetter := (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') + isDigit := character >= '0' && character <= '9' + return !isLetter && !isDigit && character != '-' && character != '_' +} diff --git a/backend/internal/adapter/secondary/mail/resend/sender.go b/backend/internal/adapter/secondary/mail/resend/sender.go new file mode 100644 index 0000000..ee19879 --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/sender.go @@ -0,0 +1,272 @@ +// 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]" + +// 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 { + protocols := new(http.Protocols) + protocols.SetHTTP1(true) + transport := &http.Transport{ + Proxy: http.ProxyFromEnvironment, + 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 +} diff --git a/backend/internal/adapter/secondary/mail/resend/sender_test.go b/backend/internal/adapter/secondary/mail/resend/sender_test.go new file mode 100644 index 0000000..e3fe0be --- /dev/null +++ b/backend/internal/adapter/secondary/mail/resend/sender_test.go @@ -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 " + testRecipient = "candidate@example.com" + testSubject = "Confirm your address" + testTextBody = "Open the link: https://lincodex.example/verify-email#token=raw-token-value" + testHTMLBody = "

Open the link

" + 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, `ok`, 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, `bad gateway`, 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) + } +} diff --git a/backend/internal/bootstrap/mail.go b/backend/internal/bootstrap/mail.go index 83c6c92..2b18360 100644 --- a/backend/internal/bootstrap/mail.go +++ b/backend/internal/bootstrap/mail.go @@ -7,6 +7,7 @@ import ( "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/adapter/secondary/mail/resend" "lincodex/backend/internal/port/outbound" ) @@ -19,7 +20,8 @@ var errMailTransportNotBuilt = errors.New("mail transport is not available in th // EMAIL_PROVIDER selects. Each provider maps to exactly one constructor, and // a failure never falls back to another transport. A transport task replaces // the errMailTransportNotBuilt return in its case with its constructor; until -// then resend and smtp fail startup after their settings are validated. +// then smtp fails startup after its settings are validated. Constructors make +// no network call, so startup does not depend on the provider. func newMailSender(settings config.Config, logger *slog.Logger) (outbound.MailSender, error) { if err := settings.ValidateMail(); err != nil { return nil, fmt.Errorf("bootstrap.newMailSender - validate mail settings: %w", err) @@ -30,7 +32,11 @@ func newMailSender(settings config.Config, logger *slog.Logger) (outbound.MailSe case config.EmailProviderDisabled: sender = disabled.NewSender() case config.EmailProviderResend: - return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", errMailTransportNotBuilt) + resendSender, err := resend.NewSender(settings.ResendAPIKey, settings.EmailFrom, settings.EmailTimeout) + if err != nil { + return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=resend: %w", err) + } + sender = resendSender case config.EmailProviderSMTP: return nil, fmt.Errorf("bootstrap.newMailSender - EMAIL_PROVIDER=smtp: %w", errMailTransportNotBuilt) default: diff --git a/backend/internal/bootstrap/mail_test.go b/backend/internal/bootstrap/mail_test.go index a7f1ce6..dd24592 100644 --- a/backend/internal/bootstrap/mail_test.go +++ b/backend/internal/bootstrap/mail_test.go @@ -9,6 +9,7 @@ import ( "lincodex/backend/config" "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/adapter/secondary/mail/resend" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) @@ -108,36 +109,67 @@ func TestStartWithDisabledMailSelectsTheDisabledTransport(t *testing.T) { assertNoMailSecrets(t, output) } -func TestStartRejectsTransportsThatThisBuildDoesNotProvide(t *testing.T) { - tests := []struct { - provider string - want string - }{ - {provider: "resend", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=resend: mail transport is not available in this build"}, - {provider: "smtp", want: "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=smtp: mail transport is not available in this build"}, - } - for _, test := range tests { - t.Run(test.provider, func(t *testing.T) { - settings := loadMailConfig(t, map[string]string{ - "EMAIL_PROVIDER": test.provider, - "DATABASE_URL": unreachableDatabaseURL, - }) - logger, logs := captureLogs() +func TestStartSelectsResendBeforeMigrations(t *testing.T) { + settings := loadMailConfig(t, map[string]string{ + "EMAIL_PROVIDER": "resend", + "DATABASE_URL": unreachableDatabaseURL, + }) + logger, logs := captureLogs() - application, cleanup, err := start(t.Context(), settings, logger) - if err == nil { - cleanup() - t.Fatalf("start() = %v, want a startup error", application) - } - if err.Error() != test.want || !errors.Is(err, errMailTransportNotBuilt) { - t.Fatalf("start() error = %q, want %q", err, test.want) - } - if strings.Contains(logs.String(), "mail transport selected") { - t.Fatalf("startup logged a selected transport after failing: %s", logs.String()) - } - assertNoMailSecrets(t, err.Error()+logs.String()) - }) + application, cleanup, err := start(t.Context(), settings, logger) + if err == nil { + cleanup() + t.Fatalf("start() = %v, want the migration error of the unreachable database", application) } + // Getting as far as the migrations proves that the Resend transport was + // built; building it makes no network call. + if !strings.HasPrefix(err.Error(), "bootstrap.start - migrate database: ") || errors.Is(err, errMailTransportNotBuilt) { + t.Fatalf("start() error = %v, want a migration error after the transport was selected", err) + } + output := logs.String() + if !strings.Contains(output, `msg="mail transport selected" email_provider=resend`) { + t.Fatalf("startup did not log the selected provider: %s", output) + } + if strings.Contains(output, "mail delivery is disabled") { + t.Fatalf("startup warned that mail is disabled for resend: %s", output) + } + assertNoMailSecrets(t, err.Error()+output) +} + +func TestNewMailSenderBuildsTheResendTransport(t *testing.T) { + settings := loadMailConfig(t, map[string]string{"EMAIL_PROVIDER": "resend"}) + logger, logs := captureLogs() + + sender, err := newMailSender(settings, logger) + if err != nil { + t.Fatalf("newMailSender() error = %v", err) + } + if _, ok := sender.(*resend.Sender); !ok { + t.Fatalf("mail sender = %T, want *resend.Sender", sender) + } + assertNoMailSecrets(t, logs.String()) +} + +func TestStartRejectsTransportsThatThisBuildDoesNotProvide(t *testing.T) { + settings := loadMailConfig(t, map[string]string{ + "EMAIL_PROVIDER": "smtp", + "DATABASE_URL": unreachableDatabaseURL, + }) + logger, logs := captureLogs() + + application, cleanup, err := start(t.Context(), settings, logger) + if err == nil { + cleanup() + t.Fatalf("start() = %v, want a startup error", application) + } + want := "bootstrap.start - select mail transport: bootstrap.newMailSender - EMAIL_PROVIDER=smtp: mail transport is not available in this build" + if err.Error() != want || !errors.Is(err, errMailTransportNotBuilt) { + t.Fatalf("start() error = %q, want %q", err, want) + } + if strings.Contains(logs.String(), "mail transport selected") { + t.Fatalf("startup logged a selected transport after failing: %s", logs.String()) + } + assertNoMailSecrets(t, err.Error()+logs.String()) } func TestStartRejectsInvalidMailSettingsBeforeMigrations(t *testing.T) { diff --git a/backend/internal/port/outbound/mail.go b/backend/internal/port/outbound/mail.go index 4815430..3b1bcf8 100644 --- a/backend/internal/port/outbound/mail.go +++ b/backend/internal/port/outbound/mail.go @@ -42,16 +42,30 @@ const ( // a message ID. It does not mean the message was delivered or read. MailOutcomeAccepted MailOutcome = "accepted" - // MailOutcomeRejected means the provider answered and refused the - // request; it did not take the message. Rejection says why. + // MailOutcomeRejected means the provider did not take the message: either + // it answered and refused the request, or the transport failed before the + // request was completely written (DNS, connect, or TLS failure), so no + // complete request reached the provider. Rejection says why; the second case is + // always MailRejectionTemporary. MailOutcomeRejected MailOutcome = "rejected" // MailOutcomeUnknown means the request may have reached the provider but - // no conclusive answer came back, for example a timeout or a connection - // lost after the request was written. The message may or may not have - // been accepted (delivery_uncertain). It is not a failure: a retry must - // reuse the same IdempotencyKey so a provider that supports keys can - // deduplicate it. + // no conclusive answer came back, for example a timeout, a connection + // lost after the request was written, or a provider error raised while + // handling it. The message may or may not have been accepted + // (delivery_uncertain). It is not a "not sent" result: a retry must reuse + // the same IdempotencyKey and the same content so a provider that + // supports keys can deduplicate it. Deduplication has a window (24 hours + // for Resend); after it a retry may send the message twice, so the + // delivery layer must stop retrying and escalate to an operator instead. + // + // ProviderCode may name the reason. With Resend, + // "concurrent_idempotent_requests" means another request with the same + // key is still in progress: retry later with the same key. And + // "invalid_idempotent_request" means the key was already used with + // another body, so an earlier request under it may have been accepted; + // repeating cannot succeed and a new key could send the message twice, so + // the delivery layer must stop and escalate. MailOutcomeUnknown MailOutcome = "unknown" ) @@ -77,11 +91,24 @@ const ( // used up; retrying before the quota resets cannot help. MailRejectionQuotaExhausted MailRejection = "quota_exhausted" - // MailRejectionTemporary means a transient provider-side refusal, such as - // a 5xx answer or an SMTP 4xx reply, that a later attempt may overcome. + // MailRejectionTemporary means a transient condition that a later attempt + // may overcome: a provider-side refusal, such as a 5xx answer or an SMTP + // 4xx reply, or a failure before the request was completely written. In + // the second case no complete request reached the provider, so a retry + // cannot duplicate the message. MailRejectionTemporary MailRejection = "temporary" ) +// MailProviderCode is the provider's machine-readable error name for a +// rejected or unknown attempt, for example Resend's +// "invalid_idempotent_request" or "daily_quota_exceeded". A transport sets it only to a name from its own +// fixed list of documented provider names and leaves it empty for anything +// else, so it never carries free text from the provider and is safe to log, +// store, and use as a metric label. Retry decisions follow Outcome and +// Rejection; the code adds operator detail, such as telling a wrong API key +// from a malformed request, or an idempotency key reused with another body. +type MailProviderCode string + // OutgoingMail is one rendered message. The sender address comes from the // transport configuration (EMAIL_FROM), so usecases and templates never choose // or depend on it, nor on the provider. @@ -98,7 +125,8 @@ type OutgoingMail struct { // IdempotencyKey is stable for one logical delivery across every retry, // for example "email_verification/". A transport that supports // provider-side deduplication sends it; others ignore it. It must not - // contain personal data. + // contain personal data. The provider keeps it only for a limited window + // (24 hours for Resend); see MailOutcomeUnknown. IdempotencyKey string } @@ -158,8 +186,15 @@ type SendResult struct { // Rejection is set only for MailOutcomeRejected. Rejection MailRejection - // RetryAfter is the provider's requested wait for a rejected attempt, or - // zero when the provider gave none. + // ProviderCode is set only for MailOutcomeRejected and MailOutcomeUnknown, + // and only when the provider answered with a documented error name; see + // MailProviderCode. + ProviderCode MailProviderCode + + // RetryAfter is the wait before the next attempt for a rejected or + // unknown result: the provider's own hint (for example Retry-After), or a + // wait the transport derived from documented provider rules (for example + // the next daily quota reset). It is zero when there is neither. RetryAfter time.Duration } @@ -172,7 +207,10 @@ type SendResult struct { // wraps ErrMailChannelUnavailable when no transport is active, // ErrInvalidOutgoingMail for an invalid message, or the context error when // ctx ended before the request was sent. The returned SendResult is then -// zero and must be ignored. +// zero and must be ignored. A failure to reach the provider before the +// request was written while ctx is still active is not an error: it is +// MailOutcomeRejected with MailRejectionTemporary. A failure after the request +// may have been written is MailOutcomeUnknown. // // Errors and logs never include recipients, subjects, bodies, credentials, or // raw provider responses. diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 455627b..76a971e 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -79,15 +79,41 @@ Planned relay contract (TASK-009): the relay selects unpublished rows (`publishe ### Mail transport -Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: the Resend transport (`mail/resend/`, the primary provider for the working stand, TASK-013) and an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP). Until they exist, `resend` and `smtp` fail startup after their settings are validated. Settings are described in [DEPLOY.md](DEPLOY.md#mail). +Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mail.go`), the `disabled` transport (`adapter/secondary/mail/disabled/`), the Resend transport (`adapter/secondary/mail/resend/`, the primary provider for the working stand), and the transport selection in bootstrap. Usecases, templates, and domain events depend only on the port; `EMAIL_PROVIDER` selects exactly one transport (`resend`, `smtp`, or `disabled`), and bootstrap binds the port to it before migrations run. There is no fallback between transports: an unusable selection stops startup. Planned: an SMTP relay transport (`mail/smtp/`, TASK-014, outside the MVP); until it exists, `smtp` fails startup after its settings are validated. No flow calls the port yet; the delivery layer is planned. Settings are described in [DEPLOY.md](DEPLOY.md#mail). `Send(ctx, OutgoingMail)` makes exactly one attempt. `OutgoingMail` carries the recipient, subject, text and HTML bodies, and an idempotency key that stays the same for one logical delivery across retries (1 to 256 printable ASCII characters, the Resend limit, without personal data); the sender comes from `EMAIL_FROM`. With a nil error the result is one of: - `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading. -- `rejected`: the provider answered and refused; `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`, with an optional `RetryAfter`. -- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`). It is not a failure; a retry reuses the idempotency key. +- `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`. +- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Provider deduplication has a window (24 hours for Resend); after it a retry may send the message twice, so the delivery layer must stop retrying and escalate to an operator. -A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. +`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store. + +A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. + +The Resend transport uses `net/http` without an SDK. One `Send` is one `POST https://api.resend.com/emails` with `from` (`EMAIL_FROM`), `to` (one recipient), `subject`, `text`, and `html` (a blank part is omitted), an `Authorization: Bearer` key, a `User-Agent`, and `Idempotency-Key` set to the message's key. Resend keeps a key for 24 hours and answers the same key and body with the original result without sending again, so a retry must repeat the stored body under the same key; a changed body under an old key is a conflict, not a reason to make a new key. `EMAIL_TIMEOUT` bounds the whole attempt. The client follows no redirects, uses HTTP/1.1, and opens a fresh connection for every send: a kept-alive connection that the server closed while idle would fail after the request was handed to it and turn a message Resend never saw into a false `unknown`. The request also has no `GetBody`, because `net/http` treats a POST with `Idempotency-Key` as replayable on a broken reused connection. The adapter has no retry loop and does not log. An answer is read up to 64 KiB; only the message ID and the error `name` are parsed, and the provider's message and body are not kept. + +| Resend answer | Result | +| --- | --- | +| 2xx with an `id` of up to 128 letters, digits, `-`, or `_` | `accepted` with `ProviderMessageID` | +| 2xx without a valid `id`, truncated, or over 64 KiB | `unknown`: the request may have been accepted | +| 3xx, not followed | `rejected`, `invalid_request`: the API documents no redirect, and a repeat gets the same one | +| 403 `validation_error` (unverified sender domain: without one Resend sends only testing emails to the account's own address) | `rejected`, `permanent` | +| Other 4xx: 400, 422, key and permission errors (401, 403), 404, 405 | `rejected`, `invalid_request` | +| 408; 409 `resource_locked` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` | +| 409 `concurrent_idempotent_requests` | `unknown`: another request with the same key is in progress and may be accepted; retry later with the same key | +| 409 `invalid_idempotent_request` | `unknown`: the key was used with another body, so an earlier request may have been accepted; repeating cannot succeed, so the delivery layer stops and escalates | +| 409 without a known name | `unknown` | +| 429 `rate_limit_exceeded` or unnamed | `rejected`, `rate_limited`, `RetryAfter` from `Retry-After` (seconds or a future HTTP date), otherwise from `ratelimit-reset` | +| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `RetryAfter` until the next 00:00 UTC | +| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, no `RetryAfter`: the reset follows the billing cycle | +| 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` from `Retry-After` | +| Other 5xx, including 500 `application_error` and `internal_server_error`, a truncated body, or a proxy or gateway answer | `unknown`: the API may have accepted the message before it failed | +| No answer after the request was written: timeout, reset, or closed connection | `unknown` | +| Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend | +| The caller's context ended before the request was written | the context error; nothing was sent | + +Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing, waiting for a quota reset or an operator decision, the attempt limit, and the stop at the end of the 24-hour key window belong to the planned delivery layer. ### Product policy versions @@ -200,9 +226,9 @@ backend/ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`. -Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. +Product domain types and usecase modules, the SMTP and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` transport, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging; the identity usecases (verification and password reset) and the planned delivery usecase are expected to call it, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. @@ -218,6 +244,7 @@ This is a compact map, not a claim that every planned product package exists. Cu | assessment | Questionnaire, tasks, attempts, scoring, grade | questionnaires, task_templates, attempts, answers, grade_history | | matching | Needs, filters, ranking, search versions | hiring_needs, search_runs, search_items | | invitation | Offer and contact permission | invitations, invitation_events, contact_grants | + mail/resend/ mail transport that sends one request to the Resend HTTP API per message | document | Files, resume analysis, standard PDF | files, analysis_results, document_jobs | | achievement | FSP link and achievement provenance | fsp_links, achievements, sync_runs | | vacancy, later | Vacancies and voluntary applications | vacancies, applications | diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 6cad9b8..d053632 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -70,7 +70,9 @@ down stops containers and keeps named volumes. Do not delete database or file vo The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read. -Current state: this build contains only the `disabled` transport. With `resend` or `smtp`, the backend validates that transport's settings and then exits with `EMAIL_PROVIDER=resend: mail transport is not available in this build` (or `EMAIL_PROVIDER=smtp: ...`); under Compose, `restart: unless-stopped` restarts the container repeatedly. The Resend transport comes in a later task; SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` therefore use `disabled`. Switch the working stand to `resend` only after the build contains the Resend transport. +Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. No flow sends mail yet: the delivery layer that calls the transport is planned. + +`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, waiting for a daily or monthly quota reset, and outcome records belong to the planned delivery layer. Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). `disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 06ef4dc..b29a932 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -79,15 +79,41 @@ Usecase пишет через outbound-порты. `Transactor.WithinTransaction ### Почтовый транспорт -Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт Resend (`mail/resend/`, основной провайдер рабочего стенда, TASK-013) и транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP). Пока их нет, `resend` и `smtp` после проверки своих настроек останавливают запуск. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). +Реализовано: outbound порт `MailSender` (`backend/internal/port/outbound/mail.go`), транспорт `disabled` (`adapter/secondary/mail/disabled/`), транспорт Resend (`adapter/secondary/mail/resend/`, основной провайдер рабочего стенда) и выбор транспорта в bootstrap. Usecase, шаблоны и доменные события зависят только от порта; `EMAIL_PROVIDER` выбирает ровно один транспорт (`resend`, `smtp` или `disabled`), и bootstrap связывает с ним порт до запуска миграций. Переключения между транспортами нет: непригодный выбор останавливает запуск. Запланировано: транспорт SMTP relay (`mail/smtp/`, TASK-014, вне MVP); пока его нет, `smtp` после проверки своих настроек останавливает запуск. Порт пока не вызывает ни один сценарий; слой доставки запланирован. Настройки описаны в [DEPLOY.md](DEPLOY.md#почта). `Send(ctx, OutgoingMail)` делает ровно одну попытку. `OutgoingMail` содержит получателя, тему, текстовое и HTML тело и ключ идемпотентности, который не меняется для одной логической доставки между повторами (от 1 до 256 печатных ASCII символов, предел Resend, без персональных данных); отправитель берется из `EMAIL_FROM`. При nil ошибке результат один из: - `accepted`: провайдер принял запрос и вернул `ProviderMessageID`. Это не доставка и не прочтение. -- `rejected`: провайдер ответил отказом; `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`, возможно с `RetryAfter`. -- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`). Это не ошибка доставки; повтор использует тот же ключ идемпотентности. +- `rejected`: провайдер не принял письмо. Либо он ответил отказом, либо транспорт сломался до полной записи запроса (DNS, соединение или TLS), и полный запрос до провайдера не дошел; второй случай всегда `temporary`, и повтор не может продублировать письмо. `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`. +- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`), например таймаут, обрыв соединения после записи запроса или ошибка провайдера во время обработки. Это не «не отправлено»: повтор использует тот же ключ идемпотентности и то же содержимое. Дедупликация у провайдера ограничена окном (24 часа у Resend); после него повтор может отправить письмо дважды, поэтому слой доставки обязан прекратить повторы и передать случай оператору. -Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. +`rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить. + +Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения (TASK-053, TASK-054) обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. + +Транспорт Resend использует `net/http` без SDK. Один `Send` - это один `POST https://api.resend.com/emails` с полями `from` (`EMAIL_FROM`), `to` (один получатель), `subject`, `text` и `html` (пустая или пробельная часть не передается), ключом в `Authorization: Bearer`, заголовком `User-Agent` и `Idempotency-Key`, равным ключу письма. Resend хранит ключ 24 часа и на тот же ключ с тем же телом возвращает исходный результат без повторной отправки, поэтому повтор обязан передать сохраненное тело под тем же ключом; измененное тело под старым ключом - это конфликт, а не повод создать новый ключ. `EMAIL_TIMEOUT` ограничивает всю попытку. Клиент не следует редиректам, использует HTTP/1.1 и открывает новое соединение для каждой отправки: keep-alive соединение, которое сервер закрыл по простою, сломалось бы уже после передачи запроса и превратило бы письмо, которого Resend не видел, в ложный `unknown`. У запроса также нет `GetBody`, потому что `net/http` считает POST с `Idempotency-Key` повторяемым после обрыва переиспользованного соединения. В адаптере нет цикла повторов, и он ничего не логирует. Ответ читается не больше 64 KiB; разбираются только идентификатор письма и `name` ошибки, а сообщение провайдера и тело ответа не сохраняются. + +| Ответ Resend | Результат | +| --- | --- | +| 2xx с `id` до 128 символов из букв, цифр, `-` и `_` | `accepted` с `ProviderMessageID` | +| 2xx без корректного `id`, обрезанный или больше 64 KiB | `unknown`: запрос мог быть принят | +| 3xx, редирект не выполняется | `rejected`, `invalid_request`: API не документирует редиректы, а повтор получит тот же | +| 403 `validation_error` (домен отправителя не подтвержден: без него Resend отправляет только тестовые письма на адрес владельца аккаунта) | `rejected`, `permanent` | +| Прочие 4xx: 400, 422, ошибки ключа и прав (401, 403), 404, 405 | `rejected`, `invalid_request` | +| 408; 409 `resource_locked` | `rejected`, `temporary`, `RetryAfter` из `Retry-After` | +| 409 `concurrent_idempotent_requests` | `unknown`: другой запрос с тем же ключом еще обрабатывается и может быть принят; повторите позже с тем же ключом | +| 409 `invalid_idempotent_request` | `unknown`: ключ уже использован с другим телом, поэтому более ранний запрос мог быть принят; повтор не поможет, и слой доставки останавливается и передает случай оператору | +| 409 без известного имени | `unknown` | +| 429 `rate_limit_exceeded` или без имени | `rejected`, `rate_limited`, `RetryAfter` из `Retry-After` (секунды или будущая HTTP-дата), иначе из `ratelimit-reset` | +| 429 `daily_quota_exceeded` | `rejected`, `quota_exhausted`, `RetryAfter` до ближайших 00:00 UTC | +| 429 `monthly_quota_exceeded` | `rejected`, `quota_exhausted`, без `RetryAfter`: сброс зависит от платежного цикла | +| 503 `service_unavailable` | `rejected`, `temporary`, `RetryAfter` из `Retry-After` | +| Прочие 5xx, включая 500 `application_error` и `internal_server_error`, обрезанное тело или ответ прокси или шлюза | `unknown`: API мог принять письмо до сбоя | +| Нет ответа после записи запроса: таймаут, сброс или закрытие соединения | `unknown` | +| Сбой до записи запроса: DNS, соединение, TLS или таймаут попытки | `rejected`, `temporary`: полный запрос до Resend не дошел | +| Контекст вызывающего завершился до записи запроса | ошибка контекста; ничего не отправлено | + +Каждый ответ `rejected` или `unknown` с известным именем ошибки заполняет `ProviderCode` этим именем, например `invalid_idempotent_request`, `invalid_api_key` или `daily_quota_exceeded`. Известны имена со страницы ошибок Resend и старые имена, которые все еще перечисляет официальный Node SDK (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); любое другое имя считается отсутствующим. `RetryAfter` ограничен 24 часами. Темп при rate limit, ожидание сброса квоты или решения оператора, предел числа попыток и остановка по окончании 24-часового окна ключа относятся к запланированному слою доставки. ### Версии продуктовой политики @@ -200,9 +226,9 @@ backend/ Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`. -`domain/`, продуктовые `usecase/`, адаптеры Resend, SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. +`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS, порт `MailSender` с транспортом `disabled` и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования; его должны вызывать usecase identity (подтверждение почты и сброс пароля) и запланированный usecase доставки, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -218,6 +244,7 @@ backend/ | assessment | Опрос, задания, попытки, оценка и грейд | questionnaires, task_templates, attempts, answers, grade_history | | matching | Потребности, фильтры, ранжирование и версии подборок | hiring_needs, search_runs, search_items | | invitation | Предложение и право раскрыть контакты | invitations, invitation_events, contact_grants | + mail/resend/ почтовый транспорт, который отправляет одно письмо одним запросом к HTTP API Resend | document | Файлы, разбор резюме и стандартизированный PDF | files, analysis_results, document_jobs | | achievement | Связь с ФСП и источник достижений | fsp_links, achievements, sync_runs | | vacancy, позже | Вакансии и добровольные отклики | vacancies, applications | diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index a82bbc4..0ef7979 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -72,7 +72,9 @@ down останавливает контейнеры, сохраняя имен Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются. -Текущее состояние: в этой сборке есть только транспорт `disabled`. С `resend` или `smtp` backend проверяет настройки этого транспорта и затем завершается с ошибкой `EMAIL_PROVIDER=resend: mail transport is not available in this build` (или `EMAIL_PROVIDER=smtp: ...`); в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. Транспорт Resend появится в следующей задаче, SMTP вне MVP. Поэтому `.env.example` и `make -C deploy smoke` используют `disabled`. Переключайте рабочий стенд на `resend` только после того, как сборка будет содержать транспорт Resend. +Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Пока ни один сценарий не отправляет почту: слой доставки, который вызывает транспорт, запланирован. + +`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit, ожидание сброса дневной или месячной квоты и учет результатов относятся к запланированному слою доставки. Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). `disabled` ничего не отправляет. Каждая отправка возвращает `ErrMailChannelUnavailable` без идентификатора сообщения провайдера и никогда не считается принятой или доставленной. Этот режим не подтверждает email, не отмечает аккаунт подтвержденным и не пропускает проверки аккаунта. В логе запуска есть `mail transport selected` с полем `email_provider`, а для `disabled` еще и предупреждение `mail delivery is disabled`.