Contact: Friendly Captcha v2, opstartvalidatie, ASF-host met Contact-module en hosttests (CMS-U9)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 23:06:23 +01:00
co-authored by Claude Sonnet 5.5
parent f43e00733a
commit 3275092401
20 changed files with 1052 additions and 21 deletions
@@ -107,6 +107,20 @@ public class ContactMailSenderTests
rig.Sent.TextBody.Should().Contain("regel2").And.Contain("Naam:");
}
[Fact]
public async Task ASubjectLabelWithSpecialCharacters_IsEncodedInTheBody_AndNeverReachesTheSubjectOrAHeader()
{
var rig = new Rig();
const string label = "Fotoshoot & <b>\"bruiloft\"</b> 'zomer'";
await rig.Build().SendAsync(Message(subject: label), CancellationToken.None);
rig.Sent!.Subject.Should().Be("Nieuw bericht via De Site");
rig.Sent.HtmlBody.Should().Contain("Fotoshoot &amp; &lt;b&gt;").And.NotContain("<b>\"bruiloft\"");
rig.Sent.TextBody.Should().Contain(" " + label);
rig.Sent.ReplyToAddress.Should().Be(Visitor);
}
[Fact]
public async Task English_UsesEnglishLabelsAndSubject()
{
@@ -0,0 +1,276 @@
using System.Net;
using System.Text;
using FluentAssertions;
using NSubstitute;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Contact.Config;
using SlpModularCms.Modules.Contact.Models;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests;
/// <summary>A stand-in for the provider: never touches the network. Records every request it receives.</summary>
public sealed class FakeCaptchaHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> respond) : HttpMessageHandler
{
public List<(HttpRequestMessage Request, string Body)> Calls { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(cancellationToken);
lock (Calls) Calls.Add((request, body));
return await respond(request, cancellationToken);
}
public static HttpResponseMessage Json(HttpStatusCode status, string json) =>
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
public static FakeCaptchaHandler Always(HttpStatusCode status, string json) => new((_, _) => Task.FromResult(Json(status, json)));
}
public class FriendlyCaptchaVerifierTests
{
private const string Secret = "ZXQ-secret-key";
private const string SiteKey = "FCMZXQ-site";
private const string Token = "ZXQ-captcha-response";
private sealed class Factory(HttpMessageHandler handler) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
}
private readonly CapturingLoggerProvider _logs = new();
private FriendlyCaptchaVerifier Verifier(HttpMessageHandler handler, Action<ContactCaptchaOptions>? configure = null)
{
var captcha = new ContactCaptchaOptions
{
Enabled = true, Provider = "friendlycaptcha", SiteKey = SiteKey, Secret = Secret, TimeoutSeconds = 1,
};
configure?.Invoke(captcha);
return new FriendlyCaptchaVerifier(
new Factory(handler),
Options.Create(new ContactOptions { Enabled = true, Captcha = captcha }),
LoggerFactory.Create(b => b.AddProvider(_logs)).CreateLogger<FriendlyCaptchaVerifier>());
}
[Fact]
public async Task ASuccessfulAnswer_Passes_AndTheRequestIsExactlyWhatTheProviderExpects()
{
var handler = FakeCaptchaHandler.Always(HttpStatusCode.OK, """{"success":true,"data":{"event_id":"e"}}""");
(await Verifier(handler).VerifyAsync(Token, CancellationToken.None)).Should().BeTrue();
var (request, body) = handler.Calls.Should().ContainSingle().Subject;
request.Method.Should().Be(HttpMethod.Post);
request.RequestUri!.ToString().Should().Be("https://global.frcapi.com/api/v2/captcha/siteverify");
request.Headers.GetValues("X-API-Key").Should().ContainSingle().Which.Should().Be(Secret);
request.Content!.Headers.ContentType!.MediaType.Should().Be("application/json");
body.Should().Be($$"""{"response":"{{Token}}","sitekey":"{{SiteKey}}"}""");
}
[Fact]
public async Task TheEuEndpoint_IsUsedWhenConfigured()
{
var handler = FakeCaptchaHandler.Always(HttpStatusCode.OK, """{"success":true}""");
await Verifier(handler, c => c.VerifyUrl = "https://eu.frcapi.com/api/v2/captcha/siteverify")
.VerifyAsync(Token, CancellationToken.None);
handler.Calls.Single().Request.RequestUri!.Host.Should().Be("eu.frcapi.com");
}
[Theory]
[InlineData(HttpStatusCode.OK, """{"success":false,"error":{"error_code":"response_invalid","detail":"x"}}""")]
[InlineData(HttpStatusCode.OK, """{"success":false,"error":{"error_code":"response_duplicate"}}""")]
[InlineData(HttpStatusCode.OK, """{"success":false,"error":{"error_code":"response_timeout"}}""")]
[InlineData(HttpStatusCode.BadRequest, """{"success":false,"error":{"error_code":"response_missing"}}""")]
[InlineData(HttpStatusCode.BadRequest, """{"success":false,"error":{"error_code":"bad_request"}}""")]
[InlineData(HttpStatusCode.OK, "not json at all")]
[InlineData(HttpStatusCode.OK, "{}")]
public async Task ADefiniteNo_IsSpam(HttpStatusCode status, string json)
{
var handler = FakeCaptchaHandler.Always(status, json);
(await Verifier(handler).VerifyAsync(Token, CancellationToken.None)).Should().BeFalse();
}
[Theory]
[InlineData(HttpStatusCode.Unauthorized, """{"success":false,"error":{"error_code":"auth_invalid"}}""")]
[InlineData(HttpStatusCode.Forbidden, "")]
[InlineData(HttpStatusCode.BadRequest, """{"success":false,"error":{"error_code":"sitekey_invalid"}}""")]
public async Task OurOwnWrongKeyOrSiteKey_LetsTheVisitorThrough_AndLogsAnError(HttpStatusCode status, string json)
{
var handler = FakeCaptchaHandler.Always(status, json);
(await Verifier(handler).VerifyAsync(Token, CancellationToken.None)).Should().BeTrue();
_logs.Messages.Should().Contain(m => m.Contains("captcha_misconfigured"));
}
[Theory]
[InlineData(HttpStatusCode.InternalServerError)]
[InlineData(HttpStatusCode.BadGateway)]
[InlineData(HttpStatusCode.ServiceUnavailable)]
public async Task AProviderServerError_FailsOpen_WithAWarning(HttpStatusCode status)
{
var handler = FakeCaptchaHandler.Always(status, "");
(await Verifier(handler).VerifyAsync(Token, CancellationToken.None)).Should().BeTrue();
_logs.Messages.Should().Contain(m => m.Contains("captcha_unavailable"));
}
[Fact]
public async Task ATimeout_FailsOpen()
{
var handler = new FakeCaptchaHandler(async (_, ct) =>
{
await Task.Delay(TimeSpan.FromSeconds(30), ct);
return FakeCaptchaHandler.Json(HttpStatusCode.OK, """{"success":true}""");
});
var verdict = await Verifier(handler).VerifyAsync(Token, CancellationToken.None);
verdict.Should().BeTrue();
_logs.Messages.Should().Contain(m => m.Contains("captcha_unavailable") && m.Contains("timeout"));
}
[Fact]
public async Task ANetworkError_FailsOpen_AndTheLogHasNoUrlOrToken()
{
var handler = new FakeCaptchaHandler((_, _) => throw new HttpRequestException("cannot reach https://global.frcapi.com with " + Token));
(await Verifier(handler).VerifyAsync(Token, CancellationToken.None)).Should().BeTrue();
_logs.Messages.Should().NotContain(m => m.Contains(Token) || m.Contains("frcapi.com"));
}
[Fact]
public async Task ACallerCancellation_IsNotSwallowed()
{
var handler = new FakeCaptchaHandler(async (_, ct) =>
{
await Task.Delay(TimeSpan.FromSeconds(30), ct);
return FakeCaptchaHandler.Json(HttpStatusCode.OK, "{}");
});
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));
var act = async () => await Verifier(handler, c => c.TimeoutSeconds = 20).VerifyAsync(Token, cts.Token);
await act.Should().ThrowAsync<OperationCanceledException>();
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task AnEmptyToken_FailsWithoutCallingTheProvider(string? token)
{
var handler = FakeCaptchaHandler.Always(HttpStatusCode.OK, """{"success":true}""");
(await Verifier(handler).VerifyAsync(token, CancellationToken.None)).Should().BeFalse();
handler.Calls.Should().BeEmpty();
}
[Fact]
public async Task NeitherTheSecretNorTheTokenIsEverLogged()
{
foreach (var status in new[] { HttpStatusCode.OK, HttpStatusCode.Unauthorized, HttpStatusCode.InternalServerError })
{
await Verifier(FakeCaptchaHandler.Always(status, """{"success":false}""")).VerifyAsync(Token, CancellationToken.None);
}
_logs.Messages.Should().NotContain(m => m.Contains(Secret) || m.Contains(Token) || m.Contains(SiteKey));
}
}
public class ContactCaptchaOptionsTests
{
private static ContactCaptchaOptions Valid() => new()
{
Enabled = true, Provider = "friendlycaptcha", SiteKey = "FCM-site", Secret = "key",
};
[Fact]
public void WhileOff_NothingIsRequired() => new ContactCaptchaOptions().Problems().Should().BeEmpty();
[Fact]
public void ACompleteSetup_HasNoProblems() => Valid().Problems().Should().BeEmpty();
[Theory]
[InlineData("provider")]
[InlineData("sitekey")]
[InlineData("secret")]
[InlineData("url")]
[InlineData("timeout")]
public void EachMissingOrInvalidSetting_IsReportedByName_NeverByValue(string which)
{
var o = Valid();
switch (which)
{
case "provider": o.Provider = "other"; break;
case "sitekey": o.SiteKey = ""; break;
case "secret": o.Secret = null; break;
case "url": o.VerifyUrl = "http://insecure.example"; break;
default: o.TimeoutSeconds = 0; break;
}
var problems = o.Problems();
problems.Should().ContainSingle();
problems.Single().Should().Contain("Contact:Captcha:");
problems.Single().Should().NotContain("key").And.NotContain("insecure");
}
[Fact]
public void TheProviderNameIsCaseInsensitive()
{
var o = Valid();
o.Provider = "FriendlyCaptcha";
o.IsFriendlyCaptcha.Should().BeTrue();
}
}
public class CaptchaSubmissionRuleTests
{
[Fact]
public async Task WhileOn_AMissingToken_IsSpam_AndTheProviderIsNotAsked()
{
using var h = new SubmissionHarness(o => o.Captcha.Enabled = true);
var result = await h.Submit(SubmissionHarness.Request(h.MatureToken(), captcha: null));
result.Should().BeOfType<SubmissionResult.Received>();
(await h.Db.ContactMessages.ToListAsyncForTests()).Single().Status.Should().Be(Data.Entities.ContactMessageStatus.Spam);
await h.Captcha.DidNotReceiveWithAnyArgs().VerifyAsync(default, default);
}
[Fact]
public async Task WhileOn_APresentToken_GoesToTheProvider()
{
using var h = new SubmissionHarness(o => o.Captcha.Enabled = true);
await h.Submit(SubmissionHarness.Request(h.MatureToken(), captcha: "solved"));
await h.Captcha.Received(1).VerifyAsync("solved", Arg.Any<CancellationToken>());
(await h.Db.ContactMessages.ToListAsyncForTests()).Single().Status.Should().Be(Data.Entities.ContactMessageStatus.New);
}
[Fact]
public async Task WhileOff_NoTokenIsNeeded()
{
using var h = new SubmissionHarness();
await h.Submit(SubmissionHarness.Request(h.MatureToken()));
(await h.Db.ContactMessages.ToListAsyncForTests()).Single().Status.Should().Be(Data.Entities.ContactMessageStatus.New);
}
}
internal static class QueryExtensions
{
public static Task<List<T>> ToListAsyncForTests<T>(this IQueryable<T> source) =>
Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync(source);
}
@@ -0,0 +1,181 @@
using System.Net;
using System.Text.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Modules.Contact.Data.Entities;
using SlpModularCms.Modules.Contact.Services;
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
/// <summary>The real host with Friendly Captcha switched on and a fake provider (no network).</summary>
public sealed class CaptchaContactHostFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:SiteId"] = "pipeline-site",
["Contact:MinSeconds"] = "0",
["Contact:Captcha:Enabled"] = "true",
["Contact:Captcha:Provider"] = "friendlycaptcha",
["Contact:Captcha:SiteKey"] = "FCMPIPELINEKEY",
["Contact:Captcha:Secret"] = "pipeline-secret-ZXQ",
["Contact:Captcha:VerifyUrl"] = "https://eu.frcapi.com/api/v2/captcha/siteverify",
["RateLimiting:ContactForm:PermitLimit"] = "1000",
["RateLimiting:ContactToken:PermitLimit"] = "1000",
})
{
/// <summary>What the fake provider answers next: status and JSON.</summary>
public volatile string Answer = """{"success":true}""";
public volatile int AnswerStatus = 200;
protected override bool OpenCmsSwitch => true;
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
var handler = new FakeCaptchaHandler((_, _) =>
Task.FromResult(FakeCaptchaHandler.Json((HttpStatusCode)AnswerStatus, Answer)));
Handler = handler;
builder.ConfigureTestServices(services =>
services.AddHttpClient(FriendlyCaptchaVerifier.HttpClientName)
.ConfigurePrimaryHttpMessageHandler(() => handler));
}
public FakeCaptchaHandler Handler { get; private set; } = null!;
}
public class ContactCaptchaPipelineTests(CaptchaContactHostFactory factory) : IClassFixture<CaptchaContactHostFactory>
{
private static string Body(string token, string name, string? captchaToken, string subject = "website", string message = "Ik wil graag een offerte.") =>
JsonSerializer.Serialize(new
{
name, email = "jan@example.nl", subject, message, hpCheck = "", token, captchaToken,
});
private async Task<(HttpResponseMessage Response, ContactMessage Row)> SubmitAsync(string name, string? captchaToken, string subject = "website", string message = "Ik wil graag een offerte.")
{
var client = factory.CreateClient();
var token = await Http.GetTokenAsync(client);
var response = await Http.PostAsync(client, Body(token, name, captchaToken, subject, message));
var row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == name));
return (response, row);
}
[Fact]
public async Task TheTokenResponse_AnnouncesTheProviderAndSiteKey_AndNothingElse()
{
var response = await factory.CreateClient().GetAsync($"{Http.Route}/token");
var text = await response.Content.ReadAsStringAsync();
using var json = JsonDocument.Parse(text);
var captcha = json.RootElement.GetProperty("captcha");
captcha.GetProperty("provider").GetString().Should().Be("friendlycaptcha");
captcha.GetProperty("siteKey").GetString().Should().Be("FCMPIPELINEKEY");
captcha.EnumerateObject().Should().HaveCount(2);
text.Should().NotContain("pipeline-secret-ZXQ").And.NotContain("frcapi.com");
}
[Fact]
public async Task AGoodAnswer_StoresAGenuineMessage_AndTheProviderGotTheKeyAndTheEuUrl()
{
factory.AnswerStatus = 200;
factory.Answer = """{"success":true}""";
var (response, row) = await SubmitAsync("Captcha Genuine", "solved-response");
response.StatusCode.Should().Be(HttpStatusCode.Accepted);
row.Status.Should().Be(ContactMessageStatus.New);
var (request, body) = factory.Handler.Calls.Last(c => c.Body.Contains("solved-response"));
request.RequestUri!.Host.Should().Be("eu.frcapi.com");
request.Headers.GetValues("X-API-Key").Single().Should().Be("pipeline-secret-ZXQ");
body.Should().Contain("FCMPIPELINEKEY");
}
[Fact]
public async Task ARejectedAnswer_IsSpam_WithTheSame202AndBodyAsAGenuineMessage()
{
factory.AnswerStatus = 200;
factory.Answer = """{"success":false,"error":{"error_code":"response_invalid"}}""";
var (spamResponse, spamRow) = await SubmitAsync("Captcha Spam", "bad-response");
factory.Answer = """{"success":true}""";
var (genuineResponse, _) = await SubmitAsync("Captcha Genuine Two", "good-response");
spamRow.Status.Should().Be(ContactMessageStatus.Spam);
spamRow.MailStatus.Should().Be(ContactMailStatus.NotApplicable);
spamResponse.StatusCode.Should().Be(HttpStatusCode.Accepted);
(await spamResponse.Content.ReadAsStringAsync()).Should().Be(await genuineResponse.Content.ReadAsStringAsync());
}
[Fact]
public async Task AMissingToken_IsSpam_Not400_AndTheProviderIsNotAsked()
{
var before = factory.Handler.Calls.Count;
var (response, row) = await SubmitAsync("Captcha Missing", null);
response.StatusCode.Should().Be(HttpStatusCode.Accepted);
row.Status.Should().Be(ContactMessageStatus.Spam);
factory.Handler.Calls.Count.Should().Be(before);
}
[Theory]
[InlineData(500)]
[InlineData(503)]
[InlineData(401)]
public async Task AProviderOutageOrOurWrongKey_FailsOpen_AndTheMessageIsGenuine(int status)
{
factory.AnswerStatus = status;
factory.Answer = "";
try
{
var (response, row) = await SubmitAsync($"Captcha Open {status}", "some-response");
response.StatusCode.Should().Be(HttpStatusCode.Accepted);
row.Status.Should().Be(ContactMessageStatus.New);
}
finally
{
factory.AnswerStatus = 200;
factory.Answer = """{"success":true}""";
}
}
[Fact]
public async Task ALabelWithSpecialCharacters_IsStoredAndListedAsTyped()
{
const string label = "Fotoshoot & <b>\"bruiloft\"</b> 'zomer'";
var (response, row) = await SubmitAsync("Captcha Label", "solved-response", subject: label, message: "Hallo <i>daar</i> & \"dag\"");
response.StatusCode.Should().Be(HttpStatusCode.Accepted);
row.Subject.Should().Be(label);
var admin = await Jwt.ClientWithRoleAsync(factory, "Administrator");
var list = await admin.GetStringAsync($"{Http.Route}?pageSize=100");
using var json = JsonDocument.Parse(list);
json.RootElement.GetProperty("items").EnumerateArray()
.Single(i => i.GetProperty("name").GetString() == "Captcha Label")
.GetProperty("subject").GetString().Should().Be(label);
}
}
public class CaptchaStartupTests
{
private sealed class MissingSecretFactory() : ContactHostFactory(new()
{
["Contact:Enabled"] = "true",
["Contact:Captcha:Enabled"] = "true",
["Contact:Captcha:Provider"] = "friendlycaptcha",
["Contact:Captcha:SiteKey"] = "FCMPIPELINEKEY",
});
[Fact]
public void ASwitchedOnCaptchaWithoutSecret_RefusesToStart_NamingTheSetting()
{
using var factory = new MissingSecretFactory();
var act = () => factory.CreateClient();
act.Should().Throw<Exception>()
.Where(e => e.ToString().Contains("Contact:Captcha:Secret") && !e.ToString().Contains("FCMPIPELINEKEY"));
}
}