Contactbeheer: berichten, schakelaar en tweelaagse poort voor het formulier
Beheerroutes zonder /admin-segment op contact-messages (lijst met spam apart en ongelezen-teller zonder spam, detail, status, verwijderen, opnieuw versturen met eigen limiet) en contact-settings voor de CMS-schakelaar, allemaal AdminOnly. Het formulier is alleen open als de hostvlag EN de CMS-schakelaar (standaard uit) aan staan; de hostvlag wordt eerst gecontroleerd zodat de database niet wordt aangeraakt. Bij uitgeschakelde host antwoorden de beheerroutes 404. OpenAPI-document bijgewerkt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,343 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using SlpModularCms.Modules.Contact.Data.Entities;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
|
||||
|
||||
/// <summary>Mints access tokens the way the host itself does (same settings, same claims).</summary>
|
||||
internal static class Jwt
|
||||
{
|
||||
public static HttpClient ClientWithRole(ContactHostFactory factory, string role, Guid? userId = null)
|
||||
{
|
||||
var settings = factory.Services.GetRequiredService<IConfiguration>().GetSection("JwtSettings");
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings["Secret"]!));
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: settings["Issuer"],
|
||||
audience: settings["Audience"],
|
||||
claims:
|
||||
[
|
||||
new Claim(ClaimTypes.NameIdentifier, (userId ?? Guid.NewGuid()).ToString()),
|
||||
new Claim(ClaimTypes.Role, role),
|
||||
],
|
||||
expires: DateTime.UtcNow.AddHours(1),
|
||||
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
|
||||
|
||||
var client = factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", new JwtSecurityTokenHandler().WriteToken(token));
|
||||
return client;
|
||||
}
|
||||
|
||||
public static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
|
||||
}
|
||||
|
||||
public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture<ClosedCmsSwitchContactHostFactory>
|
||||
{
|
||||
private const string Messages = "/api/v1/contact-messages";
|
||||
private const string Settings = "/api/v1/contact-settings";
|
||||
|
||||
private async Task<Guid> SeedAsync(ContactMessageStatus status, string name, int minutesAgo = 0)
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
await factory.WithDb(async db =>
|
||||
{
|
||||
db.ContactMessages.Add(new ContactMessage
|
||||
{
|
||||
Id = id, SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddMinutes(-minutesAgo),
|
||||
Name = name, Email = "x@example.nl", Subject = "website", Message = "Hallo",
|
||||
Status = status,
|
||||
MailStatus = status == ContactMessageStatus.Spam ? ContactMailStatus.NotApplicable : ContactMailStatus.Pending,
|
||||
RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
return 0;
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
// ---- authentication and authorization ----
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET", Messages)]
|
||||
[InlineData("GET", Settings)]
|
||||
[InlineData("PUT", Settings)]
|
||||
[InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")]
|
||||
public async Task EveryManagementRoute_RequiresLogin(string method, string url)
|
||||
{
|
||||
var request = new HttpRequestMessage(new HttpMethod(method), url);
|
||||
if (method is "PUT" or "PATCH")
|
||||
{
|
||||
request.Content = Jwt.Json("{}");
|
||||
}
|
||||
|
||||
var response = await factory.CreateClient().SendAsync(request);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET", Messages)]
|
||||
[InlineData("GET", Settings)]
|
||||
[InlineData("PUT", Settings)]
|
||||
[InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")]
|
||||
[InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")]
|
||||
public async Task EveryManagementRoute_IsForbidden_ForARegularUser(string method, string url)
|
||||
{
|
||||
var request = new HttpRequestMessage(new HttpMethod(method), url);
|
||||
if (method is "PUT" or "PATCH")
|
||||
{
|
||||
request.Content = Jwt.Json("""{"enabled":true,"status":"read"}""");
|
||||
}
|
||||
|
||||
var response = await Jwt.ClientWithRole(factory, "User").SendAsync(request);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task APutOnTheSwitchByANonAdmin_Is403_AndChangesNothing()
|
||||
{
|
||||
// The other tests in this class may have created the row; what matters is that this call changes nothing.
|
||||
var before = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync());
|
||||
|
||||
var response = await Jwt.ClientWithRole(factory, "User").PutAsync(Settings, Jwt.Json("""{"enabled":true}"""));
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
|
||||
var after = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync());
|
||||
after.Should().BeEquivalentTo(before);
|
||||
(await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
// ---- the switch ----
|
||||
|
||||
[Fact]
|
||||
public async Task TheCmsSwitch_IsOffByDefault_AndTheStateIsReportedWithTheHostSwitch()
|
||||
{
|
||||
var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true}""");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"enabled":"yes"}""")]
|
||||
[InlineData("""{"enabled":1}""")]
|
||||
[InlineData("""{"enabled":null}""")]
|
||||
[InlineData("{}")]
|
||||
[InlineData("not json")]
|
||||
[InlineData("")]
|
||||
public async Task APutWithoutABoolean_Is400_WithErrorsEnabled(string body)
|
||||
{
|
||||
var response = await Jwt.ClientWithRole(factory, "Administrator").PutAsync(Settings, Jwt.Json(body));
|
||||
|
||||
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());
|
||||
doc.RootElement.GetProperty("errors").GetProperty("enabled")[0].GetString().Should().Be("invalid");
|
||||
doc.RootElement.GetProperty("errors").EnumerateObject().Should().ContainSingle();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheSwitch_OpensAndClosesThePublicRoutes_AtOnce_WhileTheManagementRoutesKeepWorking()
|
||||
{
|
||||
var admin = Jwt.ClientWithRole(factory, "Administrator");
|
||||
var visitor = factory.CreateClient();
|
||||
|
||||
// Default: closed. 404 with an empty body, the website shows its mailto fallback.
|
||||
var closed = await visitor.GetAsync($"{Messages}/token");
|
||||
closed.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
(await closed.Content.ReadAsStringAsync()).Should().BeEmpty();
|
||||
|
||||
var on = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":true}"""));
|
||||
on.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true}""");
|
||||
(await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
|
||||
var off = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":false}"""));
|
||||
off.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
var post = await visitor.PostAsync(Messages, Jwt.Json("{}"));
|
||||
post.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
(await post.Content.ReadAsStringAsync()).Should().BeEmpty();
|
||||
|
||||
// The management side is never closed by the CMS switch.
|
||||
(await admin.GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await admin.GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheUserWhoChangedTheSwitch_IsRecorded()
|
||||
{
|
||||
var user = Guid.NewGuid();
|
||||
|
||||
await Jwt.ClientWithRole(factory, "Owner", user).PutAsync(Settings, Jwt.Json("""{"enabled":false}"""));
|
||||
|
||||
(await factory.WithDb(db => db.ContactSettings.AsNoTracking().SingleAsync())).UpdatedByUserId.Should().Be(user);
|
||||
}
|
||||
|
||||
// ---- messages ----
|
||||
|
||||
[Fact]
|
||||
public async Task TheMessageFlow_ListDetailStatusSpamDeleteResend()
|
||||
{
|
||||
var admin = Jwt.ClientWithRole(factory, "Administrator");
|
||||
var first = await SeedAsync(ContactMessageStatus.New, "Flow Eerste", minutesAgo: 10);
|
||||
var second = await SeedAsync(ContactMessageStatus.New, "Flow Tweede", minutesAgo: 5);
|
||||
var spam = await SeedAsync(ContactMessageStatus.Spam, "Flow Spam", minutesAgo: 1);
|
||||
|
||||
// Default list: no spam; unread counts only the new ones.
|
||||
using (var list = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync()))
|
||||
{
|
||||
var names = list.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()).ToList();
|
||||
names.Should().Contain(["Flow Eerste", "Flow Tweede"]).And.NotContain("Flow Spam");
|
||||
list.RootElement.GetProperty("unreadCount").GetInt32().Should().BeGreaterThanOrEqualTo(2);
|
||||
list.RootElement.GetProperty("items")[0].TryGetProperty("message", out _).Should().BeFalse("the list has no message text");
|
||||
}
|
||||
|
||||
// Spam apart.
|
||||
using (var spamList = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?status=spam")).Content.ReadAsStringAsync()))
|
||||
{
|
||||
spamList.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString())
|
||||
.Should().Equal("Flow Spam");
|
||||
}
|
||||
|
||||
// Detail.
|
||||
using (var detail = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}/{first}")).Content.ReadAsStringAsync()))
|
||||
{
|
||||
detail.RootElement.GetProperty("message").GetString().Should().Be("Hallo");
|
||||
detail.RootElement.GetProperty("status").GetString().Should().Be("new");
|
||||
detail.RootElement.GetProperty("mailStatus").GetString().Should().Be("pending");
|
||||
}
|
||||
|
||||
// Status change.
|
||||
var patch = await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"read"}"""));
|
||||
patch.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await patch.Content.ReadAsStringAsync()).Should().Contain("\"status\":\"read\"");
|
||||
(await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"spam"}"""))).StatusCode.Should().Be(HttpStatusCode.BadRequest);
|
||||
|
||||
// Resend: spam is refused, a regular message answers (no mail sender yet: mailed=false).
|
||||
(await admin.PostAsync($"{Messages}/{spam}/resend", null)).StatusCode.Should().Be(HttpStatusCode.Conflict);
|
||||
var resend = await admin.PostAsync($"{Messages}/{second}/resend", null);
|
||||
resend.StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
(await resend.Content.ReadAsStringAsync()).Should().Be("""{"mailStatus":"pending","mailAttempts":0,"mailed":false}""");
|
||||
|
||||
// Not spam after all: now in the default list.
|
||||
(await admin.PatchAsync($"{Messages}/{spam}", Jwt.Json("""{"status":"archived"}"""))).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
using (var again = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync()))
|
||||
{
|
||||
again.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString())
|
||||
.Should().Contain("Flow Spam");
|
||||
}
|
||||
|
||||
// Delete.
|
||||
(await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NoContent);
|
||||
(await admin.GetAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
(await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("?page=0")]
|
||||
[InlineData("?pageSize=101")]
|
||||
[InlineData("?status=bogus")]
|
||||
[InlineData("?page=abc")]
|
||||
public async Task ABadListQuery_Is400_InTheContractShape(string query)
|
||||
{
|
||||
var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages + query);
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
|
||||
response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ABadStatusBody_Is400_WithErrorsStatus()
|
||||
{
|
||||
var id = await SeedAsync(ContactMessageStatus.New, "Pipeline Patch");
|
||||
|
||||
var response = await Jwt.ClientWithRole(factory, "Administrator").PatchAsync($"{Messages}/{id}", Jwt.Json("""{"status":"nope"}"""));
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
|
||||
using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
doc.RootElement.GetProperty("errors").GetProperty("status")[0].GetString().Should().Be("invalid");
|
||||
}
|
||||
|
||||
// ---- the availability gate ----
|
||||
|
||||
[Fact]
|
||||
public async Task WhenTheCmsIsDisabled_TheManagementRoutesAreBlockedForVisitors_ButNotForAnAdministrator()
|
||||
{
|
||||
await factory.WithDb(db => db.Database.ExecuteSqlRawAsync(
|
||||
"INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')"));
|
||||
|
||||
// No marker on the management routes: anonymous callers meet the gate (503), not even a 401.
|
||||
(await factory.CreateClient().GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
|
||||
(await factory.CreateClient().GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
|
||||
(await Jwt.ClientWithRole(factory, "User").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
|
||||
|
||||
// By design a verified administrator can always reach a disabled CMS (to switch it back on).
|
||||
(await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK);
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactAdminHostSwitchPipelineTests(DisabledContactHostFactory factory) : IClassFixture<DisabledContactHostFactory>
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("GET", "/api/v1/contact-messages")]
|
||||
[InlineData("GET", "/api/v1/contact-settings")]
|
||||
public async Task WhileTheHostSwitchIsOff_TheManagementRoutesAre404_WithAnEmptyBody(string method, string url)
|
||||
{
|
||||
var response = await Jwt.ClientWithRole(factory, "Administrator").SendAsync(new HttpRequestMessage(new HttpMethod(method), url));
|
||||
|
||||
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
|
||||
(await response.Content.ReadAsStringAsync()).Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WhileTheHostSwitchIsOff_AnonymousCallersStillMeetAuthenticationFirst()
|
||||
{
|
||||
(await factory.CreateClient().GetAsync("/api/v1/contact-settings")).StatusCode.Should().Be(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactResendRateLimitPipelineTests(TightResendContactHostFactory factory) : IClassFixture<TightResendContactHostFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task Resend_Answers429_WithRetryAfter_AfterItsOwnLimit()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
await factory.WithDb(async db =>
|
||||
{
|
||||
db.ContactMessages.Add(new ContactMessage
|
||||
{
|
||||
Id = id, SiteId = "default", ReceivedAt = DateTimeOffset.UtcNow, Name = "n", Email = "e@example.nl",
|
||||
Subject = "s", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending,
|
||||
RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11),
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
return 0;
|
||||
});
|
||||
var admin = Jwt.ClientWithRole(factory, "Administrator");
|
||||
|
||||
HttpResponseMessage? last = null;
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
last = await admin.PostAsync($"/api/v1/contact-messages/{id}/resend", null);
|
||||
}
|
||||
|
||||
last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
|
||||
last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue();
|
||||
int.Parse(retryAfter!.Single()).Should().BeGreaterThanOrEqualTo(1);
|
||||
last.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user