feat(mail): send service identity mail through a leased worker

This commit is contained in:
shira committed 2026-10-06 21:08:11 +03:00
1 parent 204c6bae62
commit d21fd49a42
58 files changed
+7577 -164

No files matched your search

+182 -27
View File
@@ -23,9 +23,9 @@ var (
ErrInvalidDelivery = errors.New("invalid delivery")
// ErrDeliveryTransition reports a change that the delivery's state does
// not allow: an attempt on an accepted or rejected delivery, a quota wait
// outside pending or waiting_quota, or a new provider account after the
// first attempt.
// not allow: an attempt on an accepted, rejected, or cancelled delivery,
// a quota wait or a cancellation outside pending or waiting_quota, or a
// new provider account after the first attempt.
ErrDeliveryTransition = errors.New("delivery status does not allow the transition")
// Provider names follow config.EmailProvider values; the account is an
@@ -47,14 +47,19 @@ var (
// Transitions:
//
// pending, waiting_quota, unknown --RecordAttempt--> accepted | rejected | pending | waiting_quota | unknown
// accepted, rejected --RecordAttempt--> refused (ErrDeliveryTransition)
// accepted, rejected, cancelled --RecordAttempt--> refused (ErrDeliveryTransition)
// pending, waiting_quota --WaitForQuota---> waiting_quota (no attempt is recorded)
// pending, waiting_quota --Cancel---------> cancelled (no attempt is recorded)
//
// The attempt outcome decides the target: accepted gives accepted; a
// permanent or invalid_request rejection gives rejected; a temporary or
// rate_limited rejection gives pending again with a scheduled next attempt; a
// quota_exhausted rejection gives waiting_quota until the expected reset, or
// without a time when the reset is unknown; unknown gives unknown.
//
// Only accepted means that a provider took the message, and even then it is
// not delivery to a person: no status claims that the mail reached an inbox
// or was read.
type DeliveryStatus string
const (
@@ -62,7 +67,8 @@ const (
// NextAttemptAt.
DeliveryStatusPending DeliveryStatus = "pending"
// DeliveryStatusAccepted means the provider accepted the message and
// returned its ID. It is not delivery to or reading by the recipient.
// returned its ID: "accepted by the provider". It is not delivery to or
// reading by the recipient.
DeliveryStatusAccepted DeliveryStatus = "accepted"
// DeliveryStatusRejected means the provider refused the message for good;
// the cause must be fixed before mail of this kind can succeed.
@@ -77,12 +83,17 @@ const (
// time the reset is unknown (for example a monthly provider quota) and an
// operator or the quota rule decides.
DeliveryStatusWaitingQuota DeliveryStatus = "waiting_quota"
// DeliveryStatusCancelled means the message was deliberately not sent
// and never will be: no attempt of it is recorded, and the reason says
// why (see DeliveryCancelReason). It is terminal and is not an attempt.
DeliveryStatusCancelled DeliveryStatus = "cancelled"
)
// ParseDeliveryStatus accepts a known status.
func ParseDeliveryStatus(value string) (DeliveryStatus, error) {
switch status := DeliveryStatus(value); status {
case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, DeliveryStatusWaitingQuota:
case DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown,
DeliveryStatusWaitingQuota, DeliveryStatusCancelled:
return status, nil
default:
return "", invalidDelivery("domain.ParseDeliveryStatus", "unknown delivery status")
@@ -91,7 +102,7 @@ func ParseDeliveryStatus(value string) (DeliveryStatus, error) {
// IsTerminal reports a status that accepts no further attempt.
func (status DeliveryStatus) IsTerminal() bool {
return status == DeliveryStatusAccepted || status == DeliveryStatusRejected
return status == DeliveryStatusAccepted || status == DeliveryStatusRejected || status == DeliveryStatusCancelled
}
// requiresNextAttempt reports a status that the sending worker picks up again
@@ -122,6 +133,69 @@ const (
DeliveryRejectionTemporary DeliveryRejection = "temporary"
)
// DeliveryCancelReason says why a delivery was cancelled: the message was
// deliberately not sent, and no attempt of it is recorded. The values are stored and must stay
// stable; each names the first failed check of the service mail rules (see
// Delivery.CheckServiceMail) or an invalid stored message.
type DeliveryCancelReason string
const (
// DeliveryCancelTokenMissing: the delivery is bound to no token, or the
// token row does not exist.
DeliveryCancelTokenMissing DeliveryCancelReason = "token_missing"
// DeliveryCancelTokenPurposeMismatch: the token authorizes another
// purpose than the kind of the mail.
DeliveryCancelTokenPurposeMismatch DeliveryCancelReason = "token_purpose_mismatch"
// DeliveryCancelTokenOwnerMismatch: the token belongs to another account
// than the recipient.
DeliveryCancelTokenOwnerMismatch DeliveryCancelReason = "token_owner_mismatch"
// DeliveryCancelTokenConsumed: the token was already used.
DeliveryCancelTokenConsumed DeliveryCancelReason = "token_consumed"
// DeliveryCancelTokenRevoked: a resend, a re-registration, or another
// revocation replaced the token.
DeliveryCancelTokenRevoked DeliveryCancelReason = "token_revoked"
// DeliveryCancelTokenExpired: the token passed its lifetime.
DeliveryCancelTokenExpired DeliveryCancelReason = "token_expired"
// DeliveryCancelAccountNotCurrent: the account moved on since the token
// was issued: it was registered again, or its state no longer calls for
// the mail (for example the address is verified already).
DeliveryCancelAccountNotCurrent DeliveryCancelReason = "account_not_current"
// DeliveryCancelRecipientMismatch: the address stored with the delivery is
// no longer the address of the account.
DeliveryCancelRecipientMismatch DeliveryCancelReason = "recipient_mismatch"
// DeliveryCancelContentInvalid: the stored message is one that no
// transport accepts, so retrying cannot help.
DeliveryCancelContentInvalid DeliveryCancelReason = "content_invalid"
// DeliveryCancelProcessingFailed: the sending worker failed on this row
// again and again for a reason of its own, so it stopped trying and left
// the row to an operator.
DeliveryCancelProcessingFailed DeliveryCancelReason = "processing_failed"
)
// DeliveryCancelReasons lists every cancel reason, for metrics that expose
// their series at zero.
func DeliveryCancelReasons() []DeliveryCancelReason {
return []DeliveryCancelReason{
DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
DeliveryCancelProcessingFailed,
}
}
// ParseDeliveryCancelReason accepts a known reason.
func ParseDeliveryCancelReason(value string) (DeliveryCancelReason, error) {
switch reason := DeliveryCancelReason(value); reason {
case DeliveryCancelTokenMissing, DeliveryCancelTokenPurposeMismatch, DeliveryCancelTokenOwnerMismatch,
DeliveryCancelTokenConsumed, DeliveryCancelTokenRevoked, DeliveryCancelTokenExpired,
DeliveryCancelAccountNotCurrent, DeliveryCancelRecipientMismatch, DeliveryCancelContentInvalid,
DeliveryCancelProcessingFailed:
return reason, nil
default:
return "", invalidDelivery("domain.ParseDeliveryCancelReason", "unknown cancel reason")
}
}
// MailProviderAccount names the transport and the provider account that a
// delivery is pinned to, for example resend and "main". It is configuration
// identity, never a credential. A delivery keeps it for its whole life: a
@@ -172,6 +246,8 @@ type Delivery struct {
nextAttemptAt time.Time
lastAttemptAt time.Time
providerMessageID string
emailTokenID uuid.UUID
cancelReason DeliveryCancelReason
version int64
createdAt time.Time
updatedAt time.Time
@@ -189,7 +265,13 @@ type NewDeliveryInput struct {
Recipient EmailAddress
Content MailContent
ProviderAccount MailProviderAccount
CreatedAt time.Time
// EmailTokenID is the token whose link the content carries. Set it for a
// kind that CarriesBearerToken, so the sending worker can check the token
// before it sends; a delivery of such a kind without it is cancelled by
// the worker with the reason token_missing. It must be uuid.Nil for a
// notification.
EmailTokenID uuid.UUID
CreatedAt time.Time
}
// NewDelivery validates input and returns a pending delivery that is due at
@@ -209,6 +291,8 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
return Delivery{}, invalidDelivery(location, "provider account must be set")
case input.CreatedAt.IsZero():
return Delivery{}, invalidDelivery(location, "creation time must be set")
case input.EmailTokenID != uuid.Nil && !input.Content.Kind().CarriesBearerToken():
return Delivery{}, invalidDelivery(location, "only a delivery of a token kind is bound to a token")
}
return Delivery{
id: input.ID,
@@ -217,6 +301,7 @@ func NewDelivery(input NewDeliveryInput) (Delivery, error) {
recipient: input.Recipient,
content: input.Content,
providerAccount: input.ProviderAccount,
emailTokenID: input.EmailTokenID,
idempotencyKey: deliveryIdempotencyKeyPrefix + input.ID.String(),
status: DeliveryStatusPending,
nextAttemptAt: input.CreatedAt,
@@ -240,9 +325,13 @@ type DeliverySnapshot struct {
NextAttemptAt time.Time
LastAttemptAt time.Time
ProviderMessageID string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
// EmailTokenID is uuid.Nil for a delivery without a token binding.
EmailTokenID uuid.UUID
// CancelReason is set exactly for a cancelled delivery.
CancelReason DeliveryCancelReason
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// RestoreDelivery rebuilds a stored delivery and checks the invariants that
@@ -258,21 +347,11 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
if _, err := ParseDeliveryStatus(string(snapshot.Status)); err != nil {
return Delivery{}, fmt.Errorf("%s - restore status: %w", location, err)
}
switch {
case snapshot.ID == uuid.Nil || snapshot.RecipientUserID == uuid.Nil:
return Delivery{}, invalidDelivery(location, "delivery and recipient user IDs must not be nil")
case snapshot.Content.IsZero() || snapshot.ProviderAccount.IsZero():
return Delivery{}, invalidDelivery(location, "content and provider account must be set")
case !idempotencyKeyPattern.MatchString(snapshot.IdempotencyKey):
return Delivery{}, invalidDelivery(location, "idempotency key must have 1 to 256 printable ASCII characters")
case snapshot.Version <= 0 || snapshot.AttemptCount < 0:
return Delivery{}, invalidDelivery(location, "version must be positive and the attempt count not negative")
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return Delivery{}, invalidDelivery(location, "update time must not precede the creation time")
case (snapshot.AttemptCount == 0) != snapshot.LastAttemptAt.IsZero():
return Delivery{}, invalidDelivery(location, "last attempt time must be set exactly when an attempt was made")
case (snapshot.Status == DeliveryStatusAccepted) != (snapshot.ProviderMessageID != ""):
return Delivery{}, invalidDelivery(location, "provider message ID must be set exactly for an accepted delivery")
if err := checkStoredFields(location, snapshot); err != nil {
return Delivery{}, err
}
if err := checkCancellationAndBinding(location, snapshot); err != nil {
return Delivery{}, err
}
if err := checkNextAttempt(location, snapshot.Status, snapshot.NextAttemptAt); err != nil {
return Delivery{}, err
@@ -290,12 +369,54 @@ func RestoreDelivery(snapshot DeliverySnapshot) (Delivery, error) {
nextAttemptAt: snapshot.NextAttemptAt,
lastAttemptAt: snapshot.LastAttemptAt,
providerMessageID: snapshot.ProviderMessageID,
emailTokenID: snapshot.EmailTokenID,
cancelReason: snapshot.CancelReason,
version: snapshot.Version,
createdAt: snapshot.CreatedAt,
updatedAt: snapshot.UpdatedAt,
}, nil
}
// checkStoredFields checks the invariants of a stored row that do not
// depend on its cancellation or token binding.
func checkStoredFields(location string, snapshot DeliverySnapshot) error {
switch {
case snapshot.ID == uuid.Nil || snapshot.RecipientUserID == uuid.Nil:
return invalidDelivery(location, "delivery and recipient user IDs must not be nil")
case snapshot.Content.IsZero() || snapshot.ProviderAccount.IsZero():
return invalidDelivery(location, "content and provider account must be set")
case !idempotencyKeyPattern.MatchString(snapshot.IdempotencyKey):
return invalidDelivery(location, "idempotency key must have 1 to 256 printable ASCII characters")
case snapshot.Version <= 0 || snapshot.AttemptCount < 0:
return invalidDelivery(location, "version must be positive and the attempt count not negative")
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
return invalidDelivery(location, "update time must not precede the creation time")
case (snapshot.AttemptCount == 0) != snapshot.LastAttemptAt.IsZero():
return invalidDelivery(location, "last attempt time must be set exactly when an attempt was made")
case (snapshot.Status == DeliveryStatusAccepted) != (snapshot.ProviderMessageID != ""):
return invalidDelivery(location, "provider message ID must be set exactly for an accepted delivery")
}
return nil
}
// checkCancellationAndBinding checks the cancel reason and the token binding
// of a stored row. A token kind may lack its binding (rows older than the
// binding), and the sending worker cancels it; a notification never has one.
func checkCancellationAndBinding(location string, snapshot DeliverySnapshot) error {
switch {
case (snapshot.Status == DeliveryStatusCancelled) != (snapshot.CancelReason != ""):
return invalidDelivery(location, "cancel reason must be set exactly for a cancelled delivery")
case snapshot.EmailTokenID != uuid.Nil && !snapshot.Content.Kind().CarriesBearerToken():
return invalidDelivery(location, "only a delivery of a token kind is bound to a token")
}
if snapshot.CancelReason != "" {
if _, err := ParseDeliveryCancelReason(string(snapshot.CancelReason)); err != nil {
return fmt.Errorf("%s - restore cancel reason: %w", location, err)
}
}
return nil
}
func checkNextAttempt(location string, status DeliveryStatus, nextAttemptAt time.Time) error {
switch {
case status.IsTerminal() && !nextAttemptAt.IsZero():
@@ -343,7 +464,14 @@ func (delivery Delivery) LastAttemptAt() time.Time { return delivery.lastAttempt
// ProviderMessageID is set once the provider accepted the message.
func (delivery Delivery) ProviderMessageID() string { return delivery.providerMessageID }
// Version is the optimistic concurrency version, advanced by every attempt.
// EmailTokenID is the token the content's link carries, or uuid.Nil.
func (delivery Delivery) EmailTokenID() uuid.UUID { return delivery.emailTokenID }
// CancelReason says why a cancelled delivery was not sent; empty for any
// other status.
func (delivery Delivery) CancelReason() DeliveryCancelReason { return delivery.cancelReason }
// Version is the optimistic concurrency version, advanced by every change.
func (delivery Delivery) Version() int64 { return delivery.version }
func (delivery Delivery) CreatedAt() time.Time { return delivery.createdAt }
@@ -462,6 +590,33 @@ func (delivery Delivery) WaitForQuota(at, until time.Time) (Delivery, error) {
return next, nil
}
// Cancel ends a pending or waiting_quota delivery without an attempt: the
// message must not be sent, for the given reason. at is the decision time.
// It returns the next state with the next version and no next attempt; no
// attempt record is written, because the message is not sent. An unknown
// delivery is refused like in WaitForQuota: an earlier attempt may have been
// accepted, so it must not be reported as not sent. The terminal statuses are
// refused as well.
func (delivery Delivery) Cancel(at time.Time, reason DeliveryCancelReason) (Delivery, error) {
const location = "Delivery.Cancel"
if err := delivery.checkChangeTime(location, at); err != nil {
return Delivery{}, err
}
if _, err := ParseDeliveryCancelReason(string(reason)); err != nil {
return Delivery{}, fmt.Errorf("%s - %w", location, err)
}
if delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota {
return Delivery{}, fmt.Errorf("%s - delivery is %s: %w", location, delivery.status, ErrDeliveryTransition)
}
next := delivery
next.status = DeliveryStatusCancelled
next.cancelReason = reason
next.nextAttemptAt = time.Time{}
next.version = delivery.version + 1
next.updatedAt = at
return next, nil
}
// Rebind pins a delivery that has no attempt yet to another provider
// account, for example after the stand moved from EMAIL_PROVIDER=disabled to
// a real transport. Once an attempt was made, a provider may hold the
+80
View File
@@ -0,0 +1,80 @@
package domain
import (
"time"
"github.com/google/uuid"
)
// ServiceMailState is what the sending worker reads right before it sends a
// service mail that carries a one-time token: the token the delivery is
// bound to and the account it is addressed to, as one consistent snapshot.
// A zero time means "not set".
//
// It holds no raw token and no address in a loggable form: the account
// address is only the comparison key, used to compare it with the address
// stored in the delivery.
type ServiceMailState struct {
// TokenFound is false when the delivery has no token binding or the
// token row does not exist.
TokenFound bool
TokenPurpose EmailTokenPurpose
TokenUserID uuid.UUID
TokenRegistrationVersion int64
TokenConsumedAt time.Time
TokenInvalidatedAt time.Time
TokenExpiresAt time.Time
AccountRegistrationVersion int64
AccountEmailVerified bool
// AccountEmailKey is the normalized address of the account now.
AccountEmailKey string
}
// CheckServiceMail decides whether a verification or password reset mail may
// still be sent at the given time, and returns the reason when it may not.
// An empty reason means that the mail is sendable. The checks run in this
// order and the first failure decides:
//
// 1. a token is bound to the delivery and exists;
// 2. its purpose is the one the mail kind carries, and it belongs to the
// recipient account;
// 3. it is not consumed, revoked, or expired;
// 4. the account is current: it still has the registration the token was
// issued for, and a verification mail is not sent to an address that is
// verified already;
// 5. the address stored in the delivery is still the address of the
// account.
//
// Publishing consent (C2) and every other product consent play no part: a
// service mail is part of the account flow, not a product notification.
// A kind without a bearer token is refused with token_missing, because the
// sending worker never claims it.
//
// The check is a snapshot: a token consumed or revoked after it, before the
// provider call, still lets the mail go. That is harmless, because the link
// is checked again when it is used.
func (delivery Delivery) CheckServiceMail(state ServiceMailState, at time.Time) DeliveryCancelReason {
purpose, carriesToken := delivery.Kind().TokenPurpose()
switch {
case !carriesToken || !state.TokenFound:
return DeliveryCancelTokenMissing
case state.TokenPurpose != purpose:
return DeliveryCancelTokenPurposeMismatch
case state.TokenUserID != delivery.recipientUserID:
return DeliveryCancelTokenOwnerMismatch
case !state.TokenConsumedAt.IsZero():
return DeliveryCancelTokenConsumed
case !state.TokenInvalidatedAt.IsZero():
return DeliveryCancelTokenRevoked
case !at.Before(state.TokenExpiresAt):
return DeliveryCancelTokenExpired
case state.TokenRegistrationVersion != state.AccountRegistrationVersion:
return DeliveryCancelAccountNotCurrent
case delivery.Kind() == MailKindVerification && state.AccountEmailVerified:
return DeliveryCancelAccountNotCurrent
case state.AccountEmailKey != delivery.recipient.Normalized():
return DeliveryCancelRecipientMismatch
default:
return ""
}
}
@@ -0,0 +1,337 @@
package domain
import (
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
var testTokenID = uuid.MustParse("01926f3a-7c00-7000-8000-0000000000a1")
// newTokenDelivery is a verification delivery bound to testTokenID.
func newTokenDelivery(t *testing.T, kind MailKind) Delivery {
t.Helper()
version := string(kind) + ".v1"
content, err := NewMailContent(kind, version, testDeliverySubject, testDeliveryText, testDeliveryHTML)
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
input.EmailTokenID = testTokenID
delivery, err := NewDelivery(input)
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
return delivery
}
// currentState is the state in which a verification mail may be sent: the
// token is the delivery's, unused, unexpired, issued for the registration the
// account still has, and the address is unchanged and not yet verified.
func currentState(delivery Delivery, purpose EmailTokenPurpose) ServiceMailState {
return ServiceMailState{
TokenFound: true,
TokenPurpose: purpose,
TokenUserID: delivery.RecipientUserID(),
TokenRegistrationVersion: 3,
TokenExpiresAt: testDeliveryCreated.Add(24 * time.Hour),
AccountRegistrationVersion: 3,
AccountEmailKey: delivery.Recipient().Normalized(),
}
}
func TestCheckServiceMailAllowsAMailWhoseTokenAndAccountAreCurrent(t *testing.T) {
for kind, purpose := range map[MailKind]EmailTokenPurpose{
MailKindVerification: EmailTokenPurposeEmailVerification,
MailKindPasswordReset: EmailTokenPurposePasswordReset,
} {
delivery := newTokenDelivery(t, kind)
if reason := delivery.CheckServiceMail(currentState(delivery, purpose), after(1)); reason != "" {
t.Fatalf("CheckServiceMail(%s) = %q for a current mail, want it sendable", kind, reason)
}
}
}
func TestCheckServiceMailNamesTheFirstFailedRule(t *testing.T) {
verification := newTokenDelivery(t, MailKindVerification)
reset := newTokenDelivery(t, MailKindPasswordReset)
revokedAt := after(5)
tests := []struct {
name string
delivery Delivery
purpose EmailTokenPurpose
change func(*ServiceMailState)
at time.Time
want DeliveryCancelReason
}{
{"token row missing", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenFound = false }, after(1), DeliveryCancelTokenMissing},
{"reset token for a verification mail", verification, EmailTokenPurposePasswordReset, func(*ServiceMailState) {}, after(1), DeliveryCancelTokenPurposeMismatch},
{"verification token for a reset mail", reset, EmailTokenPurposeEmailVerification, func(*ServiceMailState) {}, after(1), DeliveryCancelTokenPurposeMismatch},
{"token of another account", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenUserID = uuid.New() }, after(1), DeliveryCancelTokenOwnerMismatch},
{"token consumed", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenConsumedAt = after(2) }, after(3), DeliveryCancelTokenConsumed},
{"token revoked", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.TokenInvalidatedAt = revokedAt }, after(6), DeliveryCancelTokenRevoked},
{"token expired at its deadline", verification, EmailTokenPurposeEmailVerification, func(*ServiceMailState) {}, testDeliveryCreated.Add(24 * time.Hour), DeliveryCancelTokenExpired},
{"account registered again", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.AccountRegistrationVersion = 4 }, after(1), DeliveryCancelAccountNotCurrent},
{"address already verified", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.AccountEmailVerified = true }, after(1), DeliveryCancelAccountNotCurrent},
{"address of the account changed", verification, EmailTokenPurposeEmailVerification, func(state *ServiceMailState) { state.AccountEmailKey = "other@example.com" }, after(1), DeliveryCancelRecipientMismatch},
{"reset mail to a changed address", reset, EmailTokenPurposePasswordReset, func(state *ServiceMailState) { state.AccountEmailKey = "other@example.com" }, after(1), DeliveryCancelRecipientMismatch},
// A reset goes to a verified account, so verification state does not
// apply to it.
{"reset mail to a verified account stays sendable", reset, EmailTokenPurposePasswordReset, func(state *ServiceMailState) { state.AccountEmailVerified = true }, after(1), ""},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
state := currentState(test.delivery, test.purpose)
test.change(&state)
if got := test.delivery.CheckServiceMail(state, test.at); got != test.want {
t.Fatalf("CheckServiceMail() = %q, want %q", got, test.want)
}
})
}
}
func TestCheckServiceMailRefusesADeliveryWithoutATokenBinding(t *testing.T) {
// A verification mail stored without a token binding reads no token row
// from the database, so it cannot be checked.
unbound := newTestDelivery(t)
if got := unbound.CheckServiceMail(ServiceMailState{}, after(1)); got != DeliveryCancelTokenMissing {
t.Fatalf("CheckServiceMail(unbound verification) = %q, want token_missing", got)
}
// A notification is not service mail: the worker never claims it, and the
// check refuses it even when a token row is offered.
content, err := NewMailContent(MailKindNotification, "notification.v1", "s", "t\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
plain, err := NewDelivery(input)
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
if got := plain.CheckServiceMail(ServiceMailState{TokenFound: true}, after(1)); got != DeliveryCancelTokenMissing {
t.Fatalf("CheckServiceMail(notification) = %q, want token_missing", got)
}
}
func TestNewDeliveryBindsOnlyTokenKindsToATokenAndKeepsItWhenRestored(t *testing.T) {
bound := newTokenDelivery(t, MailKindVerification)
if bound.EmailTokenID() != testTokenID {
t.Fatal("the delivery lost its token binding")
}
restored, err := RestoreDelivery(deliverySnapshot(bound))
if err != nil || restored.EmailTokenID() != testTokenID {
t.Fatalf("RestoreDelivery() = %v, %v; want the binding kept", restored.EmailTokenID(), err)
}
content, err := NewMailContent(MailKindNotification, "notification.v1", "s", "t\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
input.EmailTokenID = testTokenID
if _, err := NewDelivery(input); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("NewDelivery(notification with a token) error = %v, want ErrInvalidDelivery", err)
}
}
func TestCancelEndsAPendingOrWaitingDeliveryWithoutAnAttempt(t *testing.T) {
pending := newTokenDelivery(t, MailKindVerification)
waiting, err := pending.WaitForQuota(after(1), after(60))
if err != nil {
t.Fatalf("WaitForQuota() error = %v", err)
}
for name, delivery := range map[string]Delivery{"pending": pending, "waiting_quota": waiting} {
t.Run(name, func(t *testing.T) {
cancelled, err := delivery.Cancel(after(30), DeliveryCancelTokenRevoked)
if err != nil {
t.Fatalf("Cancel() error = %v", err)
}
switch {
case cancelled.Status() != DeliveryStatusCancelled || cancelled.CancelReason() != DeliveryCancelTokenRevoked:
t.Fatalf("status = %s, reason = %q", cancelled.Status(), cancelled.CancelReason())
case !cancelled.NextAttemptAt().IsZero() || cancelled.AttemptCount() != delivery.AttemptCount() || !cancelled.LastAttemptAt().IsZero():
t.Fatal("a cancellation scheduled or recorded an attempt")
case cancelled.Version() != delivery.Version()+1 || !cancelled.UpdatedAt().Equal(after(30)):
t.Fatal("a cancellation did not advance the version and the update time")
case cancelled.IdempotencyKey() != delivery.IdempotencyKey() || cancelled.Content().Hash() != delivery.Content().Hash():
t.Fatal("a cancellation changed the key or the content")
case !cancelled.Status().IsTerminal():
t.Fatal("cancelled is not terminal")
}
if delivery.Status() == DeliveryStatusCancelled {
t.Fatal("Cancel() changed its receiver")
}
// The terminal status accepts nothing else.
if _, _, err := cancelled.RecordAttempt(DeliveryAttemptInput{At: after(31), Outcome: DeliveryOutcomeUnknown}); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("RecordAttempt() on a cancelled delivery error = %v, want ErrDeliveryTransition", err)
}
if _, err := cancelled.WaitForQuota(after(31), time.Time{}); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("WaitForQuota() on a cancelled delivery error = %v, want ErrDeliveryTransition", err)
}
if _, err := cancelled.Cancel(after(31), DeliveryCancelTokenExpired); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("Cancel() on a cancelled delivery error = %v, want ErrDeliveryTransition", err)
}
restored, err := RestoreDelivery(deliverySnapshot(cancelled))
if err != nil || restored.Status() != DeliveryStatusCancelled || restored.CancelReason() != DeliveryCancelTokenRevoked {
t.Fatalf("RestoreDelivery() = %s, %v; want the cancelled state back", restored.Status(), err)
}
})
}
}
func TestCancelRefusesWhatItCannotHonestlyReportAsNotSent(t *testing.T) {
unknown := mustRecord(t, newTokenDelivery(t, MailKindVerification), DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeUnknown})
if _, err := unknown.Cancel(after(2), DeliveryCancelTokenRevoked); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("Cancel() on an unknown delivery error = %v, want ErrDeliveryTransition: an earlier attempt may have been accepted", err)
}
accepted := mustRecord(t, newTokenDelivery(t, MailKindVerification), DeliveryAttemptInput{At: after(1), Outcome: DeliveryOutcomeAccepted, ProviderMessageID: testMessageID})
if _, err := accepted.Cancel(after(2), DeliveryCancelTokenRevoked); !errors.Is(err, ErrDeliveryTransition) {
t.Fatalf("Cancel() on an accepted delivery error = %v, want ErrDeliveryTransition", err)
}
pending := newTokenDelivery(t, MailKindVerification)
if _, err := pending.Cancel(after(1), "because"); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("Cancel() with an unknown reason error = %v, want ErrInvalidDelivery", err)
}
if _, err := pending.Cancel(testDeliveryCreated.Add(-time.Minute), DeliveryCancelTokenRevoked); !errors.Is(err, ErrInvalidDelivery) {
t.Fatalf("Cancel() before the last change error = %v, want ErrInvalidDelivery", err)
}
}
func TestRestoreDeliveryChecksTheCancelReasonAndTheBinding(t *testing.T) {
cancelled, err := newTokenDelivery(t, MailKindVerification).Cancel(after(1), DeliveryCancelTokenExpired)
if err != nil {
t.Fatalf("Cancel() error = %v", err)
}
tests := map[string]func(*DeliverySnapshot){
"cancelled without a reason": func(snapshot *DeliverySnapshot) { snapshot.CancelReason = "" },
"unknown reason": func(snapshot *DeliverySnapshot) { snapshot.CancelReason = "because" },
"reason on a pending delivery": func(snapshot *DeliverySnapshot) {
snapshot.Status, snapshot.NextAttemptAt = DeliveryStatusPending, after(5)
},
"cancelled with a next attempt": func(snapshot *DeliverySnapshot) { snapshot.NextAttemptAt = after(5) },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
snapshot := deliverySnapshot(cancelled)
change(&snapshot)
if _, err := RestoreDelivery(snapshot); err == nil {
t.Fatal("RestoreDelivery() accepted a broken row")
}
})
}
// A notification row with a token binding is not a state the schema allows.
content, err := NewMailContent(MailKindNotification, "notification.v1", "s", "t\n", "")
if err != nil {
t.Fatalf("NewMailContent() error = %v", err)
}
input := testDeliveryInput(t)
input.Content = content
plain, err := NewDelivery(input)
if err != nil {
t.Fatalf("NewDelivery() error = %v", err)
}
snapshot := deliverySnapshot(plain)
snapshot.EmailTokenID = testTokenID
if _, err := RestoreDelivery(snapshot); err == nil {
t.Fatal("RestoreDelivery() accepted a notification bound to a token")
}
}
func TestDeliveryStatusAcceptedIsNamedForTheProviderNotThePerson(t *testing.T) {
// The only status that reports success says what happened: the provider
// accepted the message. No status claims delivery to an inbox.
for _, status := range []DeliveryStatus{DeliveryStatusPending, DeliveryStatusAccepted, DeliveryStatusRejected, DeliveryStatusUnknown, DeliveryStatusWaitingQuota, DeliveryStatusCancelled} {
if _, err := ParseDeliveryStatus(string(status)); err != nil {
t.Fatalf("ParseDeliveryStatus(%s) error = %v", status, err)
}
if strings.Contains(string(status), "deliver") || strings.Contains(string(status), "sent") {
t.Fatalf("status %q names delivery to a person", status)
}
}
if _, err := ParseDeliveryStatus("delivered"); err == nil {
t.Fatal("ParseDeliveryStatus() accepted delivered")
}
}
func TestMailKindTokenPurposeMatchesTheKindsThatCarryAToken(t *testing.T) {
for _, kind := range []MailKind{MailKindVerification, MailKindPasswordReset, MailKindNotification} {
purpose, carries := kind.TokenPurpose()
if carries != kind.CarriesBearerToken() || (carries && purpose == "") {
t.Fatalf("TokenPurpose(%s) = %q, %t, want it to follow CarriesBearerToken", kind, purpose, carries)
}
if carries {
if _, err := ParseEmailTokenPurpose(string(purpose)); err != nil {
t.Fatalf("ParseEmailTokenPurpose(%s) error = %v", purpose, err)
}
}
}
}
func TestRestoreRedactedMailContentKeepsOnlyTheSubjectAndTheHash(t *testing.T) {
content := testMailContent(t)
hash := content.Hash()
redacted, err := RestoreRedactedMailContent(MailKindVerification, "verification.v1", testDeliverySubject, hash[:])
if err != nil {
t.Fatalf("RestoreRedactedMailContent() error = %v", err)
}
if !redacted.Redacted() || redacted.Text() != "" || redacted.HTML() != "" || redacted.Hash() != hash || redacted.IsZero() {
t.Fatal("redacted content keeps a body, or lost its hash")
}
if got := redacted.String(); strings.Contains(got, testDeliverySubject) {
t.Fatalf("String() = %q shows the subject", got)
}
for name, call := range map[string]func() error{
"a notification": func() error {
_, err := RestoreRedactedMailContent(MailKindNotification, "notification.v1", "s", hash[:])
return err
},
"another version": func() error {
_, err := RestoreRedactedMailContent(MailKindVerification, "password_reset.v1", "s", hash[:])
return err
},
"a short hash": func() error {
_, err := RestoreRedactedMailContent(MailKindVerification, "verification.v1", "s", hash[:4])
return err
},
} {
if err := call(); !errors.Is(err, ErrInvalidMailContent) {
t.Fatalf("%s: error = %v, want ErrInvalidMailContent", name, err)
}
}
// A redacted terminal delivery restores.
cancelled, err := newTokenDelivery(t, MailKindVerification).Cancel(after(1), DeliveryCancelProcessingFailed)
if err != nil {
t.Fatalf("Cancel() error = %v", err)
}
snapshot := deliverySnapshot(cancelled)
snapshot.Content = redacted
if restored, err := RestoreDelivery(snapshot); err != nil || !restored.Content().Redacted() {
t.Fatalf("RestoreDelivery() = %v, %v; want a redacted delivery", restored.Content().Redacted(), err)
}
}
func TestServiceMailKindsAreTheKindsThatCarryATokenAndEveryCancelReasonParses(t *testing.T) {
kinds := ServiceMailKinds()
if len(kinds) != 2 {
t.Fatalf("ServiceMailKinds() = %v, want verification and password_reset", kinds)
}
for _, kind := range kinds {
if !kind.IsServiceMail() || !kind.CarriesBearerToken() {
t.Fatalf("%s is listed as service mail but carries no token", kind)
}
}
if MailKindNotification.IsServiceMail() {
t.Fatal("a notification is service mail")
}
for _, reason := range DeliveryCancelReasons() {
if _, err := ParseDeliveryCancelReason(string(reason)); err != nil {
t.Fatalf("ParseDeliveryCancelReason(%s) error = %v", reason, err)
}
}
}
+2
View File
@@ -331,6 +331,8 @@ func deliverySnapshot(delivery Delivery) DeliverySnapshot {
NextAttemptAt: delivery.NextAttemptAt(),
LastAttemptAt: delivery.LastAttemptAt(),
ProviderMessageID: delivery.ProviderMessageID(),
EmailTokenID: delivery.EmailTokenID(),
CancelReason: delivery.CancelReason(),
Version: delivery.Version(),
CreatedAt: delivery.CreatedAt(),
UpdatedAt: delivery.UpdatedAt(),
+13 -8
View File
@@ -10,21 +10,26 @@ import (
var ErrInvalidEmailToken = errors.New("invalid email token")
// EmailTokenPurpose names what an email token authorizes. New purposes, such
// as a planned password reset, are added here and in the email_tokens CHECK
// constraint together.
// EmailTokenPurpose names what an email token authorizes. New purposes are
// added here and in the email_tokens CHECK constraint together.
type EmailTokenPurpose string
// EmailTokenPurposeEmailVerification authorizes confirming the account email.
const EmailTokenPurposeEmailVerification EmailTokenPurpose = "email_verification" //nolint:gosec // A purpose name, not a credential.
const (
// EmailTokenPurposeEmailVerification authorizes confirming the account
// email.
EmailTokenPurposeEmailVerification EmailTokenPurpose = "email_verification" //nolint:gosec // A purpose name, not a credential.
// EmailTokenPurposePasswordReset authorizes setting a new password.
EmailTokenPurposePasswordReset EmailTokenPurpose = "password_reset"
)
// ParseEmailTokenPurpose accepts a known purpose.
func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) {
purpose := EmailTokenPurpose(value)
if purpose != EmailTokenPurposeEmailVerification {
switch purpose := EmailTokenPurpose(value); purpose {
case EmailTokenPurposeEmailVerification, EmailTokenPurposePasswordReset:
return purpose, nil
default:
return "", fmt.Errorf("domain.ParseEmailTokenPurpose - unknown purpose: %w", ErrInvalidEmailToken)
}
return purpose, nil
}
// EmailToken is the stored record of a one-time token sent by email. It holds
+1 -1
View File
@@ -48,7 +48,7 @@ func TestNewEmailTokenRejectsInvalidInput(t *testing.T) {
}
tests := map[string]func(*NewEmailTokenInput){
"nil user": func(input *NewEmailTokenInput) { input.UserID = uuid.Nil },
"unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "password_reset" },
"unknown purpose": func(input *NewEmailTokenInput) { input.Purpose = "something_else" },
"zero hash": func(input *NewEmailTokenInput) { input.TokenHash = SecretTokenHash{} },
"zero version": func(input *NewEmailTokenInput) { input.RegistrationVersion = 0 },
"zero issue time": func(input *NewEmailTokenInput) { input.IssuedAt = time.Time{} },
+54
View File
@@ -57,12 +57,39 @@ func ParseMailKind(value string) (MailKind, error) {
}
}
// ServiceMailKinds lists the kinds of service identity mail, the kinds the
// sending worker claims and sends. Notifications are not among them until
// their sending is connected (TASK-462). The delivery metrics of due mail,
// the sending worker, and the due index of the deliveries table follow this
// list; changing it changes the predicate of deliveries_due_idx too.
func ServiceMailKinds() []MailKind {
return []MailKind{MailKindVerification, MailKindPasswordReset}
}
// IsServiceMail reports a kind of service identity mail.
func (kind MailKind) IsServiceMail() bool { return kind.CarriesBearerToken() }
// CarriesBearerToken reports kinds whose body holds a one-time bearer token
// in a link. Their stored bodies are secrets until the token expires.
func (kind MailKind) CarriesBearerToken() bool {
return kind == MailKindVerification || kind == MailKindPasswordReset
}
// TokenPurpose returns the email token purpose that the link of a mail of
// this kind carries, and false for a kind without a bearer token.
func (kind MailKind) TokenPurpose() (EmailTokenPurpose, bool) {
switch kind {
case MailKindVerification:
return EmailTokenPurposeEmailVerification, true
case MailKindPasswordReset:
return EmailTokenPurposePasswordReset, true
case MailKindNotification:
return "", false
default:
return "", false
}
}
// MailContentHash is SHA-256 over the template version, subject, text part,
// and HTML part, each encoded as a netstring ("<len>:<part>,"), so moving
// bytes from one part to the next changes the digest. The mail templates and
@@ -98,6 +125,9 @@ type mailContentValue struct {
text string
html string
hash [MailContentHashSize]byte
// redacted is set for the content of a terminal token mail whose bodies
// were cleared; only the subject and the hash remain.
redacted bool
}
// NewMailContent validates a rendering and computes its hash. The template
@@ -134,6 +164,30 @@ func RestoreMailContent(kind MailKind, templateVersion, subject, text, html stri
return content, nil
}
// RestoreRedactedMailContent rebuilds the content of a token mail whose bodies
// were cleared after it reached a terminal status. Nothing can be checked
// against the hash any more, so the stored hash is kept as it is; the content
// has no bodies and can never be sent.
func RestoreRedactedMailContent(kind MailKind, templateVersion, subject string, hash []byte) (MailContent, error) {
const location = "domain.RestoreRedactedMailContent"
if _, err := ParseMailKind(string(kind)); err != nil || !kind.CarriesBearerToken() {
return MailContent{}, invalidMailContent("only a token mail has redacted content")
}
if !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v") ||
strings.TrimSpace(subject) == "" || utf8.RuneCountInString(subject) > maxMailSubjectRunes {
return MailContent{}, fmt.Errorf("%s - stored version or subject is invalid: %w", location, ErrInvalidMailContent)
}
if len(hash) != MailContentHashSize {
return MailContent{}, fmt.Errorf("%s - stored hash has the wrong size: %w", location, ErrInvalidMailContent)
}
value := &mailContentValue{kind: kind, templateVersion: templateVersion, subject: subject, redacted: true}
copy(value.hash[:], hash)
return MailContent{value: value}, nil
}
// Redacted reports content whose bodies were cleared after the mail ended.
func (content MailContent) Redacted() bool { return content.read().redacted }
func validateMailContent(kind MailKind, templateVersion, subject, text, html string) error {
switch {
case !mailTemplateVersionPattern.MatchString(templateVersion) || !strings.HasPrefix(templateVersion, string(kind)+".v"):