From 892c317fdec7084dc505619fd1b02e00f2ab80cb Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Fri, 27 Nov 2026 22:27:37 -0800 Subject: [PATCH 1/2] feat(aspire): catch Identity email locally with MailPit The standalone AppHost adds a MailPit container (CommunityToolkit 17.0.0, persistent volume unless EphemeralDatabases) and references it from Web. In Development, Web sends Identity email through a MailKit SmtpEmailSender when it receives ConnectionStrings:mailpit; without it, Identity's no-op sender still applies. Any other environment fails startup if the setting is present and keeps using Mailjet unchanged. MailKit's SMTP span source and SMTP/socket meters are exported; the meters are created only when the MailPit sender is registered. Smoke tests register a user and reset a password end to end, reading each message from MailPit's API. They share JourneyFixture (fake hCaptcha) and run in their own parallel group: Web's anonymous per-IP rate limit is shared by every 127.0.0.1 client, and overlapping the browser journeys starved them. --- Directory.Packages.props | 2 + .../EmailSenderStartupTests.cs | 88 ++++++ .../SmtpEndpointTests.cs | 37 +++ .../EssentialCSharp.Web.csproj | 1 + .../Extensions/TelemetryExtensions.cs | 7 +- EssentialCSharp.Web/Program.cs | 35 ++- .../Services/SmtpEmailSender.cs | 90 +++++++ README.md | 10 +- .../AppHostGraphTests.cs | 5 +- .../IdentityEmailSmokeTests.cs | 251 ++++++++++++++++++ .../Journeys/JourneyFixture.cs | 3 +- dev/EssentialCSharp.Web.AppHost/AppHost.cs | 7 + .../EssentialCSharp.Web.AppHost.csproj | 1 + 13 files changed, 529 insertions(+), 8 deletions(-) create mode 100644 EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs create mode 100644 EssentialCSharp.Web.Tests/SmtpEndpointTests.cs create mode 100644 EssentialCSharp.Web/Services/SmtpEmailSender.cs create mode 100644 dev/EssentialCSharp.Web.AppHost.Tests/IdentityEmailSmokeTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index e333fe9d..a0eb5a63 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -21,6 +21,7 @@ + @@ -38,6 +39,7 @@ + diff --git a/EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs b/EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs new file mode 100644 index 00000000..9f82ffe7 --- /dev/null +++ b/EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs @@ -0,0 +1,88 @@ +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Identity.UI.Services; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; + +namespace EssentialCSharp.Web.Tests; + +/// Startup selection and the non-Development guard for the local-only MailPit sender. +public class EmailSenderStartupTests : IntegrationTestBase +{ + private const string MailPitKey = "ConnectionStrings:mailpit"; + private const string MailPitConnectionString = "Endpoint=smtp://localhost:1025"; + + [Test] + public async Task Development_WithMailPit_SendsThroughSmtp() + { + await using var factory = Factory.Inner.WithWebHostBuilder(builder => + builder.UseSetting(MailPitKey, MailPitConnectionString)); + + Type senderType = InScope(factory, services => services.GetRequiredService().GetType()); + + await Assert.That(senderType).IsEqualTo(typeof(SmtpEmailSender)); + } + + [Test] + public async Task Development_WithoutMailPit_KeepsIdentityDefaultSender() + { + // The shared factory runs in Development with no mailpit connection string. + Type senderType = InScope(Factory.Inner, services => services.GetRequiredService().GetType()); + + await Assert.That(senderType).IsNotEqualTo(typeof(SmtpEmailSender)); + await Assert.That(senderType).IsNotEqualTo(typeof(EmailSender)); + } + + [Test] + public async Task NonDevelopment_WithMailPit_FailsStartup() + { + await using var factory = Factory.Inner.WithWebHostBuilder(builder => + { + builder.UseEnvironment("Production"); + // Production loads no appsettings.Development.json, so satisfy the earlier required settings (neither is + // contacted at startup; the factory swaps in SQLite). Startup then reaches the guard under test instead + // of failing for an unrelated reason, which the message check below would also catch. + builder.UseSetting("ConnectionStrings:EssentialCSharpWebContextConnection", "Server=unused;Database=unused"); + builder.UseSetting("DataProtection:AzureKeyVaultKeyUri", "https://example.vault.azure.net/keys/test"); + builder.UseSetting(MailPitKey, MailPitConnectionString); + }); + + Exception? failure = null; + try + { + _ = factory.Services; + } + catch (Exception ex) + { + failure = ex; + } + + InvalidOperationException? guard = Flatten(failure) + .OfType() + .FirstOrDefault(ex => ex.Message.Contains(MailPitKey, StringComparison.Ordinal)); + await Assert.That(guard).IsNotNull() + .Because($"startup should reject {MailPitKey} outside Development; got: {failure?.ToString() ?? "no exception"}"); + } + + private static T InScope(WebApplicationFactory factory, Func action) + { + using IServiceScope scope = factory.Services.CreateScope(); + return action(scope.ServiceProvider); + } + + private static IEnumerable Flatten(Exception? exception) + { + for (; exception is not null; exception = exception.InnerException) + { + if (exception is AggregateException aggregate) + { + foreach (Exception inner in aggregate.InnerExceptions.SelectMany(Flatten)) + { + yield return inner; + } + } + + yield return exception; + } + } +} diff --git a/EssentialCSharp.Web.Tests/SmtpEndpointTests.cs b/EssentialCSharp.Web.Tests/SmtpEndpointTests.cs new file mode 100644 index 00000000..5500866e --- /dev/null +++ b/EssentialCSharp.Web.Tests/SmtpEndpointTests.cs @@ -0,0 +1,37 @@ +using EssentialCSharp.Web.Services; + +namespace EssentialCSharp.Web.Tests; + +public class SmtpEndpointTests +{ + [Test] + [Arguments("Endpoint=smtp://mailpit:1025", "mailpit", 1025)] + [Arguments("endpoint=SMTP://localhost:2525", "localhost", 2525)] + public async Task TryParse_SmtpEndpointWithPort_ReturnsHostAndPort(string connectionString, string host, int port) + { + bool parsed = SmtpEndpoint.TryParse(connectionString, out SmtpEndpoint? endpoint); + + await Assert.That(parsed).IsTrue(); + await Assert.That(endpoint).IsEqualTo(new SmtpEndpoint(host, port)); + } + + [Test] + [Arguments(null)] + [Arguments("")] + [Arguments(" ")] + [Arguments("Endpoint=http://mailpit:1025")] + [Arguments("Endpoint=smtp://mailpit")] + [Arguments("Endpoint=smtp://mailpit:99999")] + [Arguments("Endpoint=smtp://mailpit:notaport")] + [Arguments("Endpoint=")] + [Arguments("Host=mailpit;Port=1025")] + [Arguments("garbage")] + [Arguments("Endpoint=not a uri")] + public async Task TryParse_NotAnSmtpEndpointWithPort_ReturnsFalse(string? connectionString) + { + bool parsed = SmtpEndpoint.TryParse(connectionString, out SmtpEndpoint? endpoint); + + await Assert.That(parsed).IsFalse(); + await Assert.That(endpoint).IsNull(); + } +} diff --git a/EssentialCSharp.Web/EssentialCSharp.Web.csproj b/EssentialCSharp.Web/EssentialCSharp.Web.csproj index afb742e7..72c807f2 100644 --- a/EssentialCSharp.Web/EssentialCSharp.Web.csproj +++ b/EssentialCSharp.Web/EssentialCSharp.Web.csproj @@ -44,6 +44,7 @@ + diff --git a/EssentialCSharp.Web/Extensions/TelemetryExtensions.cs b/EssentialCSharp.Web/Extensions/TelemetryExtensions.cs index 17bc6483..63eee5ca 100644 --- a/EssentialCSharp.Web/Extensions/TelemetryExtensions.cs +++ b/EssentialCSharp.Web/Extensions/TelemetryExtensions.cs @@ -48,8 +48,11 @@ internal static bool ConfigureApplicationTelemetry(this IHostApplicationBuilder }); var otel = builder.Services.AddOpenTelemetry() - .WithMetrics(metrics => metrics.AddRuntimeInstrumentation()) - .WithTracing(tracing => tracing.AddSource(builder.Environment.ApplicationName)); + // MailKit meters only emit after Telemetry.*.Configure (Development MailPit SMTP sender only; see Program). + .WithMetrics(metrics => metrics.AddRuntimeInstrumentation() + .AddMeter(MailKit.Telemetry.SmtpClient.MeterName, MailKit.Telemetry.Socket.MeterName)) + .WithTracing(tracing => tracing.AddSource(builder.Environment.ApplicationName) + .AddSource(MailKit.Telemetry.SmtpClient.ActivitySourceName)); if (useAzureMonitor) { diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index 267233b1..1fab331b 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -174,7 +174,30 @@ private static void Main(string[] args) options.Filters.Add(new Microsoft.AspNetCore.Mvc.AutoValidateAntiforgeryTokenAttribute()); }); - builder.Services.AddMailjetEmailSender(builder.Configuration.GetSection(AuthMessageSenderOptions.AuthMessageSender), builder.Environment); + // In Development, a MailPit reference from the Aspire AppHost routes Identity email to that local SMTP + // catcher; without one, Identity's no-op sender applies. Every other environment uses Mailjet, unchanged. + IConfigurationSection authMessageSenderSection = builder.Configuration.GetSection(AuthMessageSenderOptions.AuthMessageSender); + string? mailPitConnectionString = builder.Configuration.GetConnectionString(SmtpEndpoint.ConnectionStringName); + SmtpEndpoint? smtpEndpoint = null; + if (builder.Environment.IsDevelopment()) + { + if (SmtpEndpoint.TryParse(mailPitConnectionString, out smtpEndpoint)) + { + // Unvalidated: no Mailjet keys are needed locally; only the optional From address is read. + builder.Services.Configure(authMessageSenderSection); + builder.Services.AddSingleton(smtpEndpoint); + builder.Services.AddTransient(); + } + } + else if (!string.IsNullOrWhiteSpace(mailPitConnectionString)) + { + // Fail closed: a stray setting must not divert real email to a plaintext local catcher. + throw new InvalidOperationException( + $"ConnectionStrings:{SmtpEndpoint.ConnectionStringName} is for local development only and must not be " + + "set in non-Development environments, which send email through Mailjet."); + } + + builder.Services.AddMailjetEmailSender(authMessageSenderSection, builder.Environment); builder.Services.Configure(builder.Configuration.GetSection(SiteSettings.SectionName)); builder.Services.Configure(builder.Configuration.GetSection(ContentRateLimitOptions.SectionName)); @@ -344,6 +367,16 @@ await context.HttpContext.Response.WriteAsync( WebApplication app = builder.Build(); + if (smtpEndpoint is not null) + { + // MailKit's SMTP span source always exists; its meters (experimental) must be created explicitly. + // Attributes are server, port, peer IP, operation and error type only; no addresses or content. + // Parameterless on purpose: MailKit caches the meter in a static (??=), so a meter from this host's + // IMeterFactory would be disposed with the host and reused by any later host in the same process. + MailKit.Telemetry.SmtpClient.Configure(); + MailKit.Telemetry.Socket.Configure(); + } + if (profilerSkippedUnsupportedPlatform) LogSkippingUnsupportedAzureMonitorProfiler( app.Services.GetRequiredService>(), diff --git a/EssentialCSharp.Web/Services/SmtpEmailSender.cs b/EssentialCSharp.Web/Services/SmtpEmailSender.cs new file mode 100644 index 00000000..5f1f4ccd --- /dev/null +++ b/EssentialCSharp.Web/Services/SmtpEmailSender.cs @@ -0,0 +1,90 @@ +using System.Data.Common; +using MailKit.Net.Smtp; +using MailKit.Security; +using Microsoft.AspNetCore.Identity.UI.Services; +using Microsoft.Extensions.Options; +using MimeKit; + +namespace EssentialCSharp.Web.Services; + +/// The plain-SMTP server that delivers to. +/// The SMTP host name. +/// The SMTP port. +public sealed record SmtpEndpoint(string Host, int Port) +{ + /// The connection string name that Aspire's MailPit resource exposes to referencing projects. + public const string ConnectionStringName = "mailpit"; + + /// Parses an Aspire connection string such as Endpoint=smtp://localhost:1025. + /// when the connection string names an smtp:// endpoint. + public static bool TryParse(string? connectionString, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SmtpEndpoint? endpoint) + { + endpoint = null; + if (string.IsNullOrWhiteSpace(connectionString)) + { + return false; + } + + DbConnectionStringBuilder builder = new(); + try + { + builder.ConnectionString = connectionString; + } + catch (ArgumentException) + { + // Not key=value syntax at all. + return false; + } + + if (!builder.TryGetValue("Endpoint", out object? value) + || !Uri.TryCreate(value?.ToString(), UriKind.Absolute, out Uri? uri) + || !string.Equals(uri.Scheme, "smtp", StringComparison.OrdinalIgnoreCase) + || uri.Port <= 0) + { + return false; + } + + endpoint = new SmtpEndpoint(uri.Host, uri.Port); + return true; + } +} + +/// +/// Sends Identity email over unencrypted SMTP with MailKit. Intended for a local mail catcher such as MailPit, +/// which accepts plain SMTP without TLS or authentication by default. +/// +public sealed partial class SmtpEmailSender( + SmtpEndpoint endpoint, + IOptions options, + ILogger logger) : IEmailSender +{ + private const string DefaultFromEmail = "no-reply@essentialcsharp.localhost"; + private const string DefaultFromName = "Essential C#"; + + private readonly ILogger _Logger = logger; + + private AuthMessageSenderOptions Options { get; } = options.Value; + + public async Task SendEmailAsync(string email, string subject, string htmlMessage) + { + using MimeMessage message = new(); + message.From.Add(new MailboxAddress( + string.IsNullOrWhiteSpace(Options.SendFromName) ? DefaultFromName : Options.SendFromName, + string.IsNullOrWhiteSpace(Options.SendFromEmail) ? DefaultFromEmail : Options.SendFromEmail)); + message.To.Add(new MailboxAddress(string.Empty, email)); + message.Subject = subject; + message.Body = new BodyBuilder { HtmlBody = htmlMessage }.ToMessageBody(); + + // Follows MailKit's README send sequence: connect, send, DisconnectAsync(true), one client per message. + // No AuthenticateAsync: MailPit accepts unauthenticated mail. None, not StartTlsWhenAvailable, because + // MailPit offers no STARTTLS by default and this states that the connection is plaintext. + using SmtpClient client = new(); + await client.ConnectAsync(endpoint.Host, endpoint.Port, SecureSocketOptions.None); + await client.SendAsync(message); + await client.DisconnectAsync(quit: true); + LogEmailSent(_Logger, endpoint.Host, endpoint.Port); + } + + [LoggerMessage(Level = LogLevel.Information, Message = "Email sent to SMTP server {Host}:{Port}.")] + private static partial void LogEmailSent(ILogger logger, string host, int port); +} diff --git a/README.md b/README.md index 63cb9b87..adcc69f4 100644 --- a/README.md +++ b/README.md @@ -28,12 +28,17 @@ aspire describe --apphost dev\EssentialCSharp.Web.AppHost\EssentialCSharp.Web.Ap Use the allocated Web HTTP endpoint reported by Aspire, not a hard-coded localhost port. `--isolated` keeps worktree container identities separate. SQL Server, pgvector PostgreSQL, -and optional Ollama use persistent data volumes; restart with the same command to retain data. +MailPit, and optional Ollama use persistent data volumes; restart with the same command to retain data. The AppHost has its own `UserSecretsId`, separate from ordinary Web application secrets. SQL Server passwords are generated by Aspire unless an AppHost `Parameters:sqlserver-password` secret is supplied. Stop only this AppHost using `aspire stop --apphost` with the same project path. Add `--format mermaid` to `aspire describe` to print the resource dependency graph as a Mermaid diagram. +Identity email (account confirmation, password reset) goes to a local [MailPit](https://mailpit.axllent.org/) +container; open its `http` endpoint from the Aspire dashboard to read the messages. Web uses this SMTP +sender only in Development when it receives the `mailpit` connection string, and fails startup if that +setting appears in any other environment, which keep sending through Mailjet. + The Web resource uses Aspire's Project v2 model (`AddDotnetProject`), which the AppHost builds before launch. Aspire watch [is not yet implemented for Project v2 resources](https://aspire.dev/integrations/dotnet/migrate-dotnet-project-resource/#check-workflows-before-migrating); after changing Web code, rebuild just that resource with `aspire resource essentialcsharp-web rebuild --apphost `. @@ -85,7 +90,8 @@ Graph tests do not start containers. The shared `TUnit.Aspire` smoke fixture pas `--EssentialCSharpWeb:EphemeralDatabases=true` for fresh, session-lifetime databases without data volumes, disables AI/feed, and checks that migrations finished before Web became healthy, then `/health`, `/alive`, and placeholder HTML. It also starts a second AppHost and verifies both Web -instances remain healthy on distinct URLs. Smoke tests are skipped when no Linux container engine is +instances remain healthy on distinct URLs. Email smoke tests register a user and reset a password, +reading each message from MailPit's API and following its link. Smoke tests are skipped when no Linux container engine is reachable (for example hosted macOS runners or Windows runners with only Windows containers), except in Linux CI where they always run. Graph tests also generate a local manifest to verify that publish mode contains no migration tools, browser helpers, local AI, or Development environment override. diff --git a/dev/EssentialCSharp.Web.AppHost.Tests/AppHostGraphTests.cs b/dev/EssentialCSharp.Web.AppHost.Tests/AppHostGraphTests.cs index 0f767211..9fdedf5d 100644 --- a/dev/EssentialCSharp.Web.AppHost.Tests/AppHostGraphTests.cs +++ b/dev/EssentialCSharp.Web.AppHost.Tests/AppHostGraphTests.cs @@ -24,7 +24,7 @@ public async Task StandaloneGraph_Default_UsesPersistentLocalInfrastructureAndPr await Assert.That(names).Contains(expected); } - foreach (var container in builder.Resources.OfType().Where(r => r.Name is "sqlserver" or "postgres")) + foreach (var container in builder.Resources.OfType().Where(r => r.Name is "sqlserver" or "postgres" or "mailpit")) { await Assert.That(container.Annotations.OfType().Any()).IsTrue(); await Assert.That(container.Annotations.OfType().Single().Lifetime) @@ -41,6 +41,7 @@ await Assert.That(container.Annotations.OfType().Si await Assert.That(names).DoesNotContain("UseNugetContentFeed"); await Assert.That(names).DoesNotContain("UseLocalAI"); await Assert.That(env["AIOptions__UseLocalAI"]).IsEqualTo("false"); + await Assert.That(((ConnectionStringReference)env["ConnectionStrings__mailpit"]).Resource.Name).IsEqualTo("mailpit"); } [Test] @@ -49,7 +50,7 @@ public async Task StandaloneGraph_EphemeralDatabases_RemovesVolumesAndPersistenc await using var builder = await DistributedApplicationTestingBuilder.CreateAsync( ["--AIOptions:UseLocalAI=false", "--EssentialCSharpWeb:EphemeralDatabases=true"]); - foreach (var container in builder.Resources.OfType().Where(r => r.Name is "sqlserver" or "postgres")) + foreach (var container in builder.Resources.OfType().Where(r => r.Name is "sqlserver" or "postgres" or "mailpit")) { await Assert.That(container.Annotations.OfType().Any()).IsFalse(); await Assert.That(container.Annotations.OfType() diff --git a/dev/EssentialCSharp.Web.AppHost.Tests/IdentityEmailSmokeTests.cs b/dev/EssentialCSharp.Web.AppHost.Tests/IdentityEmailSmokeTests.cs new file mode 100644 index 00000000..68d8be03 --- /dev/null +++ b/dev/EssentialCSharp.Web.AppHost.Tests/IdentityEmailSmokeTests.cs @@ -0,0 +1,251 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; +using Aspire.Hosting.Testing; + +namespace EssentialCSharp.Web.AppHost.Tests; + +/// +/// Drives Identity's email flows end to end: Web sends through MailKit to the AppHost's MailPit container, and the +/// test reads each message back from MailPit's REST API and follows the link it contains. +/// +/// +/// The shared points Web's hCaptcha verification at an in-process fake that accepts +/// any token, so like the other smoke tests these need no outbound network. +/// +/// Web limits anonymous requests per IP, and every test client is 127.0.0.1. These tests make many anonymous form +/// requests, so they run in their own parallel group (after the browser journeys, which they would otherwise starve) +/// and wait out any 429 that the journeys' traffic in the same window leaves behind. +/// +/// +[Category("Docker")] +[RequiresLinuxContainers] +[ParallelGroup(nameof(IdentityEmailSmokeTests))] +[ClassDataSource(Shared = SharedType.PerTestSession)] +public partial class IdentityEmailSmokeTests(Journeys.JourneyFixture fixture) +{ + private const string CaptchaToken = "smoke-test-token"; + private static readonly TimeSpan MailTimeout = TimeSpan.FromSeconds(60); + + [Test] + public async Task Register_ConfirmationEmail_LinkEnablesSignIn() + { + using var web = CreateWebClient(); + using var mailpit = fixture.CreateHttpClient("mailpit", "http"); + string email = NewEmail(); + string password = NewPassword(); + + await RegisterAsync(web, email, password); + bool signedInBeforeConfirming = await CanSignInAsync(email, password); + string confirmLink = await GetLinkFromEmailAsync(mailpit, email, "Confirm your email"); + using (var confirmResponse = await web.GetAsync(new Uri(confirmLink))) + { + confirmResponse.EnsureSuccessStatusCode(); + } + + // RequireConfirmedEmail: the account is unusable until the emailed link is followed. + await Assert.That(signedInBeforeConfirming).IsFalse(); + await Assert.That(await CanSignInAsync(email, password)).IsTrue(); + } + + [Test] + public async Task ForgotPassword_ResetEmail_LinkReplacesPassword() + { + using var web = CreateWebClient(); + using var mailpit = fixture.CreateHttpClient("mailpit", "http"); + string email = NewEmail(); + string oldPassword = NewPassword(); + await RegisterAsync(web, email, oldPassword); + string confirmLink = await GetLinkFromEmailAsync(mailpit, email, "Confirm your email"); + using (var confirmResponse = await web.GetAsync(new Uri(confirmLink))) + { + confirmResponse.EnsureSuccessStatusCode(); + } + + using (var forgotResponse = await PostFormAsync(web, "/Identity/Account/ForgotPassword", new() + { + ["Input.Email"] = email, + })) + { + // Checked before polling: a rejected form redisplays (200) and sends no email, and waiting would hide why. + await Assert.That(forgotResponse.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + } + + string resetLink = await GetLinkFromEmailAsync(mailpit, email, "Reset Password"); + string newPassword = NewPassword(); + using var resetPage = await web.GetAsync(new Uri(resetLink)); + resetPage.EnsureSuccessStatusCode(); + string resetHtml = await resetPage.Content.ReadAsStringAsync(); + Match code = ResetCodeInput().Match(resetHtml); + if (!code.Success) + { + throw new InvalidOperationException( + $"No Input.Code field found on the reset page ({(int)resetPage.StatusCode}) at {resetLink}."); + } + + using var resetResponse = await PostFormAsync(web, resetLink, new() + { + ["Input.Code"] = WebUtility.HtmlDecode(code.Groups[1].Value), + ["Input.Email"] = email, + ["Input.Password"] = newPassword, + ["Input.ConfirmPassword"] = newPassword, + }, resetHtml); + + await Assert.That(await CanSignInAsync(email, newPassword)).IsTrue(); + await Assert.That(await CanSignInAsync(email, oldPassword)).IsFalse(); + } + + private HttpClient CreateWebClient() + { + // Own handler: the antiforgery cookie must round-trip, and redirects are asserted rather than followed. + var handler = new HttpClientHandler { CookieContainer = new CookieContainer(), AllowAutoRedirect = false }; + return new HttpClient(new RetryAfterRateLimitHandler { InnerHandler = handler }) { BaseAddress = fixture.WebUrl }; + } + + /// Retries a 429 once its Retry-After elapses; Web's anonymous limit is a fixed one-minute window. + private sealed class RetryAfterRateLimitHandler : DelegatingHandler + { + private static readonly TimeSpan MaxWait = TimeSpan.FromSeconds(65); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + for (int attempt = 0; ; attempt++) + { + HttpResponseMessage response = await base.SendAsync(request, cancellationToken); + if (response.StatusCode != HttpStatusCode.TooManyRequests || attempt == 2) + { + return response; + } + + TimeSpan wait = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(10); + response.Dispose(); + await Task.Delay(wait < MaxWait ? wait : MaxWait, cancellationToken); + } + } + } + + /// + /// Signs in with a fresh cookie jar, then reports whether an [Authorize] page is reachable. That proves + /// the auth cookie works, independent of the login page's wording or redirect target. + /// + private async Task CanSignInAsync(string email, string password) + { + using var client = CreateWebClient(); + using var loginResponse = await PostFormAsync(client, "/Identity/Account/Login", new() + { + ["Input.Email"] = email, + ["Input.Password"] = password, + }); + + using var account = await client.GetAsync(new Uri("/Identity/Account/Manage", UriKind.Relative)); + return account.StatusCode == HttpStatusCode.OK; + } + + private static async Task RegisterAsync(HttpClient web, string email, string password) + { + using var response = await PostFormAsync(web, "/Identity/Account/Register", new() + { + ["Input.UserName"] = email.Split('@')[0], + ["Input.Email"] = email, + ["Input.FirstName"] = "Smoke", + ["Input.LastName"] = "Test", + ["Input.Password"] = password, + ["Input.ConfirmPassword"] = password, + }); + + // Success redirects; a rejected form redisplays with validation errors. + if (response.StatusCode != HttpStatusCode.Redirect) + { + string body = await response.Content.ReadAsStringAsync(); + throw new InvalidOperationException( + $"Registration was not accepted ({(int)response.StatusCode}). Validation: " + + string.Join(" | ", ValidationErrors().Matches(body).Select(m => WebUtility.HtmlDecode(m.Groups[1].Value.Trim())))); + } + } + + /// Loads the form page for its antiforgery token, then posts the fields with the captcha response. + private static async Task PostFormAsync( + HttpClient web, string path, Dictionary fields, string? formHtml = null) + { + if (formHtml is null) + { + using var page = await web.GetAsync(new Uri(path, UriKind.RelativeOrAbsolute)); + page.EnsureSuccessStatusCode(); + formHtml = await page.Content.ReadAsStringAsync(); + } + + Match token = AntiforgeryInput().Match(formHtml); + if (!token.Success) + { + throw new InvalidOperationException($"No antiforgery token found on {path}."); + } + + fields["__RequestVerificationToken"] = WebUtility.HtmlDecode(token.Groups[1].Value); + fields["h-captcha-response"] = CaptchaToken; + using var content = new FormUrlEncodedContent(fields); + return await web.PostAsync(new Uri(path, UriKind.RelativeOrAbsolute), content); + } + + /// Polls MailPit until a message to with the subject arrives, then returns its link. + private static async Task GetLinkFromEmailAsync(HttpClient mailpit, string email, string subject) + { + // Mailpit search syntax: https://mailpit.axllent.org/docs/usage/search-filters/ + string query = Uri.EscapeDataString($"to:\"{email}\" subject:\"{subject}\""); + using var timeout = new CancellationTokenSource(MailTimeout); + MailPitMessage? message = null; + try + { + while (message is null) + { + var search = await mailpit.GetFromJsonAsync($"/api/v1/search?query={query}", timeout.Token); + if (search?.Messages is [var newest, ..]) + { + message = await mailpit.GetFromJsonAsync( + $"/api/v1/message/{Uri.EscapeDataString(newest.Id)}", timeout.Token); + } + else + { + await Task.Delay(TimeSpan.FromMilliseconds(500), timeout.Token); + } + } + } + catch (OperationCanceledException ex) when (timeout.IsCancellationRequested) + { + throw new TimeoutException( + $"No email with subject '{subject}' to {email} arrived in MailPit within {MailTimeout.TotalSeconds:0}s.", ex); + } + + Match link = HrefAttribute().Match(message.Html ?? string.Empty); + if (!link.Success) + { + throw new InvalidOperationException($"Email '{subject}' to {email} contained no link: {message.Html}"); + } + + return WebUtility.HtmlDecode(link.Groups[1].Value); + } + + private static string NewEmail() => $"smoke-{Guid.NewGuid():N}@example.test"; + + // Random, so it never matches the common-password or breached-password validators. + private static string NewPassword() => $"Pw-{Guid.NewGuid():N}"; + + [GeneratedRegex("""]*name="__RequestVerificationToken"[^>]*value="([^"]+)""")] + private static partial Regex AntiforgeryInput(); + + [GeneratedRegex("""]*name="Input\.Code"[^>]*value="([^"]*)""")] + private static partial Regex ResetCodeInput(); + + [GeneratedRegex("""href=['"]([^'"]+)['"]""")] + private static partial Regex HrefAttribute(); + + [GeneratedRegex("""
  • ([^<]+)
  • """)] + private static partial Regex ValidationErrors(); + + private sealed record MailPitSearchResult( + [property: JsonPropertyName("messages")] IReadOnlyList Messages); + + private sealed record MailPitMessageSummary([property: JsonPropertyName("ID")] string Id); + + private sealed record MailPitMessage([property: JsonPropertyName("HTML")] string? Html); +} diff --git a/dev/EssentialCSharp.Web.AppHost.Tests/Journeys/JourneyFixture.cs b/dev/EssentialCSharp.Web.AppHost.Tests/Journeys/JourneyFixture.cs index c262f2a9..c01dde6e 100644 --- a/dev/EssentialCSharp.Web.AppHost.Tests/Journeys/JourneyFixture.cs +++ b/dev/EssentialCSharp.Web.AppHost.Tests/Journeys/JourneyFixture.cs @@ -56,7 +56,8 @@ protected override void ConfigureBuilder(IDistributedApplicationTestingBuilder b } /// - /// Creates a confirmed user directly; UI registration can't, because the confirmation link is only emailed. + /// Creates a confirmed user directly, skipping UI registration and the emailed confirmation link + /// ( covers that flow through MailPit). /// Use one user per test: chat rate limits are per user. /// public async Task CreateConfirmedUserAsync(string name) diff --git a/dev/EssentialCSharp.Web.AppHost/AppHost.cs b/dev/EssentialCSharp.Web.AppHost/AppHost.cs index 1e87145f..d11f4b6a 100644 --- a/dev/EssentialCSharp.Web.AppHost/AppHost.cs +++ b/dev/EssentialCSharp.Web.AppHost/AppHost.cs @@ -1,3 +1,4 @@ +using Aspire.Hosting.Utils; using EssentialCSharp.Web.Hosting; var builder = DistributedApplication.CreateBuilder(args); @@ -11,16 +12,22 @@ var sqlServer = builder.AddSqlServer("sqlserver"); var postgresServer = builder.AddPostgres("postgres") .WithImage("pgvector/pgvector", "pg17"); +// Catches Identity email (confirmation, password reset) locally; Web switches to SMTP when it sees this reference. +var mailpit = builder.AddMailPit("mailpit"); if (!ephemeralDatabases) { sqlServer.WithDataVolume().WithLifetime(ContainerLifetime.Persistent); postgresServer.WithDataVolume().WithLifetime(ContainerLifetime.Persistent); + // Unlike the database integrations, MailPit's WithDataVolume requires a name; generate the same style. + mailpit.WithDataVolume(VolumeNameGenerator.Generate(mailpit, "data")).WithLifetime(ContainerLifetime.Persistent); } var sql = sqlServer.AddDatabase("EssentialCSharpWebContextConnection"); var postgres = postgresServer.AddDatabase("PostgresVectorStore"); builder.AddEssentialCSharpWeb(webProjectPath, sql, postgres) + .WithReference(mailpit) + .WaitFor(mailpit) .WithEssentialCSharpLocalAI(); builder.Build().Run(); diff --git a/dev/EssentialCSharp.Web.AppHost/EssentialCSharp.Web.AppHost.csproj b/dev/EssentialCSharp.Web.AppHost/EssentialCSharp.Web.AppHost.csproj index 96979ac0..218acbeb 100644 --- a/dev/EssentialCSharp.Web.AppHost/EssentialCSharp.Web.AppHost.csproj +++ b/dev/EssentialCSharp.Web.AppHost/EssentialCSharp.Web.AppHost.csproj @@ -12,6 +12,7 @@ + Date: Sat, 28 Nov 2026 12:19:06 -0800 Subject: [PATCH 2/2] test: assert startup failure with TUnit Throws instead of a generic catch Addresses the CodeQL generic-catch-clause alert in EmailSenderStartupTests. --- EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs b/EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs index 9f82ffe7..8003fc60 100644 --- a/EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs +++ b/EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs @@ -47,15 +47,9 @@ public async Task NonDevelopment_WithMailPit_FailsStartup() builder.UseSetting(MailPitKey, MailPitConnectionString); }); - Exception? failure = null; - try - { - _ = factory.Services; - } - catch (Exception ex) - { - failure = ex; - } + // Startup wraps the guard's exception differently depending on where the host fails, so accept any + // exception here and look for the guard anywhere in the chain below. + Exception? failure = await Assert.That(() => factory.Services).Throws(); InvalidOperationException? guard = Flatten(failure) .OfType()