using FluentAssertions; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using SlpModularCms.Core.Email; using SlpModularCms.Core.Identity.Entities; using SlpModularCms.Core.Identity.Models; using SlpModularCms.Core.SiteSettings; namespace SlpModularCms.Core.Tests.Email; internal sealed class CapturingSender : IEmailSender { public List Sent { get; } = []; public MailSendResult Result { get; set; } = MailSendResult.Ok; public bool Throw { get; set; } public Task SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default) { if (Throw) throw new InvalidOperationException("boom with secret@example.org"); Sent.Add(mail); return Task.FromResult(Result); } } public class IdentityMailServiceTests { private readonly CapturingSender _sender = new(); private readonly ISiteSettingsService _settings = Substitute.For(); public IdentityMailServiceTests() => _settings.GetEffectiveSenderAsync(Arg.Any()).Returns(("info@andreaslop.nl", "Andrea Slop Fotografie")); private IdentityMailService Service(string smtpHost = "mail.example.nl", string defaultLanguage = "nl", int hours = 24, string logo = "/admin/brand-logo-on-light.png") => new(_sender, new MailTemplateRenderer(SlpModularCms.Core.Texts.TextCatalog.CreateDefault()), new LanguageResolver(Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" })), _settings, Options.Create(new EmailOptions { LogoUrl = logo, BrandColor = "#5f6a58", Smtp = { Host = smtpHost } }), Options.Create(new AppMailOptions { DefaultLanguage = defaultLanguage, PublicBaseUrl = "https://test.andreaslop.nl/" }), Options.Create(new InvitationSettings { ExpiryHours = hours }), Options.Create(new SlpModularCms.Core.Identity.Services.PasswordResetSettings()), new FixedAvailability(!string.IsNullOrWhiteSpace(smtpHost)), NullLogger.Instance); [Fact] public async Task Invitation_HasTheAdminLink_TheSiteSender_TheLogo_AndTheLifetime() { var result = await Service().SendInvitationAsync("new@example.org", "tok/en+1=", "nl", isNewLink: false); result.Sent.Should().BeTrue(); var mail = _sender.Sent.Should().ContainSingle().Subject; mail.ToAddress.Should().Be("new@example.org"); mail.FromAddress.Should().Be("info@andreaslop.nl"); mail.FromName.Should().Be("Andrea Slop Fotografie"); mail.Subject.Should().Be("Uitnodiging voor Andrea Slop Fotografie"); mail.HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/invite/complete?token=tok%2Fen%2B1%3D") .And.Contain("https://test.andreaslop.nl/admin/brand-logo-on-light.png") .And.Contain("24 uur").And.Contain("#5f6a58"); mail.TextBody.Should().Contain("https://test.andreaslop.nl/admin/invite/complete?token=tok%2Fen%2B1%3D"); } [Fact] public async Task ANewLink_UsesTheNewLinkText_AndTheConfiguredLifetime() { await Service(hours: 48).SendInvitationAsync("new@example.org", "t", "nl", isNewLink: true); var mail = _sender.Sent.Single(); mail.Subject.Should().StartWith("Nieuwe uitnodigingslink"); mail.HtmlBody.Should().Contain("48 uur"); } [Theory] [InlineData("en", "nl", "Invitation to")] [InlineData(null, "en", "Invitation to")] [InlineData(null, "nl", "Uitnodiging voor")] [InlineData("nl", "en", "Uitnodiging voor")] [InlineData("xx", "en", "Invitation to")] public async Task TheLanguage_IsTheChosenOne_ElseTheSiteDefault(string? chosen, string siteDefault, string subjectStart) { await Service(defaultLanguage: siteDefault).SendInvitationAsync("new@example.org", "t", chosen, false); _sender.Sent.Single().Subject.Should().StartWith(subjectStart); } [Fact] public async Task WithoutAHost_NothingIsSent_AndItReportsDisabled() { var result = await Service(smtpHost: "").SendInvitationAsync("new@example.org", "t", null, false); result.Should().Be(MailSendResult.Fail(MailSendResult.Disabled)); _sender.Sent.Should().BeEmpty(); Service(smtpHost: "").IsEnabled.Should().BeFalse(); } [Fact] public async Task ASenderFailure_IsPassedOnAsAValue() { _sender.Result = MailSendResult.Fail(MailSendResult.Timeout); (await Service().SendInvitationAsync("new@example.org", "t", null, false)).Should().Be(MailSendResult.Fail(MailSendResult.Timeout)); } [Fact] public async Task AnExceptionAnywhere_NeverEscapes() { _sender.Throw = true; var result = await Service().SendInvitationAsync("new@example.org", "t", null, false); result.Should().Be(MailSendResult.Fail(MailSendResult.Unknown)); } [Fact] public async Task ARecipientWithoutAnAddress_IsRefused() { var result = await Service().SendAccountDeactivatedAsync(new ApplicationUser { Email = null }); result.Should().Be(MailSendResult.Fail(MailSendResult.Rejected)); _sender.Sent.Should().BeEmpty(); } [Fact] public async Task Deactivation_IsAddressedToTheUser_InTheirLanguage_WithoutALink() { var user = new ApplicationUser { Email = "user@example.org", DisplayName = "Jan", PreferredLanguage = "en" }; await Service().SendAccountDeactivatedAsync(user); var mail = _sender.Sent.Single(); mail.Subject.Should().Contain("deactivated"); mail.TextBody.Should().Contain("Hello Jan,").And.NotContain("https://"); } [Fact] public async Task Reactivation_LinksToTheLoginPage() { await Service().SendAccountReactivatedAsync(new ApplicationUser { Email = "user@example.org", DisplayName = "Jan" }); _sender.Sent.Single().HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/login"); } [Fact] public async Task RoleChange_NamesTheNewRole_InTheUsersLanguage() { await Service().SendRoleChangedAsync(new ApplicationUser { Email = "user@example.org", PreferredLanguage = "nl" }, "Administrator"); await Service().SendRoleChangedAsync(new ApplicationUser { Email = "user@example.org", PreferredLanguage = "en" }, "Administrator"); _sender.Sent[0].TextBody.Should().Contain("Beheerder"); _sender.Sent[1].TextBody.Should().Contain("Administrator"); } [Fact] public async Task AnAbsoluteLogoUrl_IsUsedAsIs_AndNoLogoMeansTheSiteName() { await Service(logo: "https://cdn.example.org/logo.png").SendInvitationAsync("a@example.org", "t", null, false); await Service(logo: "").SendInvitationAsync("a@example.org", "t", null, false); _sender.Sent[0].HtmlBody.Should().Contain("https://cdn.example.org/logo.png"); _sender.Sent[1].HtmlBody.Should().NotContain(" IdentityMailService.BuildLink(baseUrl, path).Should().Be(expected); [Fact] public async Task PasswordReset_LinksToTheResetPage_WithTheUserIdNotTheAddress_AndTheLifetime() { var user = new ApplicationUser { Id = Guid.Parse("11111111-2222-3333-4444-555555555555"), Email = "jan@example.org", DisplayName = "Jan", PreferredLanguage = "en" }; await Service().SendPasswordResetAsync(user, "to/ken+1="); var mail = _sender.Sent.Single(); mail.Subject.Should().StartWith("Reset your password"); mail.HtmlBody.Should().Contain("https://test.andreaslop.nl/admin/reset-password?uid=11111111-2222-3333-4444-555555555555&token=to%2Fken%2B1%3D"); mail.TextBody.Should().Contain("https://test.andreaslop.nl/admin/reset-password?uid=11111111-2222-3333-4444-555555555555&token=to%2Fken%2B1%3D") .And.Contain("1 hour").And.Contain("unchanged"); // Nothing in the link identifies the account by its address. mail.TextBody!.Split("https://", 2)[1].Split('\n', 2)[0].Should().NotContain("jan@example.org").And.NotContain("%40"); } }