Contactmodule: token- en inzendroute met spamafhandeling, idempotentie en retentietaak

Nieuwe module SlpModularCms.Modules.Contact met eigen DbContext en migratie InitialCreate. GET contact-messages/token en POST contact-messages zijn publiek ([PublicSiteEndpoint]), geven bij echte inzendingen, spam en herhalingen hetzelfde 202 en slaan spam apart op (30 dagen, dagplafond). Standaard staat de module uit (Contact:Enabled=false, 404 met lege body, geen databasetoegang) totdat de rate limiting per client op de basisbranch staat; de rate-limit-sleutel zit in een enkele functie zodat dat later een regel wijzigen is. Mail zit achter een seam (nog een no-op).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:07:27 +01:00
co-authored by Claude Sonnet 5.5
parent 0f6f5475a1
commit 7748bbe9c9
37 changed files with 3266 additions and 9 deletions
@@ -0,0 +1,52 @@
namespace SlpModularCms.Modules.Contact.Config;
/// <summary>
/// Per-host configuration of the contact module (section <c>Contact</c>).
/// </summary>
public class ContactOptions
{
public const string SectionName = "Contact";
/// <summary>
/// Master switch. While false the contact routes answer 404 and the module touches nothing.
/// It must only be switched on for a public host once per-client rate limiting is in place
/// (see <see cref="Services.ContactRateLimitPartition"/>).
/// </summary>
public bool Enabled { get; set; }
/// <summary>Identifies the site on stored rows and in the token purpose. Never taken from a request.</summary>
public string? SiteId { get; set; }
/// <summary>Minimum seconds between issuing the token and submitting; faster submissions are treated as spam.</summary>
public int MinSeconds { get; set; } = 3;
public int TokenLifetimeMinutes { get; set; } = 120;
/// <summary>Months a genuine message is kept (fixed per row at insert).</summary>
public int RetentionMonths { get; set; } = 12;
/// <summary>Days a message classified as spam is kept.</summary>
public int SpamRetentionDays { get; set; } = 30;
/// <summary>Per site and UTC day; beyond it spam is answered normally but not stored.</summary>
public int MaxSpamRowsPerDay { get; set; } = 200;
public int MaxBodyBytes { get; set; } = 16384;
/// <summary>Base of the validation problem <c>type</c> URI. When empty the type is <c>about:blank</c>.</summary>
public string? ProblemTypeBase { get; set; }
public ContactCaptchaOptions Captcha { get; set; } = new();
public string EffectiveSiteId => string.IsNullOrWhiteSpace(SiteId) ? "default" : SiteId.Trim();
}
public class ContactCaptchaOptions
{
public bool Enabled { get; set; }
public string? Provider { get; set; }
public string? SiteKey { get; set; }
/// <summary>Server-side secret; supply it through the environment or a secrets manager, never committed.</summary>
public string? Secret { get; set; }
}
@@ -0,0 +1,89 @@
using System.Diagnostics.CodeAnalysis;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Modules;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Controllers;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Repositories;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact;
[ExcludeFromCodeCoverage]
public class ContactModule : IModule
{
public string Name => "Contact";
public string Version => "1.0.0";
public void RegisterServices(IServiceCollection services)
{
services.AddOptions<ContactOptions>()
.Configure<IConfiguration>((options, config) =>
config.GetSection(ContactOptions.SectionName).Bind(options));
services.AddDbContext<ContactDbContext>((serviceProvider, options) =>
{
var config = serviceProvider.GetRequiredService<IConfiguration>();
options.UseMySQL(config.GetConnectionString("DefaultConnection")!);
options.ReplaceService<IHistoryRepository, NonLockingMySQLHistoryRepository>();
});
services.TryAddSingleton(TimeProvider.System);
services.AddScoped<IContactRepository, ContactRepository>();
services.AddScoped<IContactSubmissionService, ContactSubmissionService>();
services.AddSingleton<IContactTokenService, ContactTokenService>();
services.AddSingleton<ICaptchaVerifier, NullCaptchaVerifier>();
services.AddScoped<IContactMailSender, NoOpContactMailSender>();
services.AddScoped<IContactFormGate, HostFlagContactFormGate>();
services.AddScoped<ContactRouteFilter>();
services.AddHostedService<ContactRetentionService>();
// Rate-limit policies live in this module so the shared limiter setup stays untouched.
// The bucket key comes from one function; see ContactRateLimitPartition.
services.AddOptions<RateLimiterOptions>()
.Configure<IConfiguration>((limiter, config) =>
{
limiter.AddPolicy(ContactMessagesController.FormPolicy, context =>
Window(config, "ContactForm", 5, 600, context));
limiter.AddPolicy(ContactMessagesController.TokenPolicy, context =>
Window(config, "ContactToken", 20, 600, context));
});
}
public void UseModule(IApplicationBuilder app)
{
// Nothing is touched while the module is switched off: not even the database.
var enabled = app.ApplicationServices.GetRequiredService<IOptions<ContactOptions>>().Value.Enabled;
if (!enabled)
{
return;
}
using var scope = app.ApplicationServices.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ContactDbContext>();
db.Database.Migrate();
}
private static RateLimitPartition<string> Window(
IConfiguration config, string name, int defaultPermits, int defaultSeconds, Microsoft.AspNetCore.Http.HttpContext context)
{
var section = config.GetSection($"RateLimiting:{name}");
return RateLimitPartition.GetFixedWindowLimiter(
ContactRateLimitPartition.KeyFor(context),
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = section.GetValue("PermitLimit", defaultPermits),
Window = TimeSpan.FromSeconds(section.GetValue("WindowSeconds", defaultSeconds)),
QueueLimit = 0,
});
}
}
@@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Availability;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Controllers;
/// <summary>
/// The public contact routes. Deliberately not an <c>[ApiController]</c>: a body that cannot be
/// bound must produce our own problem shape, never the framework's, and must not echo values.
/// The management routes (list, read, delete, resend) are added with the admin unit.
/// </summary>
[Route("contact-messages")]
[ServiceFilter(typeof(ContactRouteFilter))]
public class ContactMessagesController(
IContactTokenService tokens,
IContactSubmissionService submissions,
IOptions<ContactOptions> options) : ControllerBase
{
public const string IdempotencyKeyHeader = "Idempotency-Key";
public const string TokenPolicy = "contact-token";
public const string FormPolicy = "contact-form";
[HttpGet("token")]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting(TokenPolicy)]
public IActionResult GetToken()
{
var settings = options.Value;
var captcha = settings.Captcha is { Enabled: true } c && !string.IsNullOrWhiteSpace(c.Provider)
? new ContactCaptchaInfo(c.Provider!, c.SiteKey ?? string.Empty)
: null;
return Ok(new ContactTokenResponse(tokens.Issue(), settings.MinSeconds, captcha));
}
[HttpPost]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting(FormPolicy)]
public async Task<IActionResult> Submit([FromBody] ContactMessageRequest? request, CancellationToken cancellationToken)
{
var key = Request.Headers[IdempotencyKeyHeader].FirstOrDefault();
// An unbindable body (malformed JSON, wrong types) arrives as null.
var result = await submissions.SubmitAsync(ModelState.IsValid ? request : null, key, cancellationToken);
return result switch
{
SubmissionResult.Invalid invalid => BadRequest(Problem(invalid.Errors)),
_ => new ObjectResult(new ReceivedResponse("received")) { StatusCode = StatusCodes.Status202Accepted },
};
}
private ValidationProblemDetails Problem(IReadOnlyDictionary<string, string[]> errors)
{
var baseUri = options.Value.ProblemTypeBase?.TrimEnd('/');
return new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value))
{
Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation",
Title = "Validation failed",
Status = StatusCodes.Status400BadRequest,
};
}
}
@@ -0,0 +1,63 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Controllers;
/// <summary>
/// Runs before model binding on the public contact routes:
/// 1. While the form is not open (see <see cref="IContactFormGate"/>) the route does not exist
/// (404, empty body).
/// 2. Caps the request body (413 as problem+json), also when the size is only known while reading.
/// </summary>
public sealed class ContactRouteFilter(IContactFormGate gate, IOptions<ContactOptions> options) : IAsyncResourceFilter
{
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
var settings = options.Value;
if (!await gate.IsOpenAsync(context.HttpContext.RequestAborted))
{
context.Result = new NotFoundResult();
return;
}
var request = context.HttpContext.Request;
if (HttpMethods.IsPost(request.Method))
{
if (request.ContentLength > settings.MaxBodyBytes)
{
context.Result = TooLarge();
return;
}
// For chunked bodies the length is unknown up front; Kestrel enforces the cap while reading.
var feature = context.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
if (feature is { IsReadOnly: false })
{
feature.MaxRequestBodySize = settings.MaxBodyBytes;
}
}
var executed = await next();
if (executed.Exception is BadHttpRequestException { StatusCode: StatusCodes.Status413PayloadTooLarge })
{
executed.ExceptionHandled = true;
executed.Result = TooLarge();
}
}
private static ObjectResult TooLarge() => new(new ProblemDetails
{
Status = StatusCodes.Status413PayloadTooLarge,
Title = "Payload too large",
})
{
StatusCode = StatusCodes.Status413PayloadTooLarge,
ContentTypes = { "application/problem+json" },
};
}
@@ -0,0 +1,44 @@
using Microsoft.EntityFrameworkCore;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Data;
public class ContactDbContext(DbContextOptions<ContactDbContext> options) : DbContext(options)
{
public DbSet<ContactMessage> ContactMessages => Set<ContactMessage>();
public DbSet<IdempotencyRecord> IdempotencyRecords => Set<IdempotencyRecord>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ContactMessage>(entity =>
{
entity.ToTable("ContactMessages");
entity.HasKey(e => e.Id);
entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100);
entity.Property(e => e.ReceivedAt).IsRequired();
entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
entity.Property(e => e.Email).IsRequired().HasMaxLength(254);
entity.Property(e => e.Subject).IsRequired().HasMaxLength(100);
entity.Property(e => e.Message).IsRequired().HasMaxLength(2000);
entity.Property(e => e.Status).IsRequired().HasConversion<string>().HasMaxLength(20);
entity.Property(e => e.MailStatus).IsRequired().HasConversion<string>().HasMaxLength(20);
entity.Property(e => e.MailError).HasMaxLength(100);
entity.Property(e => e.RetentionUntil).IsRequired();
entity.HasIndex(e => new { e.SiteId, e.Status, e.ReceivedAt });
entity.HasIndex(e => e.RetentionUntil);
});
modelBuilder.Entity<IdempotencyRecord>(entity =>
{
entity.ToTable("ContactIdempotency");
entity.HasKey(e => new { e.SiteId, e.Key });
entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100);
entity.Property(e => e.CreatedAt).IsRequired();
entity.Property(e => e.StatusCode).IsRequired();
entity.HasIndex(e => e.CreatedAt);
});
}
}
@@ -0,0 +1,58 @@
namespace SlpModularCms.Modules.Contact.Data.Entities;
public enum ContactMessageStatus
{
New,
Read,
Archived,
Spam,
Converted,
}
public enum ContactMailStatus
{
/// <summary>Waiting to be mailed (also the state while no mail sender is available).</summary>
Pending,
Sent,
Failed,
/// <summary>Never mailed on purpose (spam).</summary>
NotApplicable,
}
/// <summary>
/// A message sent through the website's contact form. Has its own id and status so that it can
/// later be turned into an assignment (quotes, invoices); that is not built yet.
/// </summary>
public class ContactMessage
{
public Guid Id { get; set; }
public string SiteId { get; set; } = string.Empty;
public DateTimeOffset ReceivedAt { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
/// <summary>Opaque value chosen by the site (a package id, a slug, or 'other').</summary>
public string Subject { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public ContactMessageStatus Status { get; set; }
public ContactMailStatus MailStatus { get; set; }
/// <summary>Short error code of the last failed mail attempt (never an address or content).</summary>
public string? MailError { get; set; }
public int MailAttempts { get; set; }
public DateTimeOffset? NextMailAttemptAt { get; set; }
/// <summary>Fixed at insert: a later configuration change does not apply retroactively.</summary>
public DateTimeOffset RetentionUntil { get; set; }
}
/// <summary>Remembers an Idempotency-Key for 24 hours. Holds no request content.</summary>
public class IdempotencyRecord
{
public string SiteId { get; set; } = string.Empty;
public Guid Key { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public int StatusCode { get; set; }
}
@@ -0,0 +1,115 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Contact.Data;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
[DbContext(typeof(ContactDbContext))]
[Migration("20261109200014_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<int>("MailAttempts")
.HasColumnType("int");
b.Property<string>("MailError")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("MailStatus")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("varchar(2000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset?>("NextMailAttemptAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("ReceivedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("RetentionUntil")
.HasColumnType("datetime");
b.Property<string>("SiteId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Subject")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Id");
b.HasIndex("RetentionUntil");
b.HasIndex("SiteId", "Status", "ReceivedAt");
b.ToTable("ContactMessages", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
{
b.Property<string>("SiteId")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<Guid>("Key")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<int>("StatusCode")
.HasColumnType("int");
b.HasKey("SiteId", "Key");
b.HasIndex("CreatedAt");
b.ToTable("ContactIdempotency", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase()
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "ContactIdempotency",
columns: table => new
{
SiteId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Key = table.Column<Guid>(type: "char(36)", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
StatusCode = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactIdempotency", x => new { x.SiteId, x.Key });
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateTable(
name: "ContactMessages",
columns: table => new
{
Id = table.Column<Guid>(type: "char(36)", nullable: false),
SiteId = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
ReceivedAt = table.Column<DateTimeOffset>(type: "datetime", nullable: false),
Name = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Email = table.Column<string>(type: "varchar(254)", maxLength: 254, nullable: false),
Subject = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: false),
Message = table.Column<string>(type: "varchar(2000)", maxLength: 2000, nullable: false),
Status = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
MailStatus = table.Column<string>(type: "varchar(20)", maxLength: 20, nullable: false),
MailError = table.Column<string>(type: "varchar(100)", maxLength: 100, nullable: true),
MailAttempts = table.Column<int>(type: "int", nullable: false),
NextMailAttemptAt = table.Column<DateTimeOffset>(type: "datetime", nullable: true),
RetentionUntil = table.Column<DateTimeOffset>(type: "datetime", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ContactMessages", x => x.Id);
})
.Annotation("MySQL:Charset", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_ContactIdempotency_CreatedAt",
table: "ContactIdempotency",
column: "CreatedAt");
migrationBuilder.CreateIndex(
name: "IX_ContactMessages_RetentionUntil",
table: "ContactMessages",
column: "RetentionUntil");
migrationBuilder.CreateIndex(
name: "IX_ContactMessages_SiteId_Status_ReceivedAt",
table: "ContactMessages",
columns: new[] { "SiteId", "Status", "ReceivedAt" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ContactIdempotency");
migrationBuilder.DropTable(
name: "ContactMessages");
}
}
}
@@ -0,0 +1,112 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SlpModularCms.Modules.Contact.Data;
#nullable disable
namespace SlpModularCms.Modules.Contact.Migrations
{
[DbContext(typeof(ContactDbContext))]
partial class ContactDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(254)
.HasColumnType("varchar(254)");
b.Property<int>("MailAttempts")
.HasColumnType("int");
b.Property<string>("MailError")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("MailStatus")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Message")
.IsRequired()
.HasMaxLength(2000)
.HasColumnType("varchar(2000)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<DateTimeOffset?>("NextMailAttemptAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("ReceivedAt")
.HasColumnType("datetime");
b.Property<DateTimeOffset>("RetentionUntil")
.HasColumnType("datetime");
b.Property<string>("SiteId")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Subject")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.HasKey("Id");
b.HasIndex("RetentionUntil");
b.HasIndex("SiteId", "Status", "ReceivedAt");
b.ToTable("ContactMessages", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b =>
{
b.Property<string>("SiteId")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<Guid>("Key")
.HasColumnType("char(36)");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<int>("StatusCode")
.HasColumnType("int");
b.HasKey("SiteId", "Key");
b.HasIndex("CreatedAt");
b.ToTable("ContactIdempotency", (string)null);
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,44 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Modules.Contact.Models;
/// <summary>
/// The body of POST /contact-messages. Everything is nullable on purpose: a missing field is
/// reported as the validation code <c>required</c> in our own problem shape instead of a
/// framework binding error. <c>HpCheck</c> is the honeypot (JSON name <c>hpCheck</c>).
/// </summary>
public record ContactMessageRequest(
string? Name,
string? Email,
string? Subject,
string? Message,
string? HpCheck,
string? Token,
string? CaptchaToken);
[ExcludeFromCodeCoverage]
public record ContactCaptchaInfo(string Provider, string SiteKey);
[ExcludeFromCodeCoverage]
public record ContactTokenResponse(string Token, int MinSeconds, ContactCaptchaInfo? Captcha);
[ExcludeFromCodeCoverage]
public record ReceivedResponse(string Status);
/// <summary>Validation error codes, as the client maps them to texts.</summary>
public static class ContactErrorCodes
{
public const string Required = "required";
public const string TooLong = "tooLong";
public const string Invalid = "invalid";
public const string Expired = "expired";
}
/// <summary>Outcome of handling one submission.</summary>
public abstract record SubmissionResult
{
/// <summary>Accepted: genuine, spam and replays all look the same to the caller.</summary>
public sealed record Received : SubmissionResult;
public sealed record Invalid(IReadOnlyDictionary<string, string[]> Errors) : SubmissionResult;
}
@@ -0,0 +1,75 @@
using Microsoft.EntityFrameworkCore;
using SlpModularCms.Modules.Contact.Data;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Repositories;
public interface IContactRepository
{
Task<IdempotencyRecord?> GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken);
Task<int> CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken);
void Add(ContactMessage message);
void Add(IdempotencyRecord record);
Task SaveChangesAsync(CancellationToken cancellationToken);
Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken);
Task<int> DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken);
}
public class ContactRepository(ContactDbContext context) : IContactRepository
{
private const int BatchSize = 500;
public Task<IdempotencyRecord?> GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken)
=> context.IdempotencyRecords.FirstOrDefaultAsync(r => r.SiteId == siteId && r.Key == key, cancellationToken);
public Task<int> CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken)
=> context.ContactMessages.CountAsync(
m => m.SiteId == siteId && m.Status == ContactMessageStatus.Spam && m.ReceivedAt >= since,
cancellationToken);
public void Add(ContactMessage message) => context.ContactMessages.Add(message);
public void Add(IdempotencyRecord record) => context.IdempotencyRecords.Add(record);
public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken);
public async Task<int> DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken)
{
var total = 0;
while (true)
{
var batch = await context.ContactMessages
.Where(m => m.RetentionUntil < now)
.Take(BatchSize)
.ToListAsync(cancellationToken);
if (batch.Count == 0)
{
return total;
}
context.ContactMessages.RemoveRange(batch);
await context.SaveChangesAsync(cancellationToken);
total += batch.Count;
}
}
public async Task<int> DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken)
{
var total = 0;
while (true)
{
var batch = await context.IdempotencyRecords
.Where(r => r.CreatedAt < cutoff)
.Take(BatchSize)
.ToListAsync(cancellationToken);
if (batch.Count == 0)
{
return total;
}
context.IdempotencyRecords.RemoveRange(batch);
await context.SaveChangesAsync(cancellationToken);
total += batch.Count;
}
}
}
@@ -0,0 +1,25 @@
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Decides whether the public contact form is active. The form is active only when every layer
/// says so; if any layer is off the public routes answer 404 with an empty body (the website
/// then shows its mailto fallback).
/// </summary>
/// <remarks>
/// Layers: (1) the host switch <c>Contact:Enabled</c> (release condition, default off) and,
/// from the admin unit on, (2) a switch an administrator controls in the CMS. The route filter
/// only knows this interface, so adding the second layer does not touch the filter.
/// </remarks>
public interface IContactFormGate
{
Task<bool> IsOpenAsync(CancellationToken cancellationToken);
}
/// <summary>Layer 1: the host configuration.</summary>
public sealed class HostFlagContactFormGate(IOptions<ContactOptions> options) : IContactFormGate
{
public Task<bool> IsOpenAsync(CancellationToken cancellationToken) => Task.FromResult(options.Value.Enabled);
}
@@ -0,0 +1,58 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Repositories;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Daily clean-up: deletes messages past their retention date and idempotency records older
/// than 24 hours. While the module is disabled it does nothing at all (no database access).
/// </summary>
public class ContactRetentionService(
IServiceScopeFactory scopeFactory,
IOptions<ContactOptions> options,
TimeProvider time,
ILogger<ContactRetentionService> logger) : BackgroundService
{
internal static readonly TimeSpan Interval = TimeSpan.FromHours(24);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await ExecuteTickAsync(stoppingToken);
using var timer = new PeriodicTimer(Interval);
while (await timer.WaitForNextTickAsync(stoppingToken))
{
await ExecuteTickAsync(stoppingToken);
}
}
internal async Task ExecuteTickAsync(CancellationToken stoppingToken)
{
if (!options.Value.Enabled)
{
return;
}
try
{
await using var scope = scopeFactory.CreateAsyncScope();
var repository = scope.ServiceProvider.GetRequiredService<IContactRepository>();
var now = time.GetUtcNow();
var messages = await repository.DeleteExpiredMessagesAsync(now, stoppingToken);
var records = await repository.DeleteIdempotencyOlderThanAsync(now - TimeSpan.FromHours(24), stoppingToken);
logger.LogInformation(
"Contact retention: removed {Messages} expired message(s) and {Records} idempotency record(s)",
messages, records);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
logger.LogError("Contact retention run failed ({ExceptionType})", ex.GetType().Name);
}
}
}
@@ -0,0 +1,61 @@
using Microsoft.AspNetCore.Http;
using SlpModularCms.Modules.Contact.Data.Entities;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Verifies a captcha token server-side. Implementations must fail open: when the provider
/// itself is unreachable they return <c>true</c> (and log without personal data), so real
/// visitors are never locked out by a provider outage.
/// </summary>
public interface ICaptchaVerifier
{
Task<bool> VerifyAsync(string? captchaToken, CancellationToken cancellationToken);
}
/// <summary>Used while no captcha is configured: everything passes.</summary>
public sealed class NullCaptchaVerifier : ICaptchaVerifier
{
public Task<bool> VerifyAsync(string? captchaToken, CancellationToken cancellationToken) => Task.FromResult(true);
}
public enum ContactMailOutcome
{
/// <summary>No mail was attempted (no sender available yet); the message stays pending.</summary>
Skipped,
Sent,
Failed,
}
/// <summary>
/// Sends the notification mail for a genuine message. Called after the message is stored; a
/// failure must never fail the request. The real implementation arrives with the mail unit.
/// </summary>
public interface IContactMailSender
{
Task<ContactMailOutcome> SendAsync(ContactMessage message, CancellationToken cancellationToken);
}
public sealed class NoOpContactMailSender : IContactMailSender
{
public Task<ContactMailOutcome> SendAsync(ContactMessage message, CancellationToken cancellationToken)
=> Task.FromResult(ContactMailOutcome.Skipped);
}
/// <summary>
/// The single place that decides which rate-limit bucket a request belongs to.
/// </summary>
/// <remarks>
/// On the base branch the rate limiter has no per-client partitioning (no forwarded-header
/// handling, no client key): every visitor is the same caller. This returns a constant, so the
/// contact policies behave as ONE shared bucket per policy, which is why the contact routes are
/// disabled (<c>Contact:Enabled=false</c>) until the per-client partitioning from the ASF branch
/// has been merged. Switching to per-client is the one-line change documented in the rebase
/// checklist: replace the body with <c>ClientPartitionKey.For(context)</c>.
/// </remarks>
public static class ContactRateLimitPartition
{
public const string GlobalKey = "global";
public static string KeyFor(HttpContext context) => GlobalKey;
}
@@ -0,0 +1,205 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Repositories;
namespace SlpModularCms.Modules.Contact.Services;
public interface IContactSubmissionService
{
Task<SubmissionResult> SubmitAsync(ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken);
}
/// <summary>
/// Handles one submission: validate, de-duplicate, classify (genuine or spam), store, mail.
/// Genuine messages, spam and replays are indistinguishable to the caller (the same 202), so
/// bots learn nothing. Nothing personal is ever logged: only the outcome and the site id.
/// </summary>
public sealed class ContactSubmissionService(
IContactRepository repository,
IContactTokenService tokens,
ICaptchaVerifier captcha,
IContactMailSender mailSender,
IOptions<ContactOptions> options,
TimeProvider time,
ILogger<ContactSubmissionService> logger) : IContactSubmissionService
{
private static readonly TimeSpan IdempotencyWindow = TimeSpan.FromHours(24);
private enum Outcome { Genuine, Spam, SpamNotStored, Replay }
public async Task<SubmissionResult> SubmitAsync(
ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken)
{
var o = options.Value;
var siteId = o.EffectiveSiteId;
// 1. Header and fields (one response lists every problem).
var errors = new Dictionary<string, string[]>();
Guid key = default;
if (string.IsNullOrWhiteSpace(idempotencyKey))
{
errors["idempotencyKey"] = [ContactErrorCodes.Required];
}
else if (!Guid.TryParse(idempotencyKey, out key))
{
errors["idempotencyKey"] = [ContactErrorCodes.Invalid];
}
if (request is null)
{
errors["body"] = [ContactErrorCodes.Invalid];
}
else
{
request = ContactValidator.Normalize(request);
foreach (var (field, codes) in ContactValidator.Validate(request))
{
errors[field] = codes;
}
}
if (errors.Count > 0)
{
return new SubmissionResult.Invalid(errors);
}
var now = time.GetUtcNow();
// 2. Replay within 24 hours: the same answer, nothing stored twice.
var existing = await repository.GetIdempotencyAsync(siteId, key, cancellationToken);
if (existing is not null && now - existing.CreatedAt < IdempotencyWindow)
{
Log(Outcome.Replay, siteId);
return new SubmissionResult.Received();
}
// 3. Token. Forged, other-site and expired tokens all look the same ('expired'): no oracle.
var tokenCheck = tokens.Check(request!.Token);
if (tokenCheck == TokenCheck.InvalidOrExpired)
{
return new SubmissionResult.Invalid(new Dictionary<string, string[]>
{
["token"] = [ContactErrorCodes.Expired],
});
}
// 4. Classify. A filled honeypot, a too-fast submission or a rejected captcha is spam.
var isSpam = tokenCheck == TokenCheck.TooYoung
|| !string.IsNullOrEmpty(request.HpCheck)
|| (o.Captcha.Enabled && !await captcha.VerifyAsync(request.CaptchaToken, cancellationToken));
// 5. Store. Spam is kept for a short time (a real visitor may have tripped a check) but
// capped per day so a flood cannot fill the table.
ContactMessage? message = null;
var outcome = Outcome.Genuine;
if (isSpam)
{
var startOfDay = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
var spamToday = await repository.CountSpamSinceAsync(siteId, startOfDay, cancellationToken);
if (spamToday < o.MaxSpamRowsPerDay)
{
message = NewMessage(request, siteId, now, ContactMessageStatus.Spam, ContactMailStatus.NotApplicable,
now.AddDays(o.SpamRetentionDays));
outcome = Outcome.Spam;
}
else
{
outcome = Outcome.SpamNotStored;
}
}
else
{
message = NewMessage(request, siteId, now, ContactMessageStatus.New, ContactMailStatus.Pending,
now.AddMonths(o.RetentionMonths));
}
if (message is not null)
{
repository.Add(message);
}
if (existing is null)
{
repository.Add(new IdempotencyRecord
{
SiteId = siteId,
Key = key,
CreatedAt = now,
StatusCode = StatusCodes202,
});
}
else
{
// An expired record that the daily job has not removed yet: reuse its row.
existing.CreatedAt = now;
existing.StatusCode = StatusCodes202;
}
try
{
await repository.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException)
{
// Two requests with the same key raced; the other one won. Same answer, nothing twice.
Log(Outcome.Replay, siteId);
return new SubmissionResult.Received();
}
// 6. Mail, only for genuine messages and only after the message is safely stored. A mail
// problem never fails the request.
if (outcome == Outcome.Genuine && message is not null)
{
await TryMailAsync(message, cancellationToken);
}
Log(outcome, siteId);
return new SubmissionResult.Received();
}
private const int StatusCodes202 = 202;
private async Task TryMailAsync(ContactMessage message, CancellationToken cancellationToken)
{
try
{
var result = await mailSender.SendAsync(message, cancellationToken);
if (result == ContactMailOutcome.Skipped)
{
return;
}
message.MailAttempts++;
message.MailStatus = result == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed;
await repository.SaveChangesAsync(cancellationToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// Type only: the exception message could carry addresses or content.
logger.LogError("Notification mail for a contact message failed ({ExceptionType})", ex.GetType().Name);
}
}
private static ContactMessage NewMessage(
ContactMessageRequest request, string siteId, DateTimeOffset now,
ContactMessageStatus status, ContactMailStatus mailStatus, DateTimeOffset retentionUntil) => new()
{
Id = Guid.NewGuid(),
SiteId = siteId,
ReceivedAt = now,
Name = request.Name!,
Email = request.Email!,
Subject = request.Subject!,
Message = request.Message!,
Status = status,
MailStatus = mailStatus,
RetentionUntil = retentionUntil,
};
private void Log(Outcome outcome, string siteId)
=> logger.LogInformation("Contact submission handled: {Outcome} for site {SiteId}", outcome, siteId);
}
@@ -0,0 +1,83 @@
using System.Globalization;
using System.Security.Cryptography;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
namespace SlpModularCms.Modules.Contact.Services;
public enum TokenCheck
{
Valid,
/// <summary>Issued less than <c>MinSeconds</c> ago: the form was filled in faster than a person can.</summary>
TooYoung,
/// <summary>Forged, garbage, from another site, or older than its lifetime. Never distinguished to the caller.</summary>
InvalidOrExpired,
}
public interface IContactTokenService
{
string Issue();
TokenCheck Check(string? token);
}
/// <summary>
/// Server-signed token for the minimum-time check. Protected with ASP.NET Data Protection (the
/// host stores the key ring in the database), bound to the site by the purpose string, so a token
/// of one site is garbage to another. Nothing is stored.
/// </summary>
public sealed class ContactTokenService : IContactTokenService
{
private const string Version = "v1";
private readonly IDataProtector _protector;
private readonly ContactOptions _options;
private readonly TimeProvider _time;
public ContactTokenService(IDataProtectionProvider provider, IOptions<ContactOptions> options, TimeProvider time)
{
_options = options.Value;
_time = time;
_protector = provider.CreateProtector(PurposeFor(_options.EffectiveSiteId));
}
public static string PurposeFor(string siteId) => $"SlpModularCms.Contact.Token.{siteId}";
public string Issue()
=> _protector.Protect($"{Version}|{_time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)}");
public TokenCheck Check(string? token)
{
if (string.IsNullOrWhiteSpace(token))
{
return TokenCheck.InvalidOrExpired;
}
string payload;
try
{
payload = _protector.Unprotect(token);
}
catch (CryptographicException)
{
return TokenCheck.InvalidOrExpired;
}
var parts = payload.Split('|');
if (parts.Length != 2 || parts[0] != Version
|| !long.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var issuedAt))
{
return TokenCheck.InvalidOrExpired;
}
var age = _time.GetUtcNow().ToUnixTimeSeconds() - issuedAt;
if (age < 0 || age > TimeSpan.FromMinutes(_options.TokenLifetimeMinutes).TotalSeconds)
{
return TokenCheck.InvalidOrExpired;
}
return age < _options.MinSeconds ? TokenCheck.TooYoung : TokenCheck.Valid;
}
}
@@ -0,0 +1,115 @@
using System.Text.RegularExpressions;
using SlpModularCms.Modules.Contact.Models;
namespace SlpModularCms.Modules.Contact.Services;
/// <summary>
/// Field rules of the contact form. Pure: no I/O, no clock. The same limits and codes are used
/// by the client so the two can never disagree silently.
/// </summary>
public static class ContactValidator
{
public const int NameMax = 100;
public const int EmailMax = 254;
public const int SubjectMax = 100;
public const int MessageMax = 2000;
private static readonly Regex EmailPattern =
new(@"^[^\s@]+@[^\s@]+\.[^\s@]{2,}$", RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(250));
/// <summary>The request with all text fields trimmed (null stays null).</summary>
public static ContactMessageRequest Normalize(ContactMessageRequest request) => request with
{
Name = request.Name?.Trim(),
Email = request.Email?.Trim(),
Subject = request.Subject?.Trim(),
Message = request.Message?.Trim(),
Token = request.Token?.Trim(),
};
/// <summary>Validates an already normalized request. Keys are the JSON field names.</summary>
public static Dictionary<string, string[]> Validate(ContactMessageRequest request)
{
var errors = new Dictionary<string, string[]>();
Check(errors, "name", request.Name, NameMax, allowLineBreaks: false);
CheckEmail(errors, request.Email);
Check(errors, "subject", request.Subject, SubjectMax, allowLineBreaks: false);
Check(errors, "message", request.Message, MessageMax, allowLineBreaks: true);
if (string.IsNullOrWhiteSpace(request.Token))
{
errors["token"] = [ContactErrorCodes.Required];
}
return errors;
}
private static void Check(Dictionary<string, string[]> errors, string field, string? value, int max, bool allowLineBreaks)
{
if (string.IsNullOrEmpty(value))
{
errors[field] = [ContactErrorCodes.Required];
}
else if (value.Length > max)
{
errors[field] = [ContactErrorCodes.TooLong];
}
else if (HasControlCharacters(value, allowLineBreaks))
{
errors[field] = [ContactErrorCodes.Invalid];
}
}
private static void CheckEmail(Dictionary<string, string[]> errors, string? value)
{
if (string.IsNullOrEmpty(value))
{
errors["email"] = [ContactErrorCodes.Required];
}
else if (value.Length > EmailMax)
{
errors["email"] = [ContactErrorCodes.TooLong];
}
else if (HasControlCharacters(value, allowLineBreaks: false) || !IsEmailShaped(value))
{
errors["email"] = [ContactErrorCodes.Invalid];
}
}
private static bool IsEmailShaped(string value)
{
try
{
return EmailPattern.IsMatch(value);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
/// <summary>
/// Control characters would end up in mail headers (header injection) or break displays.
/// In the message, tabs and line breaks are normal text and allowed.
/// </summary>
internal static bool HasControlCharacters(string value, bool allowLineBreaks)
{
foreach (var c in value)
{
if (!char.IsControl(c))
{
continue;
}
if (allowLineBreaks && (c is '\n' or '\r' or '\t'))
{
continue;
}
return true;
}
return false;
}
}
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>SlpModularCms.Modules.Contact.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
</ItemGroup>
</Project>