Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<PackageVersion Include="Aspire.Hosting.PostgreSQL" Version="17.0.0" />
<PackageVersion Include="Aspire.Hosting.Browsers" Version="17.0.0-preview.1.26567.5" />
<PackageVersion Include="Aspire.Hosting.EntityFrameworkCore" Version="17.0.0-preview.1.26567.5" />
<PackageVersion Include="CommunityToolkit.Aspire.Hosting.MailPit" Version="17.0.0" />
<PackageVersion Include="CommunityToolkit.Aspire.Hosting.Ollama" Version="17.0.0" />
<PackageVersion Include="TUnit.Aspire" Version="1.77.0" />
<PackageVersion Include="Azure.Extensions.AspNetCore.DataProtection.Keys" Version="1.6.5" />
Expand All @@ -38,6 +39,7 @@
<PackageVersion Include="HtmlAgilityPack" Version="1.13.1" />
<PackageVersion Include="IntelliTect.Multitool" Version="2.1.0" />
<PackageVersion Include="Mailjet.Api" Version="4.1.0" />
<PackageVersion Include="MailKit" Version="4.18.2" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="10.0.15" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.15" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.15" />
Expand Down
82 changes: 82 additions & 0 deletions EssentialCSharp.Web.Tests/EmailSenderStartupTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
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;

/// <summary>Startup selection and the non-Development guard for the local-only MailPit sender.</summary>
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<IEmailSender>().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<IEmailSender>().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);
});

// 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<Exception>();

InvalidOperationException? guard = Flatten(failure)
.OfType<InvalidOperationException>()
.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<T>(WebApplicationFactory<Program> factory, Func<IServiceProvider, T> action)
{
using IServiceScope scope = factory.Services.CreateScope();
return action(scope.ServiceProvider);
}

private static IEnumerable<Exception> 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;
}
}
}
37 changes: 37 additions & 0 deletions EssentialCSharp.Web.Tests/SmtpEndpointTests.cs
Original file line number Diff line number Diff line change
@@ -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();
}
}
1 change: 1 addition & 0 deletions EssentialCSharp.Web/EssentialCSharp.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
<PackageReference Include="HtmlAgilityPack" />
<PackageReference Include="IntelliTect.Multitool" />
<PackageReference Include="Mailjet.Api" />
<PackageReference Include="MailKit" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" />
Expand Down
7 changes: 5 additions & 2 deletions EssentialCSharp.Web/Extensions/TelemetryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
35 changes: 34 additions & 1 deletion EssentialCSharp.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AuthMessageSenderOptions>(authMessageSenderSection);
builder.Services.AddSingleton(smtpEndpoint);
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>();
}
}
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<SiteSettings>(builder.Configuration.GetSection(SiteSettings.SectionName));
builder.Services.Configure<ContentRateLimitOptions>(builder.Configuration.GetSection(ContentRateLimitOptions.SectionName));

Expand Down Expand Up @@ -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<ILogger<Program>>(),
Expand Down
90 changes: 90 additions & 0 deletions EssentialCSharp.Web/Services/SmtpEmailSender.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>The plain-SMTP server that <see cref="SmtpEmailSender"/> delivers to.</summary>
/// <param name="Host">The SMTP host name.</param>
/// <param name="Port">The SMTP port.</param>
public sealed record SmtpEndpoint(string Host, int Port)
{
/// <summary>The connection string name that Aspire's MailPit resource exposes to referencing projects.</summary>
public const string ConnectionStringName = "mailpit";

/// <summary>Parses an Aspire connection string such as <c>Endpoint=smtp://localhost:1025</c>.</summary>
/// <returns><see langword="true"/> when the connection string names an <c>smtp://</c> endpoint.</returns>
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;
}
}

/// <summary>
/// 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.
/// </summary>
public sealed partial class SmtpEmailSender(
SmtpEndpoint endpoint,
IOptions<AuthMessageSenderOptions> options,
ILogger<SmtpEmailSender> 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);
}
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <path>`.
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions dev/EssentialCSharp.Web.AppHost.Tests/AppHostGraphTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public async Task StandaloneGraph_Default_UsesPersistentLocalInfrastructureAndPr
await Assert.That(names).Contains(expected);
}

foreach (var container in builder.Resources.OfType<ContainerResource>().Where(r => r.Name is "sqlserver" or "postgres"))
foreach (var container in builder.Resources.OfType<ContainerResource>().Where(r => r.Name is "sqlserver" or "postgres" or "mailpit"))
{
await Assert.That(container.Annotations.OfType<ContainerMountAnnotation>().Any()).IsTrue();
await Assert.That(container.Annotations.OfType<ContainerLifetimeAnnotation>().Single().Lifetime)
Expand All @@ -41,6 +41,7 @@ await Assert.That(container.Annotations.OfType<ContainerLifetimeAnnotation>().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]
Expand All @@ -49,7 +50,7 @@ public async Task StandaloneGraph_EphemeralDatabases_RemovesVolumesAndPersistenc
await using var builder = await DistributedApplicationTestingBuilder.CreateAsync<Projects.EssentialCSharp_Web_AppHost>(
["--AIOptions:UseLocalAI=false", "--EssentialCSharpWeb:EphemeralDatabases=true"]);

foreach (var container in builder.Resources.OfType<ContainerResource>().Where(r => r.Name is "sqlserver" or "postgres"))
foreach (var container in builder.Resources.OfType<ContainerResource>().Where(r => r.Name is "sqlserver" or "postgres" or "mailpit"))
{
await Assert.That(container.Annotations.OfType<ContainerMountAnnotation>().Any()).IsFalse();
await Assert.That(container.Annotations.OfType<ContainerLifetimeAnnotation>()
Expand Down
Loading
Loading