feat(notifications): send product notifications with a rights check right before each send

This commit is contained in:
shira committed 2026-10-09 20:38:39 +03:00
1 parent a856066316
commit 623d41b969
59 files changed
+4125 -1126

No files matched your search

@@ -541,6 +541,10 @@ func TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries(t *test
}
// A rollback keeps the expiry, which the previous schema cannot represent.
// Migrations 44 and 45 sit above this one; they hold no rows that the
// expiry depends on, so they are rolled back first and the rollback of 43
// is the one that must be refused.
rollBackAboveVersion(ctx, t, migrator, invitationExpiryMigrationVersion)
if _, err := migrator.DownOne(ctx); err == nil {
t.Fatal("rollback with an expired invitation succeeded, want it refused")
}
+137 -3
View File
@@ -30,6 +30,7 @@ import (
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/worker/mailsender"
@@ -321,6 +322,85 @@ func TestServiceMailSending(t *testing.T) {
harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "verify-email")
})
t.Run("a password reset email for an account without C2 is accepted by the local Resend fixture", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
user := harness.createUser(ctx, t, true)
raw, token, deliveryID := harness.enqueuePasswordReset(ctx, t, user, mailSenderTokenLifetime)
assertRowCount(ctx, t, pool, pgx.Identifier{"consent_records"}, 0)
stored := harness.delivery(ctx, t, deliveryID)
if stored.Status() != domain.DeliveryStatusPending || stored.Kind() != domain.MailKindPasswordReset || stored.EmailTokenID() != token.ID {
t.Fatalf("enqueued delivery is %s of kind %s bound to %v", stored.Status(), stored.Kind(), stored.EmailTokenID())
}
sender := harness.newSender(t, harness.transactor, 100, 3000)
result := harness.pass(ctx, t, sender)
if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID {
t.Fatalf("pass = %+v, want accepted for the enqueued delivery", result)
}
requests := fixture.Requests()[calls:]
if len(requests) != 1 {
t.Fatalf("the fixture received %d calls, want 1", len(requests))
}
request := requests[0]
link := harness.publicURL + "/reset-password#token=" + raw.Reveal()
switch {
case len(request.To) != 1 || request.To[0] != user.Email.Address():
t.Fatal("the message was not addressed to the account")
case !strings.Contains(request.Text, link) || !strings.Contains(request.HTML, link):
t.Fatal("the message does not carry the reset link with its token in the fragment")
case strings.Contains(request.Text, "?token=") || strings.Contains(request.HTML, "?token="):
t.Fatal("the token travels in a query")
}
accepted := harness.delivery(ctx, t, deliveryID)
if accepted.Status() != domain.DeliveryStatusAccepted || accepted.AttemptCount() != 1 {
t.Fatalf("delivery is %s after %d attempts, want accepted after one attempt", accepted.Status(), accepted.AttemptCount())
}
harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "reset-password")
})
t.Run("a verification mail goes out after the account's C2 was granted and revoked before the worker runs", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
user := harness.createUser(ctx, t, false)
_, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
// C2 is granted and revoked while the mail waits. The publication
// history must not hold the mail back: only the account and the token
// decide, as ServiceMailState reads nothing else.
c2Text, err := postgresadapter.NewConsentStore(pool).ConsentTexts().Current(ctx, domain.ConsentPurposePublication, harness.clock.Now())
if err != nil {
t.Fatalf("read the current C2 text: %v", err)
}
consentService := consent.NewService(harness.transactor, harness.clock.Now)
granted, err := consentService.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{
SubjectID: user.ID, Purpose: domain.ConsentPurposePublication, TextVersion: c2Text.Version(),
})
if err != nil || !granted.Created {
t.Fatalf("grant C2 = created %t, %v; want a new record", granted.Created, err)
}
revocation, err := consentService.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{
SubjectID: user.ID, Purpose: domain.ConsentPurposePublication,
})
if err != nil || len(revocation.Records) != 1 {
t.Fatalf("revoke C2 = %d records, %v; want one revoked record", len(revocation.Records), err)
}
if _, revoked := revocation.Records[0].RevokedAt(); !revoked {
t.Fatal("the C2 record is not revoked")
}
sender := harness.newSender(t, harness.transactor, 100, 3000)
result := harness.pass(ctx, t, sender)
if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID {
t.Fatalf("pass = %+v, want the verification mail accepted after C2 was revoked", result)
}
requests := fixture.Requests()[calls:]
if len(requests) != 1 || len(requests[0].To) != 1 || requests[0].To[0] != user.Email.Address() {
t.Fatalf("the fixture received %d calls, want one to the account", len(requests))
}
})
t.Run("an accepted request with a lost response retries under the same key within 24 hours", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
@@ -637,6 +717,39 @@ func TestServiceMailSending(t *testing.T) {
harness.assertQuotaUsage(ctx, t, 0)
})
t.Run("a verification mail revoked before its send is cancelled, keeps its account, and stays out of the logs", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
user := harness.createUser(ctx, t, false)
raw, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime)
if invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil || invalidated != 1 {
t.Fatalf("InvalidateActive() = %d, %v; want 1", invalidated, err)
}
sender := harness.newSender(t, harness.transactor, 100, 3000)
if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelTokenRevoked {
t.Fatalf("pass = %+v, want cancelled with reason %s", result, domain.DeliveryCancelTokenRevoked)
}
if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle {
t.Fatalf("pass after the cancellation = %+v, want idle", again)
}
if got := len(fixture.Requests()[calls:]); got != 0 {
t.Fatalf("the provider received %d calls, want none for a revoked mail", got)
}
cancelled := harness.delivery(ctx, t, deliveryID)
switch {
case cancelled.Status() != domain.DeliveryStatusCancelled || cancelled.CancelReason() != domain.DeliveryCancelTokenRevoked:
t.Fatalf("delivery is %s (%s), want cancelled by a revoked token", cancelled.Status(), cancelled.CancelReason())
case cancelled.ProviderAccount() != harness.account || cancelled.AttemptCount() != 0 || cancelled.ProviderMessageID() != "":
t.Fatal("the cancellation changed the transport account or recorded an attempt")
case !cancelled.Content().Redacted() || cancelled.Content().Text() != "":
t.Fatal("the body of the cancelled mail is still stored")
}
// The address, the token, the link, and the account ID never reach the logs.
harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), user.ID.String(), "verify-email")
})
t.Run("a delivery that cannot be restored is cancelled and does not block the queue", func(t *testing.T) {
reset(t)
calls := len(fixture.Requests())
@@ -1695,13 +1808,34 @@ func (harness *senderHarness) createUser(ctx context.Context, t *testing.T, veri
// enqueueVerification issues a token and stores its mail in one transaction,
// as the registration flow will.
func (harness *senderHarness) enqueueVerification(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) {
t.Helper()
return harness.enqueueToken(ctx, t, user, domain.EmailTokenPurposeEmailVerification, lifetime, harness.mailer.EnqueueVerification)
}
// enqueuePasswordReset issues a password reset token and stores its mail in
// one transaction, as the reset flow will.
func (harness *senderHarness) enqueuePasswordReset(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) {
t.Helper()
return harness.enqueueToken(ctx, t, user, domain.EmailTokenPurposePasswordReset, lifetime, harness.mailer.EnqueuePasswordReset)
}
// enqueueToken issues a token of purpose and stores the mail that enqueue
// builds for it, in the same transaction as the token.
func (harness *senderHarness) enqueueToken(
ctx context.Context,
t *testing.T,
user domain.User,
purpose domain.EmailTokenPurpose,
lifetime time.Duration,
enqueue func(context.Context, outbound.UnitOfWork, notification.TokenMailRequest) (uuid.UUID, error),
) (domain.SecretToken, domain.EmailToken, uuid.UUID) {
t.Helper()
raw, err := domain.NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(),
UserID: user.ID, Purpose: purpose, TokenHash: raw.Hash(),
RegistrationVersion: user.RegistrationVersion, IssuedAt: harness.clock.Now(), Lifetime: lifetime,
})
if err != nil {
@@ -1712,13 +1846,13 @@ func (harness *senderHarness) enqueueVerification(ctx context.Context, t *testin
if err := unit.EmailTokens().Insert(ctx, token); err != nil {
return err
}
deliveryID, err = harness.mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{
deliveryID, err = enqueue(ctx, unit, notification.TokenMailRequest{
Recipient: user.Email, Token: token, RawToken: raw, Lifetime: domain.Hours(lifetime / time.Hour),
})
return err
})
if err != nil {
t.Fatalf("enqueue the verification mail: %v", err)
t.Fatalf("enqueue the %s mail: %v", purpose, err)
}
return raw, token, deliveryID
}
@@ -0,0 +1,108 @@
//go:build integration
package integration_test
import (
"context"
"crypto/sha256"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
// notificationSubjectMigrationVersion adds the subject columns of notifications;
// productNoticeMigrationVersion adds the rights reasons, the body clearing of a
// cancelled notice, and the product due index on top of it.
const (
notificationSubjectMigrationVersion = 44
productNoticeMigrationVersion = 45
)
// TestNotificationSubjectMigrations checks the constraints that the rights
// checks rely on, and that the rollback of the two migrations refuses while
// rows name a subject or carry a rights cancellation, and runs once they are gone.
func TestNotificationSubjectMigrations(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
now := time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC)
userID, deliveryID, invitationID, organizationID := uuid.New(), uuid.New(), uuid.New(), uuid.New()
exec := func(statement string, args ...any) error {
t.Helper()
_, err := pool.Exec(ctx, statement, args...)
return err
}
if err := exec(`INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, email_verified_at,
registration_version, last_registered_at, version, created_at, updated_at)
VALUES ($1, 'notice@example.com', 'notice@example.com', $2, 'candidate', 'candidate_consents', $3, 1, $3, 1, $3, $3)`,
userID, identityTestPasswordHash, now); err != nil {
t.Fatalf("insert the account: %v", err)
}
// A cancelled notice that names its invitation and has no bodies is what
// the sending worker stores after a rights check.
if err := exec(`INSERT INTO deliveries (id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body,
content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version,
created_at, updated_at, cancel_reason, body_redacted_at, subject_kind, subject_id, subject_organization_id)
VALUES ($1, $2, 'notice@example.com', 'notification', 'notification.v1', 's', '', '', $3, 'resend', 'main',
'delivery/notice', 'cancelled', 0, NULL, 2, $4, $4, 'rights_revoked', $4, 'invitation', $5, $6)`,
deliveryID, userID, make([]byte, sha256.Size), now, invitationID, organizationID); err != nil {
t.Fatalf("store a cancelled notice with its subject: %v", err)
}
// A subject belongs to a notification only, and the three subject columns
// are set together.
if err := exec(`INSERT INTO deliveries (id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body,
content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version,
created_at, updated_at, subject_kind, subject_id, subject_organization_id)
VALUES ($1, $2, 'notice@example.com', 'verification', 'verification.v1', 's', 't', '', $3, 'resend', 'main',
'delivery/subject-verification', 'pending', 0, $4, 1, $4, $4, 'invitation', $5, $6)`,
uuid.New(), userID, make([]byte, sha256.Size), now, invitationID, organizationID); err == nil || !strings.Contains(err.Error(), "deliveries_subject_complete") {
t.Fatalf("a subject on a verification mail: error = %v, want deliveries_subject_complete", err)
}
// Bodies are cleared only for a cancelled notice or a terminal token mail.
if err := exec(`INSERT INTO deliveries (id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body,
content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version,
created_at, updated_at, body_redacted_at)
VALUES ($1, $2, 'notice@example.com', 'notification', 'notification.v1', 's', '', '', $3, 'resend', 'main',
'delivery/cleared-pending', 'pending', 0, $4, 1, $4, $4, $4)`,
uuid.New(), userID, make([]byte, sha256.Size), now); err == nil || !strings.Contains(err.Error(), "deliveries_body_present") {
t.Fatalf("a pending notice without bodies: error = %v, want deliveries_body_present", err)
}
// The subject is fixed with the delivery, like its content.
// The trigger reports its refusal by message, not by constraint name.
if err := exec(`UPDATE deliveries SET subject_id = gen_random_uuid() WHERE id = $1`, deliveryID); err == nil ||
!strings.Contains(err.Error(), "content and recipient are immutable") {
t.Fatalf("changing the subject: error = %v, want the content refusal", err)
}
// The rollback refuses while the schema holds rights cancellations.
if _, err := migrator.DownOne(ctx); err == nil || !strings.Contains(err.Error(), "rights check") {
t.Fatalf("DownOne() with a rights cancellation stored: error = %v, want the refusal that names the rights check", err)
}
// Once the account is gone, its notices go with it, and the rollback runs.
if err := exec(`DELETE FROM users WHERE id = $1`, userID); err != nil {
t.Fatalf("delete the account: %v", err)
}
for _, version := range []int64{productNoticeMigrationVersion, notificationSubjectMigrationVersion} {
result, err := migrator.DownOne(ctx)
if err != nil {
t.Fatalf("DownOne() to below %d error = %v", version, err)
}
if result.Version != version {
t.Fatalf("DownOne() rolled back %d, want %d", result.Version, version)
}
}
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() after the rollback error = %v", err)
}
}
@@ -0,0 +1,625 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
identityusecase "lincodex/backend/internal/usecase/identity"
invitationusecase "lincodex/backend/internal/usecase/invitation"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/usecase/policy"
)
const (
productNoticeTimeout = 5 * time.Minute
// productNoticeOrganization names the sending organization. The notice
// must never carry it, so the tests look for it in the mail and the logs.
productNoticeOrganization = "Notice company"
// productNoticeBody is the start of the neutral body of an invitation
// notice; the full text stays in the mail templates.
productNoticeBody = "Работодатель отправил вам приглашение"
// productNoticeConcurrentWorkers drain one queue at once, each with its
// own sender, as separate processes do.
productNoticeConcurrentWorkers = 4
productNoticeQueued = 6
// productNoticeBacklog is the number of due rows that the other lane holds
// while the product claim is explained.
productNoticeBacklog = 5000
)
// productNoticeFixture drives the invitation send with the real notifier, the
// consumer that stores its notice, and the notification sender, against one
// isolated database and the local Resend fixture.
type productNoticeFixture struct {
ctx context.Context
pool *pgxpool.Pool
transactor *postgresadapter.Transactor
identity identityFixture
organizations organizationFixture
clock *testClock
key domain.CandidateViewPseudonymKey
handles map[string]uuid.UUID
organization domain.Organization
owner domain.User
service *invitationusecase.Service
renderer *mailtemplate.Renderer
account domain.MailProviderAccount
mail *resendfixture.Server
transport outbound.MailSender
logs *syncBuffer
// harness reads the deliveries and runs the service sender, which the
// notice tests share.
harness *senderHarness
publicURL string
}
func newProductNoticeFixture(ctx context.Context, t *testing.T, env *testEnvironment) *productNoticeFixture {
t.Helper()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)}
transactor := postgresadapter.NewTransactor(pool)
identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()}
organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()}
owner := organizations.employer(t, "notice-owner@example.test")
confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute))
organization := organizations.create(t, owner, organizations.completeProfile(t, productNoticeOrganization), clock.Now())
keyring, err := identityusecase.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
key, err := keyring.CandidateViewPseudonymKey()
if err != nil {
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
}
renderer, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
account, err := domain.NewMailProviderAccount("resend", mailSenderAccount)
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
mail := resendfixture.New()
t.Cleanup(mail.Close)
mail.SetClock(clock.Now)
transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, mail.URL(), clock.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(renderer), clock.Now))
if err != nil {
t.Fatalf("NewInvitationNotifier() error = %v", err)
}
logs := &syncBuffer{}
fixture := &productNoticeFixture{
ctx: ctx, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock,
key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, renderer: renderer,
account: account, mail: mail, transport: transport, logs: logs, publicURL: env.Config.AppPublicURL,
}
quota := companyquota.NewService(clock.Now)
fixture.service, err = invitationusecase.NewService(invitationusecase.Dependencies{
Transactor: transactor, Keyring: keyring, PseudonymKey: key,
Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) {
candidateID, ok := fixture.handles[handle]
if !ok || organizationID != organization.ID() {
return uuid.Nil, candidateview.ErrCandidateCardNotFound
}
return candidateID, nil
},
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveInvitation(ctx, unit, organization, invitationID)
},
Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now,
})
if err != nil {
t.Fatalf("invitation.NewService() error = %v", err)
}
// The organization is E1, so one owner may send more than the E0 quota
// allows; the rights under test do not depend on the quota.
if _, err := pool.Exec(ctx, `
UPDATE organizations
SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2
WHERE id = $1`, organization.ID(), clock.Now()); err != nil {
t.Fatalf("raise the organization to E1: %v", err)
}
fixture.harness = &senderHarness{
pool: pool,
transactor: transactor,
identity: postgresadapter.NewIdentityStore(pool),
deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(),
mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, clock.Now),
fixture: mail,
transport: transport,
account: account,
clock: clock,
logs: logs,
publicURL: env.Config.AppPublicURL,
}
return fixture
}
// candidate makes a verified candidate with a current publication (C2) and
// the card handle of the organization, so that the send accepts it.
func (fixture *productNoticeFixture) candidate(t *testing.T, email string) domain.User {
t.Helper()
user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour))
confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute))
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
fixture.handles[handle] = user.ID
fixture.publish(t, user.ID)
return user
}
// publish stores a C2 grant and a published card that names it, the state an
// invitation is sent under.
func (fixture *productNoticeFixture) publish(t *testing.T, userID uuid.UUID) {
t.Helper()
ledger := postgresadapter.NewConsentStore(fixture.pool)
text, err := ledger.ConsentTexts().Get(fixture.ctx, domain.ConsentPurposePublication, privacyC2Version)
if err != nil {
t.Fatalf("ConsentTexts().Get(c2) error = %v", err)
}
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
SubjectID: userID, Purpose: domain.ConsentPurposePublication, TextVersion: text.Version(), TextHash: text.Hash(),
Source: domain.ConsentSourceConsentSettings, GrantedAt: fixture.clock.Now().Add(-time.Hour),
})
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
}
record, created, err := ledger.ConsentLedger().Grant(fixture.ctx, grant)
if err != nil || !created {
t.Fatalf("Grant(c2) = %t, %v; want a new record", created, err)
}
request, err := domain.NewPublicationRequest(domain.PublicationPublished, []domain.CardField{domain.CardFieldStack, domain.CardFieldCategories})
if err != nil {
t.Fatalf("NewPublicationRequest() error = %v", err)
}
empty, err := domain.NewPublication(userID)
if err != nil {
t.Fatalf("NewPublication() error = %v", err)
}
change, err := empty.Apply(request, 0, record.ID(), fixture.clock.Now())
if err != nil || !change.Changed {
t.Fatalf("Apply(publish) = %+v, %v; want a change", change, err)
}
if _, err := sqlc.New(fixture.pool).InsertCandidatePublication(fixture.ctx, sqlc.InsertCandidatePublicationParams{
UserID: uuidParam(userID), State: string(change.Publication.StoredState()), Fields: change.Publication.StoredFields(),
ConsentRecordID: uuidParam(record.ID()), PublishedAt: timeParam(change.Publication.PublishedAt()),
ClosedAt: pgtype.Timestamptz{}, At: timeParam(fixture.clock.Now()),
}); err != nil {
t.Fatalf("InsertCandidatePublication() error = %v", err)
}
}
func (fixture *productNoticeFixture) handleOf(t *testing.T, candidateID uuid.UUID) string {
t.Helper()
handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID)
if err != nil {
t.Fatalf("ForOrganization() error = %v", err)
}
return handle
}
// invite drafts an invitation for the candidate and sends it. The send records
// the notice request in the same transaction, as it does in production.
func (fixture *productNoticeFixture) invite(t *testing.T, candidateID uuid.UUID) domain.OrganizationInvitationView {
t.Helper()
key := "create-" + uuid.NewString()
draft, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{
ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key,
CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID),
Terms: invitationStorageTerms(),
})
if err != nil {
t.Fatalf("Create() error = %v", err)
}
sent, err := fixture.service.Send(fixture.ctx, invitationusecase.SendCommand{
ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), InvitationID: draft.ID,
IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: draft.Version,
})
if err != nil {
t.Fatalf("Send() error = %v", err)
}
return sent
}
// deliverNotice runs the delivery consumer on the notice request that the send
// recorded, as the event consumer does, and returns the delivery ID.
func (fixture *productNoticeFixture) deliverNotice(t *testing.T, candidateID uuid.UUID) uuid.UUID {
t.Helper()
var event outbound.ConsumedEvent
var payload string
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at
FROM outbox_events
WHERE event_type = 'notification.mail_requested'
AND aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $1)`, candidateID).
Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, &event.AggregateID,
&event.AggregateVersion, &payload, &event.OccurredAt); err != nil {
t.Fatalf("read the notice request: %v", err)
}
event.Payload = []byte(payload)
event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond)
handler := notification.NewDeliveryHandler(notification.NewTemplateRenderer(fixture.renderer), fixture.account, fixture.clock.Now, slog.New(slog.DiscardHandler))
if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return handler.Handle(ctx, unit, event)
}); err != nil {
t.Fatalf("DeliveryHandler.Handle() error = %v", err)
}
var deliveryID uuid.UUID
if err := fixture.pool.QueryRow(fixture.ctx,
`SELECT id FROM deliveries WHERE recipient_user_id = $1 AND kind = 'notification'`, candidateID).Scan(&deliveryID); err != nil {
t.Fatalf("read the notice delivery: %v", err)
}
return deliveryID
}
// sender builds the notification lane with the reserve of its quota gate. The
// lane shares the transport, account, and timing of the service lane.
func (fixture *productNoticeFixture) sender(t *testing.T, daily, monthly, reserveDaily, reserveMonthly int64) *notification.DeliverySender {
t.Helper()
limits, err := domain.NewMailQuotaLimits(daily, monthly)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
logger := slog.New(slog.NewJSONHandler(fixture.logs, nil))
gate, err := notification.NewQuotaGate(fixture.account, limits, resend.IdempotencyWindow, fixture.clock.Now, logger).WithReserve(reserveDaily, reserveMonthly)
if err != nil {
t.Fatalf("WithReserve() error = %v", err)
}
sender, err := notification.NewNotificationSender(fixture.transactor, fixture.transport, gate, notification.DeliverySenderSettings{
Account: fixture.account,
Lease: mailSenderLease,
StoreTimeout: 30 * time.Second,
SettleBudget: mailSenderSettleBudget,
ShutdownSettleBudget: time.Second,
MaxFailures: 3,
Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute},
}, fixture.clock.Now, logger, []notification.SubjectRights{notification.NewInvitationNoticeRights()})
if err != nil {
t.Fatalf("NewNotificationSender() error = %v", err)
}
return sender
}
// deliveryRow reads the stored status, cancel reason, and bodies of a delivery,
// without decoding it, so a test sees what is in the table.
func (fixture *productNoticeFixture) deliveryRow(t *testing.T, id uuid.UUID) (status, reason, text, html string, redacted bool) {
t.Helper()
var cancelReason *string
var redactedAt *time.Time
if err := fixture.pool.QueryRow(fixture.ctx, `
SELECT status, cancel_reason, text_body, html_body, body_redacted_at FROM deliveries WHERE id = $1`, id).
Scan(&status, &cancelReason, &text, &html, &redactedAt); err != nil {
t.Fatalf("read delivery %s: %v", id, err)
}
if cancelReason != nil {
reason = *cancelReason
}
return status, reason, text, html, redactedAt != nil
}
// requestsFor returns the provider requests addressed to the address.
func (fixture *productNoticeFixture) requestsFor(address string) []resendfixture.Request {
var matching []resendfixture.Request
for _, request := range fixture.mail.Requests() {
for _, to := range request.To {
if to == address {
matching = append(matching, request)
break
}
}
}
return matching
}
func TestProductNoticeIsSentOnceByItsOwnWorker(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
candidate := fixture.candidate(t, "notice-sent@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
calls := len(fixture.mail.Requests())
serviceSender := fixture.harness.newSender(t, fixture.transactor, 100, 3000)
if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls {
t.Fatalf("service pass = %+v with %d provider calls; want idle and none: the service worker takes only service mail", result, len(fixture.mail.Requests())-calls)
}
if got := fixture.harness.delivery(ctx, t, deliveryID); got.Kind() != domain.MailKindNotification || got.Status() != domain.DeliveryStatusPending || got.Subject().Kind() != domain.MailSubjectInvitation {
t.Fatalf("stored notice = %s %s with subject %v; want a pending notification that names its invitation", got.Kind(), got.Status(), got.Subject())
}
productSender := fixture.sender(t, 100, 3000, 0, 0)
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("product pass = %+v, want accepted", result)
}
sent := fixture.requestsFor(candidate.Email.Address())
if len(sent) != 1 {
t.Fatalf("provider requests to the candidate = %d, want exactly one", len(sent))
}
if !strings.Contains(sent[0].Text, productNoticeBody) || strings.Contains(sent[0].Text, productNoticeOrganization) ||
strings.Contains(sent[0].Text, candidate.ID.String()) || !strings.Contains(sent[0].Text, "/candidate/invitations") {
t.Fatalf("notice body = %q; want the neutral text with the inbox link and no organization or identifier", sent[0].Text)
}
if got := fixture.harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 {
t.Fatalf("delivery is %s after %d attempts, want accepted after one", got.Status(), got.AttemptCount())
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls+1 {
t.Fatalf("pass after the send = %+v; want idle with no second request", result)
}
fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID))
}
func TestProductNoticeRightsAreCheckedBeforeEverySend(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
productSender := fixture.sender(t, 100, 3000, 0, 0)
t.Run("a candidate who hides the organization after the send gets no mail and the body is cleared", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-hidden@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
fixture.hide(t, candidate.ID)
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked {
t.Fatalf("pass = %+v, want cancelled as rights_revoked", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for a notice whose organization is hidden")
}
status, reason, text, html, redacted := fixture.deliveryRow(t, deliveryID)
if status != "cancelled" || reason != "rights_revoked" || text != "" || html != "" || !redacted {
t.Fatalf("stored notice is %s (%s) with bodies %q/%q redacted %v; want cancelled as rights_revoked with no body", status, reason, text, html, redacted)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle {
t.Fatalf("pass after the cancellation = %+v, want idle", result)
}
fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID))
})
t.Run("an address that is no longer verified gets no mail and is cancelled as recipient_ineligible", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-unverified@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
if _, err := fixture.pool.Exec(ctx, `UPDATE users SET email_verified_at = NULL, version = version + 1 WHERE id = $1`, candidate.ID); err != nil {
t.Fatalf("unverify the address: %v", err)
}
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRecipientIneligible {
t.Fatalf("pass = %+v, want cancelled as recipient_ineligible", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for an unverified address")
}
if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "recipient_ineligible" {
t.Fatalf("stored notice is %s (%s), want cancelled as recipient_ineligible", status, reason)
}
})
t.Run("a notice that names no subject has no right to check and is cancelled as source_closed", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-no-subject@example.test")
content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY notification\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: uuid.Must(uuid.NewV7()), RecipientUserID: candidate.ID, Recipient: candidate.Email,
Content: content, ProviderAccount: fixture.account, CreatedAt: fixture.clock.Now(),
})
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
if created, err := fixture.harness.deliveries.Create(ctx, delivery); err != nil || !created {
t.Fatalf("Create() = %t, %v; want the notice stored", created, err)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelSourceClosed {
t.Fatalf("pass = %+v, want cancelled as source_closed", result)
}
if status, _, text, _, _ := fixture.deliveryRow(t, delivery.ID()); status != "cancelled" || text != "" {
t.Fatalf("stored notice is %s with text %q, want cancelled with no body", status, text)
}
})
// The clock moves past the response deadline, so this subtest comes last.
t.Run("an invitation that passed its response deadline gets no mail and is cancelled as rights_revoked", func(t *testing.T) {
candidate := fixture.candidate(t, "notice-expired@example.test")
fixture.invite(t, candidate.ID)
deliveryID := fixture.deliverNotice(t, candidate.ID)
fixture.clock.Advance(400 * 24 * time.Hour)
calls := len(fixture.mail.Requests())
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked {
t.Fatalf("pass = %+v, want cancelled as rights_revoked", result)
}
if len(fixture.mail.Requests()) != calls {
t.Fatal("the transport was called for an expired invitation")
}
if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "rights_revoked" {
t.Fatalf("stored notice is %s (%s), want cancelled as rights_revoked", status, reason)
}
})
}
// hide records that the candidate hid the organization, as the privacy
// settings do.
func (fixture *productNoticeFixture) hide(t *testing.T, candidateID uuid.UUID) {
t.Helper()
if _, err := fixture.pool.Exec(fixture.ctx, `
INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`,
candidateID, fixture.organization.ID(), fixture.clock.Now()); err != nil {
t.Fatalf("hide the organization: %v", err)
}
}
func TestProductNoticeReserveLeavesServiceQuotaToServiceMail(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
// The day holds ten recipients. The notification lane keeps eight for other
// mail, so it admits two notices, and the service lane still has the full
// day.
productSender := fixture.sender(t, 10, 3000, 8, 0)
var waiting uuid.UUID
for index := range 3 {
candidate := fixture.candidate(t, fmt.Sprintf("notice-reserve-%d@example.test", index))
fixture.invite(t, candidate.ID)
id := fixture.deliverNotice(t, candidate.ID)
if index == 2 {
waiting = id
}
}
for range 2 {
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("notice pass = %+v, want accepted within the lane's share", result)
}
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassWaitingQuota {
t.Fatalf("third notice pass = %+v, want waiting_quota at the reserve", result)
}
midnight := domain.MailQuotaWindowsAt(fixture.clock.Now()).ResetAt(domain.MailQuotaPeriodDay)
if got := fixture.harness.delivery(ctx, t, waiting); got.Status() != domain.DeliveryStatusWaitingQuota || !got.NextAttemptAt().Equal(midnight) {
t.Fatalf("waiting notice is %s due %s, want waiting_quota until %s", got.Status(), got.NextAttemptAt(), midnight)
}
if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle {
t.Fatalf("notice pass while the reserve holds = %+v, want idle without a spin", result)
}
service := fixture.harness.createUser(ctx, t, false)
_, _, serviceID := fixture.harness.enqueueVerification(ctx, t, service, mailSenderTokenLifetime)
serviceSender := fixture.harness.newSender(t, fixture.transactor, 10, 3000)
if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassAccepted {
t.Fatalf("service pass = %+v, want the verification mail accepted under the reserve", result)
}
if got := fixture.harness.delivery(ctx, t, serviceID); got.Status() != domain.DeliveryStatusAccepted {
t.Fatalf("service mail is %s, want accepted", got.Status())
}
fixture.harness.assertQuotaUsage(ctx, t, 3)
if got := len(fixture.mail.Requests()); got != 3 {
t.Fatalf("provider calls = %d, want two notices and the service mail", got)
}
}
func TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
ids := make([]uuid.UUID, 0, productNoticeQueued)
for index := range productNoticeQueued {
candidate := fixture.candidate(t, fmt.Sprintf("notice-queue-%d@example.test", index))
fixture.invite(t, candidate.ID)
ids = append(ids, fixture.deliverNotice(t, candidate.ID))
}
var group sync.WaitGroup
errs := make([]error, productNoticeConcurrentWorkers)
for worker := range productNoticeConcurrentWorkers {
sender := fixture.sender(t, 1000, 3000, 0, 0)
group.Go(func() {
for {
result, err := sender.ProcessNext(ctx, ctx)
if err != nil {
errs[worker] = err
return
}
if result.Outcome == inbound.MailPassIdle {
return
}
}
})
}
group.Wait()
if err := errors.Join(errs...); err != nil {
t.Fatalf("a worker failed: %v", err)
}
if got := len(fixture.mail.Requests()); got != productNoticeQueued {
t.Fatalf("provider calls = %d, want one per notice (%d)", got, productNoticeQueued)
}
for _, id := range ids {
if got := fixture.harness.delivery(ctx, t, id); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 {
t.Fatalf("notice %s is %s after %d attempts, want accepted after one", id, got.Status(), got.AttemptCount())
}
}
}
func TestProductNoticeClaimReadsItsOwnDueIndex(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout)
defer cancel()
fixture := newProductNoticeFixture(ctx, t, env)
// Service mail backlog: the product claim must not scan it.
if _, err := fixture.pool.Exec(ctx, `INSERT INTO deliveries (
id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256,
provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, created_at, updated_at
)
SELECT gen_random_uuid(), $1, 'backlog@example.com', 'verification', 'verification.v1', 's', 't', '', decode(repeat('00', 32), 'hex'),
'resend', $2, 'delivery/service-backlog-' || n, 'pending', 0, $3::timestamptz - interval '1 day', 1, $3, $3
FROM generate_series(1, $4::int) AS n`, fixture.identity.createUser(t, "backlog-owner@example.test", domain.ScenarioCandidate, fixture.clock.Now()).ID,
fixture.account.Account(), fixture.clock.Now(), productNoticeBacklog); err != nil {
t.Fatalf("insert the service backlog: %v", err)
}
if _, err := fixture.pool.Exec(ctx, "ANALYZE deliveries"); err != nil {
t.Fatalf("ANALYZE deliveries: %v", err)
}
rows, err := fixture.pool.Query(ctx, `EXPLAIN (COSTS OFF) SELECT due.id FROM deliveries AS due
WHERE due.kind = 'notification'
AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL
AND due.next_attempt_at <= $1::timestamptz AND due.provider = 'resend' AND due.provider_account = $2
AND (due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp())
ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED`,
fixture.clock.Now(), fixture.account.Account())
if err != nil {
t.Fatalf("explain the product claim: %v", err)
}
defer rows.Close()
var plan strings.Builder
for rows.Next() {
var line string
if err := rows.Scan(&line); err != nil {
t.Fatalf("scan the plan: %v", err)
}
plan.WriteString(line + "\n")
}
if !strings.Contains(plan.String(), "deliveries_product_due_idx") || strings.Contains(plan.String(), "Seq Scan") {
t.Fatalf("the product claim does not use deliveries_product_due_idx over the service backlog:\n%s", plan.String())
}
}