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:
@@ -73,12 +73,55 @@ public class ContactMailOptions
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Start-up validation: only checks anything while the module and the captcha are switched on.</summary>
|
||||
public sealed class ContactOptionsValidator : Microsoft.Extensions.Options.IValidateOptions<ContactOptions>
|
||||
{
|
||||
public Microsoft.Extensions.Options.ValidateOptionsResult Validate(string? name, ContactOptions options)
|
||||
{
|
||||
if (!options.Enabled) return Microsoft.Extensions.Options.ValidateOptionsResult.Success;
|
||||
var problems = options.Captcha.Problems();
|
||||
return problems.Count == 0
|
||||
? Microsoft.Extensions.Options.ValidateOptionsResult.Success
|
||||
: Microsoft.Extensions.Options.ValidateOptionsResult.Fail(problems);
|
||||
}
|
||||
}
|
||||
|
||||
public class ContactCaptchaOptions
|
||||
{
|
||||
public const string FriendlyCaptcha = "friendlycaptcha";
|
||||
public const string DefaultVerifyUrl = "https://global.frcapi.com/api/v2/captcha/siteverify";
|
||||
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>The captcha provider; the only supported value is <c>friendlycaptcha</c> (Friendly Captcha v2).</summary>
|
||||
public string? Provider { get; set; }
|
||||
|
||||
/// <summary>Public site key; it is also sent to the browser in the token response.</summary>
|
||||
public string? SiteKey { get; set; }
|
||||
|
||||
/// <summary>Server-side secret; supply it through the environment or a secrets manager, never committed.</summary>
|
||||
/// <summary>Server-side API key; supply it through the environment (<c>Contact__Captcha__Secret</c>) or a secrets manager, never committed.</summary>
|
||||
public string? Secret { get; set; }
|
||||
|
||||
/// <summary>Verify endpoint. Global by default; for the EU-only endpoint use <c>https://eu.frcapi.com/api/v2/captcha/siteverify</c>.</summary>
|
||||
public string VerifyUrl { get; set; } = DefaultVerifyUrl;
|
||||
|
||||
/// <summary>A provider that does not answer within this time counts as passed (fail-open).</summary>
|
||||
public int TimeoutSeconds { get; set; } = 3;
|
||||
|
||||
public bool IsFriendlyCaptcha =>
|
||||
string.Equals(Provider?.Trim(), FriendlyCaptcha, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The problems that stop the host from starting while the captcha is on (setting names only, never values).</summary>
|
||||
public IReadOnlyList<string> Problems()
|
||||
{
|
||||
if (!Enabled) return [];
|
||||
var problems = new List<string>();
|
||||
if (!IsFriendlyCaptcha) problems.Add("Contact:Captcha:Provider must be 'friendlycaptcha'.");
|
||||
if (string.IsNullOrWhiteSpace(SiteKey)) problems.Add("Contact:Captcha:SiteKey is required while the captcha is enabled.");
|
||||
if (string.IsNullOrWhiteSpace(Secret)) problems.Add("Contact:Captcha:Secret is required while the captcha is enabled (environment variable Contact__Captcha__Secret).");
|
||||
if (!Uri.TryCreate(VerifyUrl, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
|
||||
problems.Add("Contact:Captcha:VerifyUrl must be an absolute https URL.");
|
||||
if (TimeoutSeconds is < 1 or > 30) problems.Add("Contact:Captcha:TimeoutSeconds must be between 1 and 30.");
|
||||
return problems;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,10 @@ public class ContactModule : IModule
|
||||
{
|
||||
services.AddOptions<ContactOptions>()
|
||||
.Configure<IConfiguration>((options, config) =>
|
||||
config.GetSection(ContactOptions.SectionName).Bind(options));
|
||||
config.GetSection(ContactOptions.SectionName).Bind(options))
|
||||
.ValidateOnStart();
|
||||
// A switched-on captcha with missing settings stops the host at start-up (setting names only, never a value).
|
||||
services.AddSingleton<IValidateOptions<ContactOptions>, ContactOptionsValidator>();
|
||||
|
||||
services.AddDbContext<ContactDbContext>((serviceProvider, options) =>
|
||||
{
|
||||
@@ -43,7 +46,14 @@ public class ContactModule : IModule
|
||||
services.AddScoped<IContactRepository, ContactRepository>();
|
||||
services.AddScoped<IContactSubmissionService, ContactSubmissionService>();
|
||||
services.AddSingleton<IContactTokenService, ContactTokenService>();
|
||||
services.AddSingleton<ICaptchaVerifier, NullCaptchaVerifier>();
|
||||
// Captcha: the provider is chosen by configuration; while it is off (or unset) everything passes.
|
||||
services.AddHttpClient(FriendlyCaptchaVerifier.HttpClientName);
|
||||
services.AddSingleton<FriendlyCaptchaVerifier>();
|
||||
services.AddSingleton<NullCaptchaVerifier>();
|
||||
services.AddSingleton<ICaptchaVerifier>(sp =>
|
||||
sp.GetRequiredService<IOptions<ContactOptions>>().Value.Captcha is { Enabled: true, IsFriendlyCaptcha: true }
|
||||
? sp.GetRequiredService<FriendlyCaptchaVerifier>()
|
||||
: sp.GetRequiredService<NullCaptchaVerifier>());
|
||||
// Mail: the request only stores and signals; the background service sends (and retries) with the host's mail pieces.
|
||||
services.AddScoped<IContactMailSender, ContactMailSender>();
|
||||
services.AddSingleton<IContactMailSignal, ContactMailSignal>();
|
||||
|
||||
@@ -37,8 +37,9 @@ public class ContactMessagesController(
|
||||
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)
|
||||
// Only a complete, supported captcha setup is announced; the secret and the verify URL are never part of a response.
|
||||
var captcha = settings.Captcha is { Enabled: true, IsFriendlyCaptcha: true } c && !string.IsNullOrWhiteSpace(c.SiteKey)
|
||||
? new ContactCaptchaInfo(ContactCaptchaOptions.FriendlyCaptcha, c.SiteKey!)
|
||||
: null;
|
||||
|
||||
return Ok(new ContactTokenResponse(tokens.Issue(), settings.MinSeconds, captcha));
|
||||
|
||||
@@ -32,6 +32,7 @@ public sealed class ContactOpenApiDocumentTransformer : IOpenApiDocumentTransfor
|
||||
if (document.Paths.TryGetValue(TokenPath, out var token) && token.Operations is not null
|
||||
&& token.Operations.TryGetValue(HttpMethod.Get, out var getToken))
|
||||
{
|
||||
getToken.Description = "Returns a signed form token and the minimum number of seconds before a submission counts as human. 'captcha' is null while the captcha is off; otherwise it is { provider: \"friendlycaptcha\", siteKey } (Friendly Captcha v2), which the website widget needs. Nothing else about the captcha (secret, verify URL) is ever returned.";
|
||||
getToken.Responses ??= [];
|
||||
getToken.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." };
|
||||
getToken.Responses["429"] = new OpenApiResponseReference("RateLimited", document);
|
||||
@@ -126,6 +127,7 @@ public sealed class ContactOpenApiDocumentTransformer : IOpenApiDocumentTransfor
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String, Format = "uuid" },
|
||||
});
|
||||
|
||||
submit.Description = "Stores a message. While the captcha is on, 'captchaToken' (the widget response) is required: a missing, empty or rejected value is treated as spam and answered exactly like a genuine message (202, stored with status spam), never with a 400. A captcha provider that does not answer in time, or fails, lets the visitor through (fail-open).";
|
||||
submit.Responses ??= [];
|
||||
submit.Responses["400"] = new OpenApiResponseReference("Validation", document);
|
||||
submit.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." };
|
||||
|
||||
@@ -90,7 +90,9 @@ public sealed class ContactSubmissionService(
|
||||
// 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));
|
||||
|| (o.Captcha.Enabled
|
||||
&& (string.IsNullOrWhiteSpace(request.CaptchaToken) // required while on: missing = spam, never a 400
|
||||
|| !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.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Verifies a Friendly Captcha v2 response server-side (POST {VerifyUrl}, header <c>X-API-Key</c>, JSON
|
||||
/// <c>{ response, sitekey }</c>). Only a definite negative answer counts as failed. Everything that is not the
|
||||
/// visitor's fault (timeout, network error, 5xx, our own wrong key or site key) lets the visitor through and is logged
|
||||
/// without personal data: the response token, the key and the secret are never logged.
|
||||
/// </summary>
|
||||
public sealed class FriendlyCaptchaVerifier(
|
||||
IHttpClientFactory httpClients,
|
||||
IOptions<ContactOptions> options,
|
||||
ILogger<FriendlyCaptchaVerifier> logger) : ICaptchaVerifier
|
||||
{
|
||||
public const string HttpClientName = "contact-captcha";
|
||||
public const string ApiKeyHeader = "X-API-Key";
|
||||
|
||||
private sealed record VerifyRequest(
|
||||
[property: JsonPropertyName("response")] string Response,
|
||||
[property: JsonPropertyName("sitekey")] string SiteKey);
|
||||
|
||||
private sealed class VerifyError
|
||||
{
|
||||
[JsonPropertyName("error_code")] public string? ErrorCode { get; set; }
|
||||
}
|
||||
|
||||
private sealed class VerifyResponse
|
||||
{
|
||||
[JsonPropertyName("success")] public bool Success { get; set; }
|
||||
[JsonPropertyName("error")] public VerifyError? Error { get; set; }
|
||||
}
|
||||
|
||||
public async Task<bool> VerifyAsync(string? captchaToken, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(captchaToken))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var captcha = options.Value.Captcha;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(Math.Clamp(captcha.TimeoutSeconds, 1, 30)));
|
||||
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, captcha.VerifyUrl)
|
||||
{
|
||||
Content = JsonContent.Create(new VerifyRequest(captchaToken, captcha.SiteKey ?? string.Empty)),
|
||||
};
|
||||
request.Headers.TryAddWithoutValidation(ApiKeyHeader, captcha.Secret);
|
||||
|
||||
using var response = await httpClients.CreateClient(HttpClientName).SendAsync(request, timeout.Token);
|
||||
var status = (int)response.StatusCode;
|
||||
|
||||
VerifyResponse? body = null;
|
||||
if (status < 500)
|
||||
{
|
||||
try
|
||||
{
|
||||
body = await response.Content.ReadFromJsonAsync<VerifyResponse>(timeout.Token);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Not JSON: judged by the status code below.
|
||||
}
|
||||
}
|
||||
|
||||
if (status >= 500)
|
||||
{
|
||||
logger.LogWarning("captcha_unavailable status={Status}; letting the visitor through", status);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Our own configuration is wrong (API key or site key rejected): not the visitor's fault.
|
||||
if (status is 401 or 403 || body?.Error?.ErrorCode == "sitekey_invalid")
|
||||
{
|
||||
logger.LogError("captcha_misconfigured status={Status} code={Code}; letting the visitor through",
|
||||
status, body?.Error?.ErrorCode);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (response.IsSuccessStatusCode && body is { Success: true })
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// A definite no (wrong, expired or reused response, or a missing/bad request): spam.
|
||||
return false;
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
logger.LogWarning("captcha_unavailable reason=timeout; letting the visitor through");
|
||||
return true;
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
// Type only: the message could quote the URL.
|
||||
logger.LogWarning("captcha_unavailable reason=network exception={ExceptionType}; letting the visitor through",
|
||||
ex.GetType().Name);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user