454 lines
17 KiB
Go
454 lines
17 KiB
Go
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())
|
|
})
|
|
}
|
|
}
|