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) } } }