feat(notification): add durable mail delivery state

This commit is contained in:
shira committed 2026-10-06 10:52:47 +03:00
1 parent 391c8a6cec
commit 2db585fbff
41 files changed
+4903 -108

No files matched your search

@@ -0,0 +1,199 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
// DeliveryConsumerName names the consumer group and scopes deduplication.
// Renaming it makes the consumer process every retained request again; the
// delivery IDs then keep the deliveries unique, but do not rename it lightly.
const DeliveryConsumerName = "notification_delivery"
// DeliveryHandler creates one Delivery for each notification.mail_requested
// event, in the consumer transaction that records the event as processed.
//
// The delivery ID is the request ID, so a duplicate event, a replayed dead
// letter, or a renamed consumer maps to the same delivery. The content is
// rendered once, here, and stored; a later template version does not change
// it. The request row is deleted in the same transaction, so its text lives
// only as long as it is needed.
type DeliveryHandler struct {
renderer NotificationRenderer
providerAccount domain.MailProviderAccount
clock func() time.Time
logger *slog.Logger
}
var _ inbound.EventHandler = (*DeliveryHandler)(nil)
// NewDeliveryHandler pins new deliveries to providerAccount, the transport
// and account configured when the event is handled. clock is the
// application clock for the creation time.
func NewDeliveryHandler(
renderer NotificationRenderer,
providerAccount domain.MailProviderAccount,
clock func() time.Time,
logger *slog.Logger,
) *DeliveryHandler {
return &DeliveryHandler{renderer: renderer, providerAccount: providerAccount, clock: clock, logger: logger}
}
func (*DeliveryHandler) ConsumerName() string { return DeliveryConsumerName }
func (*DeliveryHandler) Handles(eventType string) bool { return eventType == MailRequestedEventType }
// Handle turns the request into a delivery:
//
// - A request that breaks the event contract, data the template refuses,
// or an existing delivery under the same ID for another recipient or
// kind is rejected for good (inbound.ErrEventRejected).
// - A request that no longer exists, because it was already turned into a
// delivery or its account was deleted, is skipped.
// - A notification to an account whose address is not verified is skipped
// and its request deleted: notifications go only to confirmed addresses.
// - Storage errors are returned for a retry. That includes an account
// deleted after it was read, which aborts the insert; the retry then
// finds the request gone with the account and skips it.
//
// Errors and logs carry the delivery and event IDs, never the address or
// the notification text.
func (handler *DeliveryHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error {
const location = "DeliveryHandler.Handle"
payload, err := decodeMailRequest(event)
if err != nil {
return err
}
request, err := unit.MailRequests().Lock(ctx, payload.MailRequestID)
if errors.Is(err, outbound.ErrMailRequestNotFound) {
handler.logSkip(ctx, "mail request skipped because it was already handled or its account was deleted", event)
return nil
}
if err != nil {
return fmt.Errorf("%s - lock mail request: %w", location, err)
}
if string(request.Kind) != payload.Kind {
return fmt.Errorf("%s - event kind does not match the stored request: %w", location, inbound.ErrEventRejected)
}
recipient, err := unit.Users().GetByID(ctx, request.RecipientUserID)
if errors.Is(err, outbound.ErrUserNotFound) {
// The foreign key deletes a request with its account, so this is a
// defensive branch.
handler.logSkip(ctx, "mail request skipped because the recipient account does not exist", event)
return handler.finish(ctx, unit, request.ID)
}
if err != nil {
return fmt.Errorf("%s - read recipient account: %w", location, err)
}
if recipient.EmailVerifiedAt == nil {
handler.logSkip(ctx, "notification skipped because the recipient address is not verified", event)
return handler.finish(ctx, unit, request.ID)
}
content, err := handler.renderer.RenderNotification(mailtemplate.NotificationData{
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
})
if errors.Is(err, mailtemplate.ErrInvalidTemplateData) || errors.Is(err, domain.ErrInvalidMailContent) {
return fmt.Errorf("%s - render notification: %w: %w", location, inbound.ErrEventRejected, err)
}
if err != nil {
return fmt.Errorf("%s - render notification: %w", location, err)
}
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: request.ID,
SourceEventID: event.EventID,
RecipientUserID: recipient.ID,
Recipient: recipient.Email,
Content: content,
ProviderAccount: handler.providerAccount,
CreatedAt: handler.clock(),
})
if err != nil {
return fmt.Errorf("%s - build delivery: %w: %w", location, inbound.ErrEventRejected, err)
}
created, err := unit.Deliveries().Create(ctx, delivery)
if err != nil {
return fmt.Errorf("%s - store delivery: %w", location, err)
}
if !created {
if err := checkExistingDelivery(ctx, unit, request); err != nil {
return err
}
}
return handler.finish(ctx, unit, request.ID)
}
// checkExistingDelivery accepts a delivery stored earlier under the request
// ID only when it is for the same recipient and kind; its content stays as
// stored.
func checkExistingDelivery(ctx context.Context, unit outbound.UnitOfWork, request domain.MailRequest) error {
const location = "notification.checkExistingDelivery"
existing, err := unit.Deliveries().Get(ctx, request.ID)
if err != nil {
return fmt.Errorf("%s - read existing delivery: %w", location, err)
}
if existing.RecipientUserID() != request.RecipientUserID || existing.Kind() != request.Kind {
return fmt.Errorf("%s - a delivery for another recipient or kind has the request ID: %w", location, inbound.ErrEventRejected)
}
return nil
}
// finish deletes the handled request in the consumer transaction.
func (handler *DeliveryHandler) finish(ctx context.Context, unit outbound.UnitOfWork, requestID uuid.UUID) error {
if err := unit.MailRequests().Delete(ctx, requestID); err != nil {
return fmt.Errorf("DeliveryHandler.finish - delete mail request: %w", err)
}
return nil
}
func (handler *DeliveryHandler) logSkip(ctx context.Context, message string, event outbound.ConsumedEvent) {
handler.logger.InfoContext(ctx, message,
slog.String("delivery_id", event.AggregateID.String()),
slog.String("event_id", event.EventID.String()))
}
// decodeMailRequest checks the envelope and payload of a version 1 request.
// Errors name the broken rule and never quote the payload.
func decodeMailRequest(event outbound.ConsumedEvent) (mailRequestedPayload, error) {
const location = "notification.decodeMailRequest"
rejected := func(reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, inbound.ErrEventRejected)
}
if event.SchemaVersion != mailRequestedSchemaVersion {
return mailRequestedPayload{}, rejected(fmt.Sprintf("schema version %d is not supported", event.SchemaVersion))
}
if event.AggregateType != mailRequestAggregateType || event.AggregateID == uuid.Nil {
return mailRequestedPayload{}, rejected("aggregate must be a mail_request with an ID")
}
var payload mailRequestedPayload
decoder := json.NewDecoder(bytes.NewReader(event.Payload))
// The decoder error can quote a fragment of the payload, so it is not
// wrapped. A second value after the object is refused as well.
if err := decoder.Decode(&payload); err != nil {
return mailRequestedPayload{}, rejected("payload is not a valid mail request")
}
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
return mailRequestedPayload{}, rejected("payload has data after the mail request")
}
switch {
case payload.MailRequestID != event.AggregateID:
return mailRequestedPayload{}, rejected("mail_request_id must equal the aggregate ID")
case payload.Kind != string(domain.MailKindNotification):
return mailRequestedPayload{}, rejected("kind must be notification in schema version 1")
}
return payload, nil
}
@@ -0,0 +1,148 @@
// Package notification turns mail requests into durable deliveries.
//
// A product usecase requests a notification mail inside its own transaction
// with MailRequester, which stores the request text in mail_requests and
// appends a notification.mail_requested event that names only the request.
// DeliveryHandler consumes the event and, in the transaction of the
// consumer's dedup marker, reads the request, resolves the recipient address
// from the account, renders the current template version once, stores the
// Delivery, and deletes the request. Sending the stored content is the job
// of the delivery worker, which is planned.
package notification
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
const (
// MailRequestedEventType announces a stored mail request.
MailRequestedEventType = "notification.mail_requested"
// mailRequestedSchemaVersion 1 is mailRequestedPayload.
mailRequestedSchemaVersion = 1
// mailRequestAggregateType names the request. Its aggregate ID is the
// request ID and the ID of the delivery it becomes; a request is never
// changed, so its version is 1.
mailRequestAggregateType = "mail_request"
mailRequestAggregateVersion = 1
)
// mailRequestedPayload is version 1 of the event payload. It names the
// request and its kind only. The text and the recipient stay in
// mail_requests, which the account's deletion removes, so neither the
// outbox table nor the event bus keeps personal data after the account is
// gone.
type mailRequestedPayload struct {
MailRequestID uuid.UUID `json:"mail_request_id"`
Kind string `json:"kind"`
}
// NotificationRenderer renders notification mail as the content a delivery
// stores.
type NotificationRenderer interface {
RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error)
}
// TemplateRenderer renders with the current versions of the embedded mail
// templates.
type TemplateRenderer struct {
renderer *mailtemplate.Renderer
}
func NewTemplateRenderer(renderer *mailtemplate.Renderer) TemplateRenderer {
return TemplateRenderer{renderer: renderer}
}
func (renderer TemplateRenderer) RenderNotification(data mailtemplate.NotificationData) (domain.MailContent, error) {
rendered, err := renderer.renderer.RenderNotification(data)
if err != nil {
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderNotification - render: %w", err)
}
content, err := rendered.Content()
if err != nil {
return domain.MailContent{}, fmt.Errorf("TemplateRenderer.RenderNotification - convert rendering: %w", err)
}
return content, nil
}
// NotificationRequest asks for one notification mail to one account.
type NotificationRequest struct {
RecipientUserID uuid.UUID
Notification mailtemplate.NotificationData
}
// MailRequester records mail requests in the caller's transaction.
type MailRequester struct {
renderer NotificationRenderer
clock func() time.Time
}
// NewMailRequester takes the renderer only to refuse data that the template
// would refuse at handling time, so a bad request fails its own transaction
// instead of becoming a dead letter later. clock is the application clock
// for the request time.
func NewMailRequester(renderer NotificationRenderer, clock func() time.Time) *MailRequester {
return &MailRequester{renderer: renderer, clock: clock}
}
// RequestNotification stores the request and appends a
// notification.mail_requested event through unit, which must be the caller's
// transaction, and returns the ID that the delivery will have. The mail is
// created only if that transaction commits. Invalid input returns an error
// wrapping domain.ErrInvalidMailRequest and writes nothing; an unknown
// recipient account returns an error wrapping outbound.ErrUserNotFound and
// aborts the transaction.
func (requester *MailRequester) RequestNotification(ctx context.Context, unit outbound.UnitOfWork, request NotificationRequest) (uuid.UUID, error) {
const location = "MailRequester.RequestNotification"
if _, err := requester.renderer.RenderNotification(request.Notification); err != nil {
return uuid.Nil, fmt.Errorf("%s - validate notification: %w: %w", location, domain.ErrInvalidMailRequest, err)
}
requestID, err := uuid.NewV7()
if err != nil {
return uuid.Nil, fmt.Errorf("%s - generate request ID: %w", location, err)
}
stored, err := domain.NewMailRequest(domain.MailRequest{
ID: requestID,
RecipientUserID: request.RecipientUserID,
Kind: domain.MailKindNotification,
Notification: domain.NotificationText{
Subject: request.Notification.Subject,
Body: request.Notification.Body,
LinkPath: request.Notification.LinkPath,
},
CreatedAt: requester.clock(),
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build request: %w", location, err)
}
payload, err := json.Marshal(mailRequestedPayload{MailRequestID: requestID, Kind: string(domain.MailKindNotification)})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - encode payload: %w", location, err)
}
event, err := domain.NewDomainEvent(domain.DomainEventInput{
EventType: MailRequestedEventType,
SchemaVersion: mailRequestedSchemaVersion,
AggregateType: mailRequestAggregateType,
AggregateID: requestID,
AggregateVersion: mailRequestAggregateVersion,
Payload: payload,
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build event: %w", location, err)
}
if err := unit.MailRequests().Create(ctx, stored); err != nil {
return uuid.Nil, fmt.Errorf("%s - store request: %w", location, err)
}
if err := unit.Outbox().Append(ctx, event); err != nil {
return uuid.Nil, fmt.Errorf("%s - append event: %w", location, err)
}
return requestID, nil
}
@@ -1,7 +1,6 @@
package mailtemplate
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
@@ -15,7 +14,7 @@ import (
// the same digest, and any change to any part gives another one. The delivery
// layer can store it with the idempotency key to pin the body of one logical
// delivery and to detect a different body offered under the same key.
type ContentHash [sha256.Size]byte
type ContentHash [domain.MailContentHashSize]byte
// String returns the lowercase hex digest. It is not secret: SHA-256 over a
// body that holds a 256-bit token cannot be reversed.
@@ -50,7 +49,7 @@ func newRenderedMail(kind Kind, version TemplateVersion, subject, text, html str
subject: subject,
text: text,
html: html,
contentHash: contentHash(string(version), subject, text, html),
contentHash: ContentHash(domain.MailContentHash(string(version), subject, text, html)),
}}
}
@@ -78,6 +77,18 @@ func (mail RenderedMail) read() renderedContent {
return *mail.content
}
// Content returns the rendering as domain.MailContent, the form a delivery
// stores. The kinds and the hash are the same: both use
// domain.MailContentHash.
func (mail RenderedMail) Content() (domain.MailContent, error) {
content := mail.read()
stored, err := domain.NewMailContent(domain.MailKind(content.kind), string(content.version), content.subject, content.text, content.html)
if err != nil {
return domain.MailContent{}, fmt.Errorf("RenderedMail.Content - %w", err)
}
return stored, nil
}
// ToOutgoingMail addresses the rendering for the MailSender port. The
// recipient and the idempotency key come from the delivery, never from the
// template data.
@@ -13,7 +13,6 @@ package mailtemplate
import (
"bytes"
"crypto/sha256"
"embed"
"errors"
"fmt"
@@ -172,21 +171,6 @@ func finishPart(part string) string {
return strings.TrimSpace(part) + "\n"
}
// contentHash is SHA-256 over the parts encoded as netstrings ("<len>:<part>,"),
// so moving bytes from one part to the next changes the digest.
func contentHash(parts ...string) ContentHash {
digest := sha256.New()
for _, part := range parts {
// hash.Hash.Write never returns an error.
_, _ = fmt.Fprintf(digest, "%d:", len(part))
_, _ = io.WriteString(digest, part)
_, _ = io.WriteString(digest, ",")
}
var sum ContentHash
copy(sum[:], digest.Sum(nil))
return sum
}
// parseTemplates reads every file in the template directory. Each version
// must provide the subject, text, and HTML parts, and no other file may be
// present, so a misnamed file cannot be silently ignored.
@@ -306,9 +306,20 @@ func TestContentHashPinsTheBody(t *testing.T) {
if mail.ContentHash() != second[kind].ContentHash() {
t.Fatalf("%s content hash differs for the same version and data", kind)
}
if mail.ContentHash() != contentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML()) {
if mail.ContentHash() != ContentHash(domain.MailContentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML())) {
t.Fatalf("%s content hash does not cover the version, subject, and parts", kind)
}
// A delivery stores the rendering as domain.MailContent; both forms
// must name the same kind, version, parts, and hash.
content, err := mail.Content()
if err != nil {
t.Fatalf("%s Content() error = %v", kind, err)
}
if string(content.Kind()) != string(kind) || content.TemplateVersion() != string(mail.TemplateVersion()) ||
content.Subject() != mail.Subject() || content.Text() != mail.Text() || content.HTML() != mail.HTML() ||
ContentHash(content.Hash()) != mail.ContentHash() {
t.Fatalf("%s Content() does not carry the rendering", kind)
}
seen[mail.ContentHash()] = kind
}
if len(seen) != len(first) {
@@ -350,19 +361,6 @@ func TestContentHashPinsTheBody(t *testing.T) {
t.Fatalf("content hash did not change with the %s", change.name)
}
}
base := contentHash("verification.v1", "subject", "text", "html")
for name, other := range map[string]ContentHash{
"version": contentHash("verification.v2", "subject", "text", "html"),
"subject": contentHash("verification.v1", "subject!", "text", "html"),
"text": contentHash("verification.v1", "subject", "text!", "html"),
"html": contentHash("verification.v1", "subject", "text", "html!"),
"shifted border": contentHash("verification.v1", "subjec", "ttext", "html"),
} {
if other == base {
t.Fatalf("content hash ignores a change of the %s", name)
}
}
}
// TestRenderingNeverReachesLogs plays the render harness: it prints every
@@ -0,0 +1,453 @@
package notification
import (
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
const (
testOrigin = "https://lincodex.example"
// The private markers must never reach logs, errors, or events.
testRecipientAddress = "Private.Recipient@Example.com"
testSubject = "PRIVATE-SUBJECT invitation"
testBody = "PRIVATE-BODY: a company invited you."
testLinkPath = "/candidate/invitations"
)
var (
testNow = time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
errStorageDown = errors.New("storage unavailable")
privateMarkers = []string{testRecipientAddress, strings.ToLower(testRecipientAddress), "PRIVATE-SUBJECT", "PRIVATE-BODY"}
)
type fakeUsers struct {
outbound.UserRepository
users map[uuid.UUID]domain.User
err error
}
func (users *fakeUsers) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) {
if users.err != nil {
return domain.User{}, users.err
}
user, ok := users.users[id]
if !ok {
return domain.User{}, outbound.ErrUserNotFound
}
return user, nil
}
type fakeDeliveries struct {
outbound.DeliveryRepository
stored map[uuid.UUID]domain.Delivery
createErr error
}
func (deliveries *fakeDeliveries) Create(_ context.Context, delivery domain.Delivery) (bool, error) {
if deliveries.createErr != nil {
return false, deliveries.createErr
}
if _, ok := deliveries.stored[delivery.ID()]; ok {
return false, nil
}
deliveries.stored[delivery.ID()] = delivery
return true, nil
}
func (deliveries *fakeDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) {
delivery, ok := deliveries.stored[id]
if !ok {
return domain.Delivery{}, outbound.ErrDeliveryNotFound
}
return delivery, nil
}
type fakeMailRequests struct {
stored map[uuid.UUID]domain.MailRequest
createErr error
}
func (requests *fakeMailRequests) Create(_ context.Context, request domain.MailRequest) error {
if requests.createErr != nil {
return requests.createErr
}
requests.stored[request.ID] = request
return nil
}
func (requests *fakeMailRequests) Lock(_ context.Context, id uuid.UUID) (domain.MailRequest, error) {
request, ok := requests.stored[id]
if !ok {
return domain.MailRequest{}, outbound.ErrMailRequestNotFound
}
return request, nil
}
func (requests *fakeMailRequests) Delete(_ context.Context, id uuid.UUID) error {
delete(requests.stored, id)
return nil
}
type recordingOutbox struct {
events []domain.DomainEvent
err error
}
func (outbox *recordingOutbox) Append(_ context.Context, events ...domain.DomainEvent) error {
if outbox.err != nil {
return outbox.err
}
outbox.events = append(outbox.events, events...)
return nil
}
// fakeUnit implements the repositories the usecases use; any other call
// panics on the nil embedded interface.
type fakeUnit struct {
outbound.UnitOfWork
users *fakeUsers
deliveries *fakeDeliveries
requests *fakeMailRequests
outbox *recordingOutbox
}
func (unit fakeUnit) Users() outbound.UserRepository { return unit.users }
func (unit fakeUnit) Deliveries() outbound.DeliveryRepository { return unit.deliveries }
func (unit fakeUnit) MailRequests() outbound.MailRequestRepository { return unit.requests }
func (unit fakeUnit) Outbox() outbound.OutboxWriter { return unit.outbox }
type harness struct {
recipient domain.User
unit fakeUnit
handler *DeliveryHandler
requester *MailRequester
logs *bytes.Buffer
}
func newHarness(t *testing.T) *harness {
t.Helper()
renderer, err := mailtemplate.NewRenderer(testOrigin)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
email, err := domain.NewEmailAddress(testRecipientAddress)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
providerAccount, err := domain.NewMailProviderAccount("resend", "main")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
verifiedAt := testNow.Add(-time.Hour)
recipient := domain.User{ID: uuid.MustParse("01926f3a-7c00-7000-8000-0000000000aa"), Email: email, EmailVerifiedAt: &verifiedAt}
logs := &bytes.Buffer{}
templates := NewTemplateRenderer(renderer)
clock := func() time.Time { return testNow }
return &harness{
recipient: recipient,
unit: fakeUnit{
users: &fakeUsers{users: map[uuid.UUID]domain.User{recipient.ID: recipient}},
deliveries: &fakeDeliveries{stored: make(map[uuid.UUID]domain.Delivery)},
requests: &fakeMailRequests{stored: make(map[uuid.UUID]domain.MailRequest)},
outbox: &recordingOutbox{},
},
handler: NewDeliveryHandler(templates, providerAccount, clock, slog.New(slog.NewJSONHandler(logs, nil))),
requester: NewMailRequester(templates, clock),
logs: logs,
}
}
func testNotification() mailtemplate.NotificationData {
return mailtemplate.NotificationData{Subject: testSubject, Body: testBody, LinkPath: testLinkPath}
}
// request records a notification request and returns its event as the
// consumer receives it from the event bus.
func (h *harness) request(t *testing.T) outbound.ConsumedEvent {
t.Helper()
before := len(h.unit.outbox.events)
requestID, err := h.requester.RequestNotification(t.Context(), h.unit, NotificationRequest{
RecipientUserID: h.recipient.ID,
Notification: testNotification(),
})
if err != nil {
t.Fatalf("RequestNotification() error = %v", err)
}
if len(h.unit.outbox.events) != before+1 || h.unit.outbox.events[before].AggregateID() != requestID {
t.Fatalf("RequestNotification() did not append one event for request %s", requestID)
}
return consumedEvent(h.unit.outbox.events[before])
}
func consumedEvent(event domain.DomainEvent) outbound.ConsumedEvent {
return outbound.ConsumedEvent{
EventID: event.EventID(),
EventType: event.EventType(),
SchemaVersion: event.SchemaVersion(),
AggregateType: event.AggregateType(),
AggregateID: event.AggregateID(),
AggregateVersion: event.AggregateVersion(),
OccurredAt: testNow,
Payload: event.Payload(),
}
}
func (h *harness) assertNoPrivateData(t *testing.T, texts ...string) {
t.Helper()
for _, text := range append(texts, h.logs.String()) {
for _, marker := range privateMarkers {
if strings.Contains(text, marker) {
t.Fatalf("personal data %q reached an error, event, or log: %s", marker, text)
}
}
}
}
func TestRequestNotificationStoresTheTextAndAnnouncesOnlyIDs(t *testing.T) {
h := newHarness(t)
event := h.request(t)
if event.EventType != MailRequestedEventType || event.SchemaVersion != 1 ||
event.AggregateType != "mail_request" || event.AggregateVersion != 1 {
t.Fatalf("event = %s v%d %s/%d", event.EventType, event.SchemaVersion, event.AggregateType, event.AggregateVersion)
}
var payload map[string]any
if err := json.Unmarshal(event.Payload, &payload); err != nil {
t.Fatalf("decode payload: %v", err)
}
if len(payload) != 2 || payload["mail_request_id"] != event.AggregateID.String() || payload["kind"] != "notification" {
t.Fatalf("payload = %v, want only the request ID and the kind", payload)
}
h.assertNoPrivateData(t, string(event.Payload))
stored, ok := h.unit.requests.stored[event.AggregateID]
if !ok || stored.RecipientUserID != h.recipient.ID || stored.Kind != domain.MailKindNotification ||
stored.Notification.Subject != testSubject || stored.Notification.Body != testBody ||
stored.Notification.LinkPath != testLinkPath || !stored.CreatedAt.Equal(testNow) {
t.Fatal("the request text was not stored under the event's aggregate ID")
}
}
func TestRequestNotificationRefusesInvalidRequestsBeforeWriting(t *testing.T) {
h := newHarness(t)
hostileLink := testNotification()
hostileLink.LinkPath = "https://evil.example/phish"
nul := testNotification()
nul.Subject += "\x00"
tests := map[string]NotificationRequest{
"nil recipient": {Notification: testNotification()},
"link outside the app": {RecipientUserID: h.recipient.ID, Notification: hostileLink},
"empty notification": {RecipientUserID: h.recipient.ID},
"NUL in the subject": {RecipientUserID: h.recipient.ID, Notification: nul},
}
for name, request := range tests {
t.Run(name, func(t *testing.T) {
_, err := h.requester.RequestNotification(t.Context(), h.unit, request)
if !errors.Is(err, domain.ErrInvalidMailRequest) {
t.Fatalf("RequestNotification() error = %v, want ErrInvalidMailRequest", err)
}
if len(h.unit.outbox.events) != 0 || len(h.unit.requests.stored) != 0 {
t.Fatal("an invalid request was written")
}
h.assertNoPrivateData(t, err.Error())
})
}
h.unit.requests.createErr = outbound.ErrUserNotFound
_, err := h.requester.RequestNotification(t.Context(), h.unit, NotificationRequest{RecipientUserID: h.recipient.ID, Notification: testNotification()})
if !errors.Is(err, outbound.ErrUserNotFound) || len(h.unit.outbox.events) != 0 {
t.Fatalf("RequestNotification() for an unknown account error = %v, events = %d", err, len(h.unit.outbox.events))
}
}
func TestDeliveryHandlerStoresTheRenderedRequest(t *testing.T) {
h := newHarness(t)
event := h.request(t)
if h.handler.ConsumerName() != DeliveryConsumerName || !h.handler.Handles(event.EventType) || h.handler.Handles("identity.user_registered") {
t.Fatal("the handler does not claim exactly the mail request events")
}
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
delivery, ok := h.unit.deliveries.stored[event.AggregateID]
if !ok || len(h.unit.deliveries.stored) != 1 {
t.Fatalf("Handle() stored %d deliveries, want one under the request ID", len(h.unit.deliveries.stored))
}
switch {
case delivery.SourceEventID() != event.EventID:
t.Fatal("the delivery does not name its source event")
case delivery.RecipientUserID() != h.recipient.ID || delivery.Recipient().Address() != testRecipientAddress:
t.Fatal("the delivery is not addressed to the account email")
case delivery.Kind() != domain.MailKindNotification || delivery.Content().TemplateVersion() != "notification.v1":
t.Fatalf("the delivery has kind %s and version %s", delivery.Kind(), delivery.Content().TemplateVersion())
case !strings.Contains(delivery.Content().Text(), "PRIVATE-BODY") || !strings.Contains(delivery.Content().Text(), testOrigin+testLinkPath):
t.Fatal("the stored body is not the rendering of the request")
case delivery.ProviderAccount().Provider() != "resend" || delivery.ProviderAccount().Account() != "main":
t.Fatal("the delivery is not pinned to the configured provider account")
case delivery.Status() != domain.DeliveryStatusPending || !delivery.CreatedAt().Equal(testNow):
t.Fatalf("the delivery is %s, created %s", delivery.Status(), delivery.CreatedAt())
}
if len(h.unit.requests.stored) != 0 {
t.Fatal("the handled request was not deleted")
}
// The same event again finds no request and keeps the first delivery.
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("second Handle() error = %v", err)
}
if len(h.unit.deliveries.stored) != 1 {
t.Fatal("a repeated request created a second delivery")
}
h.assertNoPrivateData(t)
}
func TestDeliveryHandlerChecksAnExistingDeliveryUnderTheRequestID(t *testing.T) {
h := newHarness(t)
event := h.request(t)
request := h.unit.requests.stored[event.AggregateID]
// A delivery for the same recipient and kind is accepted as the result.
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v", err)
}
h.unit.requests.stored[request.ID] = request
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() over a matching delivery error = %v", err)
}
if len(h.unit.requests.stored) != 0 {
t.Fatal("the request was not deleted after the matching delivery")
}
// A delivery for another recipient under the same ID is a contract
// violation.
other := request
other.RecipientUserID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000bb")
h.unit.users.users[other.RecipientUserID] = domain.User{ID: other.RecipientUserID, Email: h.recipient.Email, EmailVerifiedAt: h.recipient.EmailVerifiedAt}
h.unit.requests.stored[request.ID] = other
err := h.handler.Handle(t.Context(), h.unit, event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() over a delivery for another recipient error = %v, want ErrEventRejected", err)
}
h.assertNoPrivateData(t, err.Error())
}
func TestDeliveryHandlerRejectsBrokenRequestsWithoutQuotingThem(t *testing.T) {
h := newHarness(t)
valid := h.request(t)
tests := map[string]func(*outbound.ConsumedEvent){
"newer schema version": func(event *outbound.ConsumedEvent) { event.SchemaVersion = 2 },
"other aggregate": func(event *outbound.ConsumedEvent) { event.AggregateType = "user" },
"nil aggregate ID": func(event *outbound.ConsumedEvent) { event.AggregateID = uuid.Nil },
"payload not an object": func(event *outbound.ConsumedEvent) { event.Payload = json.RawMessage(`["PRIVATE-SUBJECT"]`) },
"trailing data": func(event *outbound.ConsumedEvent) {
event.Payload = append(append(json.RawMessage{}, event.Payload...), []byte(` {"PRIVATE-SUBJECT":1}`)...)
},
"request ID not the aggregate": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"01926f3a-7c00-7000-8000-0000000000cc","kind":"notification"}`)
},
"request ID not a UUID": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"PRIVATE-SUBJECT","kind":"notification"}`)
},
"token mail kind": func(event *outbound.ConsumedEvent) {
event.Payload = json.RawMessage(`{"mail_request_id":"` + event.AggregateID.String() + `","kind":"verification"}`)
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
event := valid
change(&event)
err := h.handler.Handle(t.Context(), h.unit, event)
if !errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want ErrEventRejected", err)
}
if len(h.unit.deliveries.stored) != 0 {
t.Fatal("a rejected request created a delivery")
}
h.assertNoPrivateData(t, err.Error())
})
}
t.Run("text the template refuses", func(t *testing.T) {
request := h.unit.requests.stored[valid.AggregateID]
request.Notification.LinkPath = "//evil.example/PRIVATE-SUBJECT"
h.unit.requests.stored[valid.AggregateID] = request
err := h.handler.Handle(t.Context(), h.unit, valid)
if !errors.Is(err, inbound.ErrEventRejected) || len(h.unit.deliveries.stored) != 0 {
t.Fatalf("Handle() error = %v, want ErrEventRejected and no delivery", err)
}
h.assertNoPrivateData(t, err.Error())
})
}
func TestDeliveryHandlerSkipsRequestsItMustNotDeliver(t *testing.T) {
tests := map[string]func(*harness, outbound.ConsumedEvent){
"request already gone": func(h *harness, event outbound.ConsumedEvent) {
delete(h.unit.requests.stored, event.AggregateID)
},
"account gone": func(h *harness, _ outbound.ConsumedEvent) {
delete(h.unit.users.users, h.recipient.ID)
},
"address not verified": func(h *harness, _ outbound.ConsumedEvent) {
unverified := h.recipient
unverified.EmailVerifiedAt = nil
h.unit.users.users[h.recipient.ID] = unverified
},
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
event := h.request(t)
change(h, event)
if err := h.handler.Handle(t.Context(), h.unit, event); err != nil {
t.Fatalf("Handle() error = %v, want the request skipped", err)
}
if len(h.unit.deliveries.stored) != 0 || len(h.unit.requests.stored) != 0 {
t.Fatal("a skipped request created a delivery or stayed stored")
}
if !strings.Contains(h.logs.String(), event.AggregateID.String()) || !strings.Contains(h.logs.String(), event.EventID.String()) {
t.Fatalf("the skip log does not name the delivery and event IDs: %s", h.logs.String())
}
h.assertNoPrivateData(t)
})
}
}
func TestDeliveryHandlerRetriesStorageFailures(t *testing.T) {
for name, change := range map[string]func(*fakeUnit){
"account read": func(unit *fakeUnit) { unit.users.err = errStorageDown },
"insert": func(unit *fakeUnit) { unit.deliveries.createErr = errStorageDown },
// The account was deleted between its read and the insert. The insert
// aborted the transaction, so the handler cannot skip here; the retry
// finds the request deleted with the account and skips it.
"account deleted before the insert": func(unit *fakeUnit) { unit.deliveries.createErr = outbound.ErrUserNotFound },
} {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
event := h.request(t)
change(&h.unit)
err := h.handler.Handle(t.Context(), h.unit, event)
if err == nil || errors.Is(err, inbound.ErrEventRejected) {
t.Fatalf("Handle() error = %v, want a retryable storage error", err)
}
if len(h.unit.requests.stored) != 1 {
t.Fatal("a failed attempt deleted the request")
}
h.assertNoPrivateData(t, err.Error())
})
}
}