using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; using FluentAssertions; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SlpModularCms.Modules.Contact.Data.Entities; using SlpModularCms.Modules.Contact.Services; namespace SlpModularCms.Modules.Contact.Tests.Pipeline; internal static class Http { public const string Route = "/api/v1/contact-messages"; public static async Task GetTokenAsync(HttpClient client) { var response = await client.GetAsync($"{Route}/token"); response.StatusCode.Should().Be(HttpStatusCode.OK); using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); return json.RootElement.GetProperty("token").GetString()!; } public static Task PostAsync( HttpClient client, string json, string? key = "new", bool useKey = true) { var request = new HttpRequestMessage(HttpMethod.Post, Route) { Content = new StringContent(json, Encoding.UTF8, "application/json"), }; if (useKey) { request.Headers.Add("Idempotency-Key", key == "new" ? Guid.NewGuid().ToString() : key); } return client.SendAsync(request); } public static string Body(string token, string name = "Jan Jansen", string hp = "") => JsonSerializer.Serialize(new { name, email = "jan@example.nl", subject = "website", message = "Ik wil graag een offerte.", hpCheck = hp, token, }); } public class ContactPipelineEnabledTests(EnabledContactHostFactory factory) : IClassFixture { [Fact] public async Task TheTokenRoute_ReturnsATokenTheMinimumTime_AndNoCaptcha() { var response = await factory.CreateClient().GetAsync($"{Http.Route}/token"); response.StatusCode.Should().Be(HttpStatusCode.OK); using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); json.RootElement.GetProperty("token").GetString().Should().NotBeNullOrWhiteSpace(); json.RootElement.GetProperty("minSeconds").GetInt32().Should().Be(0); json.RootElement.GetProperty("captcha").ValueKind.Should().Be(JsonValueKind.Null); } [Fact] public async Task AValidSubmission_Returns202_IsStoredOnce_AndAReplayDoesNotStoreAgain() { var client = factory.CreateClient(); var token = await Http.GetTokenAsync(client); var key = Guid.NewGuid().ToString(); var body = Http.Body(token, name: "Pipeline Genuine"); var first = await Http.PostAsync(client, body, key); var second = await Http.PostAsync(client, body, key); first.StatusCode.Should().Be(HttpStatusCode.Accepted); (await first.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); second.StatusCode.Should().Be(HttpStatusCode.Accepted); (await second.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); var rows = await factory.WithDb(db => db.ContactMessages.AsNoTracking().Where(m => m.Name == "Pipeline Genuine").ToListAsync()); rows.Should().ContainSingle(); rows[0].Status.Should().Be(ContactMessageStatus.New); rows[0].SiteId.Should().Be("pipeline-site"); rows[0].RetentionUntil.Should().BeAfter(DateTimeOffset.UtcNow.AddMonths(11)); } [Fact] public async Task AFilledHoneypot_GetsTheIdenticalAnswer_ButIsStoredAsSpam() { var client = factory.CreateClient(); var token = await Http.GetTokenAsync(client); var response = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Bot", hp: "http://spam")); response.StatusCode.Should().Be(HttpStatusCode.Accepted); (await response.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); var row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Pipeline Bot")); row.Status.Should().Be(ContactMessageStatus.Spam); row.MailStatus.Should().Be(ContactMailStatus.NotApplicable); row.RetentionUntil.Should().BeBefore(DateTimeOffset.UtcNow.AddDays(31)); } [Fact] public async Task InvalidFields_Return400_WithTheContractedShape() { var client = factory.CreateClient(); var token = await Http.GetTokenAsync(client); var json = JsonSerializer.Serialize(new { name = "", email = "nope", subject = "s", message = "m", hpCheck = "", token }); var response = await Http.PostAsync(client, json); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); var root = doc.RootElement; root.GetProperty("status").GetInt32().Should().Be(400); root.GetProperty("type").GetString().Should().Be("about:blank"); root.GetProperty("errors").GetProperty("name")[0].GetString().Should().Be("required"); root.GetProperty("errors").GetProperty("email")[0].GetString().Should().Be("invalid"); (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Subject == "s"))).Should().Be(0); } [Fact] public async Task AMissingIdempotencyKey_Returns400() { var client = factory.CreateClient(); var token = await Http.GetTokenAsync(client); var response = await Http.PostAsync(client, Http.Body(token), useKey: false); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); doc.RootElement.GetProperty("errors").GetProperty("idempotencyKey")[0].GetString().Should().Be("required"); } [Fact] public async Task AForgedToken_IsReportedAsExpired() { var response = await Http.PostAsync(factory.CreateClient(), Http.Body("forged-token")); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); doc.RootElement.GetProperty("errors").GetProperty("token")[0].GetString().Should().Be("expired"); } [Theory] [InlineData("{ this is not json")] [InlineData("""{"name": 123, "email": "a@b.nl"}""")] [InlineData("")] public async Task AnUnbindableBody_Returns400_InOurShape_WithoutEchoingTheInput(string body) { var response = await Http.PostAsync(factory.CreateClient(), body); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); var text = await response.Content.ReadAsStringAsync(); using var doc = JsonDocument.Parse(text); doc.RootElement.GetProperty("errors").GetProperty("body")[0].GetString().Should().Be("invalid"); text.Should().NotContain("this is not json").And.NotContain("a@b.nl"); } [Fact] public async Task ABodyBeyondTheLimit_Returns413_AsProblemJson() { var client = factory.CreateClient(); var huge = new string('x', 20_000); var response = await Http.PostAsync(client, JsonSerializer.Serialize(new { message = huge })); response.StatusCode.Should().Be(HttpStatusCode.RequestEntityTooLarge); response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); doc.RootElement.GetProperty("status").GetInt32().Should().Be(413); } [Fact] public async Task TheMigration_CreatedBothTables_AndTheIdempotencyKeyIsUnique() { var count = await factory.WithDb(async db => { var key = Guid.NewGuid(); db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 }); await db.SaveChangesAsync(); db.ChangeTracker.Clear(); db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 }); var act = () => db.SaveChangesAsync(); await act.Should().ThrowAsync("the same site cannot use a key twice"); return await db.ContactMessages.CountAsync(); }); count.Should().BeGreaterThanOrEqualTo(0); } [Fact] public async Task TheRetentionJob_RemovesExpiredRows_InTheRealDatabase() { await factory.WithDb(async db => { db.ContactMessages.Add(new ContactMessage { Id = Guid.NewGuid(), SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddYears(-2), Name = "Pipeline Expired", Email = "a@b.nl", Subject = "s", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, RetentionUntil = DateTimeOffset.UtcNow.AddDays(-1), }); await db.SaveChangesAsync(); return 0; }); var job = factory.Services.GetServices().OfType().Single(); await job.ExecuteTickAsync(CancellationToken.None); (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Expired"))).Should().Be(0); } } public class ContactPipelineDisabledTests(DisabledContactHostFactory factory) : IClassFixture { [Fact] public async Task WhileDisabled_BothRoutesAre404_WithAnEmptyBody() { var client = factory.CreateClient(); var token = await client.GetAsync($"{Http.Route}/token"); var post = await Http.PostAsync(client, Http.Body("anything")); token.StatusCode.Should().Be(HttpStatusCode.NotFound); (await token.Content.ReadAsStringAsync()).Should().BeEmpty(); post.StatusCode.Should().Be(HttpStatusCode.NotFound); (await post.Content.ReadAsStringAsync()).Should().BeEmpty(); } [Fact] public async Task WhileDisabled_TheModuleNeverTouchedTheDatabase_AndTheRetentionJobDoesNothing() { // The host has started (other modules migrated their tables), but the contact tables do // not exist: the module neither migrated nor queried anything. await using var connection = new MySql.Data.MySqlClient.MySqlConnection(factory.ConnectionString); await connection.OpenAsync(); await using var command = connection.CreateCommand(); command.CommandText = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name IN ('ContactMessages','ContactIdempotency')"; Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0); _ = factory.CreateClient(); // make sure the host is up var job = factory.Services.GetServices().OfType().Single(); await job.ExecuteTickAsync(CancellationToken.None); Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0, "the disabled job must not create or touch anything"); } } public class ContactPipelineFormRateLimitTests(TightFormLimitContactHostFactory factory) : IClassFixture { [Fact] public async Task TheFormPolicy_Answers429_WithRetryAfter_AndOnlyTheStandardFields() { var client = factory.CreateClient(); var token = await Http.GetTokenAsync(client); HttpResponseMessage? last = null; for (var i = 0; i < 3; i++) { last = await Http.PostAsync(client, Http.Body(token, name: $"Pipeline Limit {i}")); } last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue(); int.Parse(retryAfter!.Single()).Should().BeInRange(1, 600); last.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); using var doc = JsonDocument.Parse(await last.Content.ReadAsStringAsync()); doc.RootElement.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["type", "title", "status"]); } } public class ContactPipelineTokenRateLimitTests(TightTokenLimitContactHostFactory factory) : IClassFixture { [Fact] public async Task TheTokenPolicy_AnswersAfterItsOwnLimit_With429AndRetryAfter() { var client = factory.CreateClient(); HttpResponseMessage? last = null; for (var i = 0; i < 3; i++) { last = await client.GetAsync($"{Http.Route}/token"); } last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); last.Headers.Contains("Retry-After").Should().BeTrue(); } } public class ContactPipelineGateTests(EnabledContactHostFactory factory) : IClassFixture { [Fact] public async Task TheContactRoutes_StayReachable_WhileTheCmsIsDisabled_ButAdminRoutesAreBlocked() { // Switch the CMS off through the availability state of the real database. await factory.WithDb(db => db.Database.ExecuteSqlRawAsync( "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')")); var client = factory.CreateClient(); (await client.GetAsync("/api/v1/offerings/categories")).StatusCode .Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed"); var token = await Http.GetTokenAsync(client); var post = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Gate")); post.StatusCode.Should().Be(HttpStatusCode.Accepted); (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Gate"))).Should().Be(1); } }