De host controleert nu elk toegangstoken tegen een bestaande, actieve gebruiker met dezelfde security stamp, dus de pipelinetests maken een echte gebruiker met rol aan en loggen in via de authenticatieservice. Het OpenAPI-document is opnieuw gegenereerd met de routes van de gemergede master. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
364 lines
17 KiB
C#
364 lines
17 KiB
C#
|
|
using System.Net;
|
|
using System.Net.Http.Headers;
|
|
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using FluentAssertions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using SlpModularCms.Core.Identity.Entities;
|
|
using SlpModularCms.Core.Identity.Services;
|
|
using SlpModularCms.Modules.Contact.Data.Entities;
|
|
|
|
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
|
|
|
|
/// <summary>
|
|
/// Logs in the way the host itself does: a real, active user with the given role is created and
|
|
/// the host's own authentication service issues the access token. (The host checks every access
|
|
/// token against its user, so a hand-made token for a user that does not exist is refused.)
|
|
/// </summary>
|
|
internal static class Jwt
|
|
{
|
|
private const string Password = "Password1!";
|
|
|
|
public static HttpClient ClientWithRole(ContactHostFactory factory, string role, Guid? userId = null)
|
|
=> ClientWithRoleAsync(factory, role, userId).GetAwaiter().GetResult();
|
|
|
|
public static async Task<HttpClient> ClientWithRoleAsync(ContactHostFactory factory, string role, Guid? userId = null)
|
|
{
|
|
var id = userId ?? Guid.NewGuid();
|
|
var email = $"pipeline-{id:N}@example.test";
|
|
|
|
string accessToken;
|
|
await using (var scope = factory.Services.CreateAsyncScope())
|
|
{
|
|
var users = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
|
|
var roles = scope.ServiceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
|
|
if (!await roles.RoleExistsAsync(role))
|
|
{
|
|
// Roles normally appear with the first-run setup; a test host starts without one.
|
|
(await roles.CreateAsync(new ApplicationRole { Name = role })).Succeeded.Should().BeTrue();
|
|
}
|
|
|
|
if (await users.FindByIdAsync(id.ToString()) is null)
|
|
{
|
|
var user = new ApplicationUser { Id = id, UserName = email, Email = email, IsActive = true, DisplayName = email };
|
|
(await users.CreateAsync(user, Password)).Succeeded.Should().BeTrue();
|
|
(await users.AddToRoleAsync(user, role)).Succeeded.Should().BeTrue();
|
|
}
|
|
|
|
accessToken = (await scope.ServiceProvider.GetRequiredService<IAuthService>().AuthenticateAsync(email, Password)).AccessToken;
|
|
}
|
|
|
|
var client = factory.CreateClient();
|
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
|
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");
|
|
}
|
|
}
|