Contact: captcha-regio (global/eu) in de token-response en frame-src voor de StrictSite-CSP (CMS-U9 vervolg)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+5
@@ -6,3 +6,8 @@
|
||||
- Tests (new): verifier (request shape, EU URL, all answers, timeout, network error, cancellation, empty token, no secrets in logs), options validation, submission rule, pipeline with a fake provider (token response shape, spam vs genuine identical 202, missing token, fail-open 500/503/401, label with `& ' " < >`, start-up refusal), mail label encoding, ASF host tests (closed by default, public routes reachable while the gate is closed, per-client vs shared bucket, committed defaults), frontend label test.
|
||||
- NOT included (instruction): the `frame-src` CSP catalogue change (`AllowedSiteFrameOrigins`), parked as a patch; see handoff section 8 for the provider's CSP requirement.
|
||||
- Deviation found against the plan: the v2 widget needs `frame-src` (iframes); the "no frame-src" assumption was wrong. Also `sitekey_invalid` is HTTP 400 (not 401/403).
|
||||
|
||||
## Follow-up (owner decisions)
|
||||
- `frame-src` catalogue change committed: `SecurityHeaders:AllowedSiteFrameOrigins` (exact origins; StrictSite only; empty = byte-identical). 6 new Core tests (Core 645).
|
||||
- Region: `Contact:Captcha:Region` = `global` (default) | `eu`; token response `captcha` gains `apiEndpoint` (additive); VerifyUrl derived from the region, an explicit VerifyUrl must match it, an unknown region or a mismatch stops the host at start-up. Tests: options (default, eu, mismatches, unknown), pipeline (default global, eu, mismatch refuses to start), OpenAPI regenerated. Contact tests 313.
|
||||
- Privacy documented for both regions (handoff section 8).
|
||||
|
||||
@@ -117,7 +117,7 @@ Rebased onto `origin/master` `e671078` (merge of PR #11: identity-email-notifica
|
||||
## 8. CMS-U9 additions (Friendly Captcha v2 and the ASF host)
|
||||
|
||||
### Captcha contract (no wire change)
|
||||
- `GET /contact-messages/token` -> `captcha: null` while off, otherwise `{ "provider": "friendlycaptcha", "siteKey": "<public site key>" }`. Nothing else about the captcha (API key, verify URL) is ever returned.
|
||||
- `GET /contact-messages/token` -> `captcha: null` while off, otherwise `{ "provider": "friendlycaptcha", "siteKey": "<public site key>", "apiEndpoint": "global" | "eu" }`. `apiEndpoint` (additive, default `global`) is the widget's data region and follows `Contact:Captcha:Region`, so switching region needs no website rebuild. Nothing else about the captcha (API key, verify URL) is ever returned.
|
||||
- `POST /contact-messages`: `captchaToken` = the widget's response string (the widget also puts it in the form field `frc-captcha-response`). While the captcha is on, a **missing, empty or rejected** value is treated as spam: answer `202 {"status":"received"}` identical to a genuine message, stored with status `spam` (never a 400, so a bot learns nothing). While the captcha is off the field is ignored.
|
||||
- Verify (server side, Friendly Captcha **v2**): `POST https://global.frcapi.com/api/v2/captcha/siteverify` (EU-only: `https://eu.frcapi.com/api/v2/captcha/siteverify`), header `X-API-Key: <API key>`, JSON `{ "response": "...", "sitekey": "..." }`; `success:true` passes, `success:false` (HTTP 200 `response_invalid|response_timeout|response_duplicate`, or 400 `response_missing|bad_request`) = spam. Checked against developer.friendlycaptcha.com on 2026-11-10.
|
||||
- **Fail-open**: timeout (default 3 s), network error and 5xx let the visitor through (warning `captcha_unavailable`, kind only). Our own wrong API key or site key (HTTP 401, or 400 with `error_code: sitekey_invalid`) also lets the visitor through but logs an **error** `captcha_misconfigured`. The response token, the API key and the site key are never logged.
|
||||
@@ -129,15 +129,16 @@ Rebased onto `origin/master` `e671078` (merge of PR #11: identity-email-notifica
|
||||
| `Contact:Captcha:Provider` | `friendlycaptcha` (only supported value; case-insensitive) |
|
||||
| `Contact:Captcha:SiteKey` | public; sent to the browser |
|
||||
| `Contact__Captcha__Secret` | the API key; **environment variable / secrets manager only**, never committed |
|
||||
| `Contact:Captcha:VerifyUrl` | default global v2 URL; use the EU URL above for EU-only processing; must be https |
|
||||
| `Contact:Captcha:Region` | `global` (default) or `eu`; decides the verify host and the `apiEndpoint` announced to the widget. Unknown value = host refuses to start |
|
||||
| `Contact:Captcha:VerifyUrl` | optional override, normally empty (derived from Region); if set it must be https **and match the Region's host** (`global.frcapi.com` / `eu.frcapi.com`), otherwise the host refuses to start |
|
||||
| `Contact:Captcha:TimeoutSeconds` | default 3 (1-30) |
|
||||
|
||||
With `Contact:Enabled=true` and `Captcha:Enabled=true` the host **refuses to start** when provider, site key or secret is missing/invalid (the message names the setting only, never a value).
|
||||
|
||||
### Widget (website session) and CSP
|
||||
- Widget: Friendly Captcha v2 SDK with `sitekey` = `siteKey` from the token response; for the EU endpoint the widget needs `apiEndpoint: "eu"` (`data-api-endpoint="eu"`). The response goes into `captchaToken`. Exact SDK package/events: to be verified by the website session against the SDK docs.
|
||||
- **CSP**: the v2 widget renders in iframes. The provider's CSP guide says you need `frame-src https://*.frcapi.com` (global and EU). `StrictSite` currently has no `frame-src` (iframes fall back to `default-src 'self'` and are blocked). The additive catalogue change `SecurityHeaders:AllowedSiteFrameOrigins` (StrictSite only, absent = header byte-identical) is **prepared but NOT included in this unit**; waiting for the owner's decision on exact origins vs wildcard and on global vs EU. No `connect-src`/`script-src` additions are documented by the provider.
|
||||
- Privacy (provider statements, v2 docs): "Friendly Captcha does not rely on user tracking or cookies for its protection service"; the dedicated EU endpoint is "hosted in Germany" and "personal information (i.e. visitor IP addresses) never leave the EU". The site's privacy page must name the captcha provider and the processing of the visitor's IP address for the challenge.
|
||||
- **CSP** (decision: exact origins, no wildcard): the v2 widget renders in iframes and the provider's CSP guide requires `frame-src` for `*.frcapi.com`. New option `SecurityHeaders:AllowedSiteFrameOrigins` (StrictSite only; empty = header byte-identical to before; origins only, validated at start-up; the admin and relaxed policies never get it). ASF value for now: `SecurityHeaders__AllowedSiteFrameOrigins__0=https://global.frcapi.com`; add `https://eu.frcapi.com` as `__1` when the site switches to the EU region. The resulting directive is `frame-src 'self' https://global.frcapi.com`. No `connect-src`/`script-src` additions are documented by the provider; a browser test with the real widget is still needed.
|
||||
- Privacy (provider statements, v2 docs): "Friendly Captcha does not rely on user tracking or cookies for its protection service". **Region `global`**: the visitor's IP address can be processed outside the EU. **Region `eu`** (dedicated endpoint "hosted in Germany"; paid Advanced/Enterprise plan): "personal information (i.e. visitor IP addresses) never leave the EU". The site's privacy page must name the captcha provider, the processing of the visitor's IP address for the challenge, and which region is in use; commercial use needs a paid plan with the provider. For a test or a launch without a paid plan keep `Contact:Captcha:Enabled=false`.
|
||||
|
||||
### ASF host (`Api.AndreaSlopFotografie`)
|
||||
- References `Modules.Contact`; section `Contact` in its `appsettings.json` (`Enabled:false`, `SiteId: andreaslop`), the three contact rate-limit policies. Capabilities now list `Contact`; the module does nothing and touches no database while `Contact:Enabled=false`.
|
||||
|
||||
@@ -94,6 +94,10 @@
|
||||
},
|
||||
"ContactCaptchaInfo": {
|
||||
"properties": {
|
||||
"apiEndpoint": {
|
||||
"default": "global",
|
||||
"type": "string"
|
||||
},
|
||||
"provider": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -1807,7 +1811,7 @@
|
||||
},
|
||||
"/api/v1/contact-messages/token": {
|
||||
"get": {
|
||||
"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.",
|
||||
"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, apiEndpoint: \"global\"|\"eu\" } (Friendly Captcha v2; apiEndpoint is the widget's data region and follows the server configuration), which the website widget needs. Nothing else about the captcha (secret, verify URL) is ever returned.",
|
||||
"responses": {
|
||||
"200": {
|
||||
"content": {
|
||||
|
||||
@@ -136,3 +136,71 @@ public class StrictSitePolicyTests
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>NEW tests: the optional frame-src of the StrictSite policy (third-party iframes such as the captcha widget).</summary>
|
||||
public class StrictSiteFrameSourceTests
|
||||
{
|
||||
private const string Global = "https://global.frcapi.com";
|
||||
private const string Eu = "https://eu.frcapi.com";
|
||||
|
||||
[Fact]
|
||||
public void WithoutFrameOrigins_TheHeaderHasNoFrameSrc_AndIsUnchanged()
|
||||
{
|
||||
var plain = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [], [], ["https://a.example"], ["https://a.example"]);
|
||||
var explicitNone = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [], [], ["https://a.example"], ["https://a.example"], []);
|
||||
|
||||
plain.ContentSecurityPolicy.Should().NotContain("frame-src");
|
||||
explicitNone.Should().Be(plain);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void WithFrameOrigins_FrameSrcListsSelfAndThemOnly_BeforeObjectSrc()
|
||||
{
|
||||
var set = CspPolicyCatalog.Build(CspPolicyCatalog.StrictSite, [], [], null, null, [Global, Eu + "/"]);
|
||||
|
||||
set.ContentSecurityPolicy.Should().Contain($"frame-src 'self' {Global} {Eu}; object-src 'none'");
|
||||
set.ContentSecurityPolicy.Should().Contain("frame-ancestors 'none'");
|
||||
set.FrameOptions.Should().Be("DENY");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(CspPolicyCatalog.Strict)]
|
||||
[InlineData(CspPolicyCatalog.Relaxed)]
|
||||
public void TheAdminAndRelaxedPolicies_NeverGetTheFrameOrigins(string policy)
|
||||
{
|
||||
var set = CspPolicyCatalog.Build(policy, [], [], null, null, [Global]);
|
||||
|
||||
set.ContentSecurityPolicy.Should().NotContain("frcapi.com");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFrameOriginWithAPath_IsRejectedAtStartup()
|
||||
{
|
||||
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["SecurityHeaders:AllowedSiteFrameOrigins:0"] = "https://global.frcapi.com/some/path",
|
||||
}).Build();
|
||||
var services = new ServiceCollection();
|
||||
services.AddCmsSecurityHeaders(config);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
var act = () => provider.GetRequiredService<IOptions<SecurityHeadersOptions>>().Value;
|
||||
|
||||
act.Should().Throw<OptionsValidationException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheConfiguredFrameOrigins_ReachTheProvider()
|
||||
{
|
||||
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["SecurityHeaders:AllowedSiteFrameOrigins:0"] = Global,
|
||||
}).Build();
|
||||
var services = new ServiceCollection();
|
||||
services.AddCmsSecurityHeaders(config);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
provider.GetRequiredService<ICspPolicyProvider>().Get(CspPolicyCatalog.StrictSite)
|
||||
.ContentSecurityPolicy.Should().Contain($"frame-src 'self' {Global};");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,25 +47,43 @@ public static class CspPolicyCatalog
|
||||
IEnumerable<string> allowedScriptOrigins,
|
||||
IEnumerable<string> allowedConnectOrigins,
|
||||
IEnumerable<string>? allowedSiteScriptOrigins = null,
|
||||
IEnumerable<string>? allowedSiteConnectOrigins = null)
|
||||
IEnumerable<string>? allowedSiteConnectOrigins = null,
|
||||
IEnumerable<string>? allowedSiteFrameOrigins = null)
|
||||
{
|
||||
var connect = Join("'self'", allowedConnectOrigins);
|
||||
|
||||
if (StrictSite.Equals(policy, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var directives = new List<string>
|
||||
{
|
||||
"default-src 'self'",
|
||||
$"script-src {Join("'self'", allowedSiteScriptOrigins ?? [])}",
|
||||
// Same documented exception as Strict: inline style attributes only, no script.
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
$"connect-src {Join("'self'", allowedSiteConnectOrigins ?? [])}",
|
||||
};
|
||||
|
||||
// Only present when a site embeds a third party (for example the captcha widget's iframe); without
|
||||
// origins the header stays byte-for-byte what it was (frames then fall back to default-src 'self').
|
||||
var frames = (allowedSiteFrameOrigins ?? [])
|
||||
.Where(origin => !string.IsNullOrWhiteSpace(origin)).ToArray();
|
||||
if (frames.Length > 0)
|
||||
{
|
||||
directives.Add($"frame-src {Join("'self'", frames)}");
|
||||
}
|
||||
|
||||
directives.AddRange(
|
||||
[
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
]);
|
||||
|
||||
return new SecurityHeaderSet(
|
||||
ContentSecurityPolicy: string.Join("; ",
|
||||
"default-src 'self'",
|
||||
$"script-src {Join("'self'", allowedSiteScriptOrigins ?? [])}",
|
||||
// Same documented exception as Strict: inline style attributes only, no script.
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
$"connect-src {Join("'self'", allowedSiteConnectOrigins ?? [])}",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'"),
|
||||
ContentSecurityPolicy: string.Join("; ", directives),
|
||||
FrameOptions: "DENY",
|
||||
ReferrerPolicy: ReferrerPolicyValue);
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ public sealed class CspPolicyProvider : ICspPolicyProvider
|
||||
value.AllowedScriptOrigins,
|
||||
value.AllowedConnectOrigins,
|
||||
value.AllowedSiteScriptOrigins,
|
||||
value.AllowedSiteConnectOrigins),
|
||||
value.AllowedSiteConnectOrigins,
|
||||
value.AllowedSiteFrameOrigins),
|
||||
StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,8 @@ public static class SecurityHeadersExtensions
|
||||
$"SecurityHeaders:DefaultPolicy is not a known policy. Known policies: {string.Join(", ", CspPolicyCatalog.KnownPolicies)}.")
|
||||
.Validate(
|
||||
options => options.AllowedScriptOrigins.Concat(options.AllowedConnectOrigins)
|
||||
.Concat(options.AllowedSiteScriptOrigins).Concat(options.AllowedSiteConnectOrigins).All(IsOrigin),
|
||||
.Concat(options.AllowedSiteScriptOrigins).Concat(options.AllowedSiteConnectOrigins)
|
||||
.Concat(options.AllowedSiteFrameOrigins).All(IsOrigin),
|
||||
"SecurityHeaders origins must be absolute scheme-and-host values without a path, e.g. https://analytics.example.com.")
|
||||
// ValidateOnStart, not a constructor check: options resolve lazily, so without this
|
||||
// a typo in PathPolicies is discovered when the first request arrives — by which
|
||||
@@ -73,13 +74,15 @@ public static class SecurityHeadersExtensions
|
||||
logger.LogInformation(
|
||||
"HTTP security headers enabled. Default policy: {DefaultPolicy}. Path policies: {PathPolicies}. " +
|
||||
"Allowed script origins: {ScriptOrigins}. Allowed connect origins: {ConnectOrigins}. " +
|
||||
"Allowed site script origins: {SiteScriptOrigins}. Allowed site connect origins: {SiteConnectOrigins}.",
|
||||
"Allowed site script origins: {SiteScriptOrigins}. Allowed site connect origins: {SiteConnectOrigins}. " +
|
||||
"Allowed site frame origins: {SiteFrameOrigins}.",
|
||||
options.DefaultPolicy,
|
||||
string.Join(", ", options.PathPolicies.Select(rule => $"{rule.PathPrefix} => {rule.Policy}")),
|
||||
Describe(options.AllowedScriptOrigins),
|
||||
Describe(options.AllowedConnectOrigins),
|
||||
Describe(options.AllowedSiteScriptOrigins),
|
||||
Describe(options.AllowedSiteConnectOrigins));
|
||||
Describe(options.AllowedSiteConnectOrigins),
|
||||
Describe(options.AllowedSiteFrameOrigins));
|
||||
|
||||
return app.UseMiddleware<SecurityHeadersMiddleware>();
|
||||
}
|
||||
|
||||
@@ -70,6 +70,13 @@ public sealed class SecurityHeadersOptions
|
||||
/// analytics and error-reporting hosts called directly by the website).
|
||||
/// </summary>
|
||||
public IList<string> AllowedSiteConnectOrigins { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Origins added as a <c>frame-src</c> directive under the <c>StrictSite</c> policy only (for example the Friendly
|
||||
/// Captcha widget, which renders in an iframe: <c>https://global.frcapi.com</c>, <c>https://eu.frcapi.com</c>).
|
||||
/// Empty (the default) adds no <c>frame-src</c> at all, so existing headers are unchanged.
|
||||
/// </summary>
|
||||
public IList<string> AllowedSiteFrameOrigins { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>One entry in <see cref="SecurityHeadersOptions.PathPolicies"/>.</summary>
|
||||
|
||||
@@ -74,7 +74,7 @@ public class FriendlyCaptchaVerifierTests
|
||||
{
|
||||
var handler = FakeCaptchaHandler.Always(HttpStatusCode.OK, """{"success":true}""");
|
||||
|
||||
await Verifier(handler, c => c.VerifyUrl = "https://eu.frcapi.com/api/v2/captcha/siteverify")
|
||||
await Verifier(handler, c => c.Region = "eu")
|
||||
.VerifyAsync(Token, CancellationToken.None);
|
||||
|
||||
handler.Calls.Single().Request.RequestUri!.Host.Should().Be("eu.frcapi.com");
|
||||
@@ -224,6 +224,63 @@ public class ContactCaptchaOptionsTests
|
||||
problems.Single().Should().NotContain("key").And.NotContain("insecure");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheRegionDefaultsToGlobal_AndDerivesTheVerifyUrl()
|
||||
{
|
||||
var o = Valid();
|
||||
|
||||
o.ApiEndpoint.Should().Be("global");
|
||||
o.EffectiveVerifyUrl.Should().Be("https://global.frcapi.com/api/v2/captcha/siteverify");
|
||||
o.Problems().Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheEuRegion_DerivesTheEuVerifyUrl_AndAnnouncesEu()
|
||||
{
|
||||
var o = Valid();
|
||||
o.Region = "EU";
|
||||
|
||||
o.ApiEndpoint.Should().Be("eu");
|
||||
o.EffectiveVerifyUrl.Should().Be("https://eu.frcapi.com/api/v2/captcha/siteverify");
|
||||
o.Problems().Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("global", "https://eu.frcapi.com/api/v2/captcha/siteverify")]
|
||||
[InlineData("eu", "https://global.frcapi.com/api/v2/captcha/siteverify")]
|
||||
[InlineData("global", "https://evil.example/api/v2/captcha/siteverify")]
|
||||
public void AVerifyUrlThatDoesNotMatchTheRegion_RefusesToStart(string region, string url)
|
||||
{
|
||||
var o = Valid();
|
||||
o.Region = region;
|
||||
o.VerifyUrl = url;
|
||||
|
||||
o.Problems().Should().ContainSingle().Which.Should().Contain("does not match Contact:Captcha:Region");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AMatchingVerifyUrl_IsAccepted_AndUsed()
|
||||
{
|
||||
var o = Valid();
|
||||
o.Region = "eu";
|
||||
o.VerifyUrl = "https://eu.frcapi.com/api/v2/captcha/siteverify";
|
||||
|
||||
o.Problems().Should().BeEmpty();
|
||||
o.EffectiveVerifyUrl.Should().Be("https://eu.frcapi.com/api/v2/captcha/siteverify");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("us")]
|
||||
[InlineData("")]
|
||||
[InlineData("europe")]
|
||||
public void AnUnknownRegion_RefusesToStart(string region)
|
||||
{
|
||||
var o = Valid();
|
||||
o.Region = region;
|
||||
|
||||
o.Problems().Should().ContainSingle().Which.Should().Contain("Contact:Captcha:Region");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheProviderNameIsCaseInsensitive()
|
||||
{
|
||||
|
||||
@@ -20,7 +20,7 @@ public sealed class CaptchaContactHostFactory() : ContactHostFactory(new()
|
||||
["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",
|
||||
["Contact:Captcha:Region"] = "eu",
|
||||
["RateLimiting:ContactForm:PermitLimit"] = "1000",
|
||||
["RateLimiting:ContactToken:PermitLimit"] = "1000",
|
||||
})
|
||||
@@ -72,7 +72,8 @@ public class ContactCaptchaPipelineTests(CaptchaContactHostFactory factory) : IC
|
||||
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);
|
||||
captcha.GetProperty("apiEndpoint").GetString().Should().Be("eu");
|
||||
captcha.EnumerateObject().Should().HaveCount(3);
|
||||
text.Should().NotContain("pipeline-secret-ZXQ").And.NotContain("frcapi.com");
|
||||
}
|
||||
|
||||
@@ -158,6 +159,71 @@ public class ContactCaptchaPipelineTests(CaptchaContactHostFactory factory) : IC
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>No Region configured: the default, global.</summary>
|
||||
public sealed class GlobalCaptchaContactHostFactory() : ContactHostFactory(new()
|
||||
{
|
||||
["Contact:Enabled"] = "true",
|
||||
["Contact:SiteId"] = "pipeline-site",
|
||||
["Contact:MinSeconds"] = "0",
|
||||
["Contact:Captcha:Enabled"] = "true",
|
||||
["Contact:Captcha:Provider"] = "friendlycaptcha",
|
||||
["Contact:Captcha:SiteKey"] = "FCMGLOBALKEY",
|
||||
["Contact:Captcha:Secret"] = "pipeline-secret-ZXQ",
|
||||
})
|
||||
{
|
||||
protected override bool OpenCmsSwitch => true;
|
||||
}
|
||||
|
||||
public class GlobalCaptchaRegionPipelineTests(GlobalCaptchaContactHostFactory factory) : IClassFixture<GlobalCaptchaContactHostFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task WithoutARegion_TheTokenResponseAnnouncesTheGlobalEndpoint()
|
||||
{
|
||||
var response = await factory.CreateClient().GetAsync($"{Http.Route}/token");
|
||||
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
var captcha = json.RootElement.GetProperty("captcha");
|
||||
captcha.GetProperty("apiEndpoint").GetString().Should().Be("global");
|
||||
captcha.GetProperty("siteKey").GetString().Should().Be("FCMGLOBALKEY");
|
||||
}
|
||||
}
|
||||
|
||||
public class CaptchaOffTokenTests(EnabledContactHostFactory factory) : IClassFixture<EnabledContactHostFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task WithTheCaptchaOff_TheTokenResponseHasNoCaptcha()
|
||||
{
|
||||
var response = await factory.CreateClient().GetAsync($"{Http.Route}/token");
|
||||
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
json.RootElement.GetProperty("captcha").ValueKind.Should().Be(JsonValueKind.Null);
|
||||
}
|
||||
}
|
||||
|
||||
public class CaptchaInconsistentRegionStartupTests
|
||||
{
|
||||
private sealed class InconsistentFactory() : ContactHostFactory(new()
|
||||
{
|
||||
["Contact:Enabled"] = "true",
|
||||
["Contact:Captcha:Enabled"] = "true",
|
||||
["Contact:Captcha:Provider"] = "friendlycaptcha",
|
||||
["Contact:Captcha:SiteKey"] = "FCMKEY",
|
||||
["Contact:Captcha:Secret"] = "pipeline-secret-ZXQ",
|
||||
["Contact:Captcha:Region"] = "global",
|
||||
["Contact:Captcha:VerifyUrl"] = "https://eu.frcapi.com/api/v2/captcha/siteverify",
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public void ARegionThatContradictsTheVerifyUrl_RefusesToStart()
|
||||
{
|
||||
using var factory = new InconsistentFactory();
|
||||
|
||||
var act = () => factory.CreateClient();
|
||||
|
||||
act.Should().Throw<Exception>().Where(e => e.ToString().Contains("does not match Contact:Captcha:Region"));
|
||||
}
|
||||
}
|
||||
|
||||
public class CaptchaStartupTests
|
||||
{
|
||||
private sealed class MissingSecretFactory() : ContactHostFactory(new()
|
||||
|
||||
@@ -89,7 +89,9 @@ public sealed class ContactOptionsValidator : Microsoft.Extensions.Options.IVali
|
||||
public class ContactCaptchaOptions
|
||||
{
|
||||
public const string FriendlyCaptcha = "friendlycaptcha";
|
||||
public const string DefaultVerifyUrl = "https://global.frcapi.com/api/v2/captcha/siteverify";
|
||||
public const string Global = "global";
|
||||
public const string Eu = "eu";
|
||||
private const string VerifyPath = "/api/v2/captcha/siteverify";
|
||||
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
@@ -102,8 +104,24 @@ public class ContactCaptchaOptions
|
||||
/// <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>
|
||||
/// Which Friendly Captcha endpoint this site uses: <c>global</c> (default) or <c>eu</c> (the dedicated EU endpoint,
|
||||
/// a paid plan). It decides the verify host here and is announced to the widget as <c>apiEndpoint</c>, so the
|
||||
/// website needs no rebuild to switch.
|
||||
/// </summary>
|
||||
public string Region { get; set; } = Global;
|
||||
|
||||
/// <summary>Optional override of the verify URL; empty = derived from <see cref="Region"/>. If set it must match the region.</summary>
|
||||
public string? VerifyUrl { get; set; }
|
||||
|
||||
/// <summary><c>global</c> or <c>eu</c>, normalised (an unknown value falls back to <c>global</c>; start-up validation rejects it first).</summary>
|
||||
public string ApiEndpoint =>
|
||||
string.Equals(Region?.Trim(), Eu, StringComparison.OrdinalIgnoreCase) ? Eu : Global;
|
||||
|
||||
private string RegionHost => ApiEndpoint == Eu ? "eu.frcapi.com" : "global.frcapi.com";
|
||||
|
||||
public string EffectiveVerifyUrl =>
|
||||
string.IsNullOrWhiteSpace(VerifyUrl) ? $"https://{RegionHost}{VerifyPath}" : VerifyUrl.Trim();
|
||||
|
||||
/// <summary>A provider that does not answer within this time counts as passed (fail-open).</summary>
|
||||
public int TimeoutSeconds { get; set; } = 3;
|
||||
@@ -119,8 +137,16 @@ public class ContactCaptchaOptions
|
||||
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.");
|
||||
var region = Region?.Trim();
|
||||
if (!string.Equals(region, Global, StringComparison.OrdinalIgnoreCase) && !string.Equals(region, Eu, StringComparison.OrdinalIgnoreCase))
|
||||
problems.Add("Contact:Captcha:Region must be 'global' or 'eu'.");
|
||||
if (!string.IsNullOrWhiteSpace(VerifyUrl))
|
||||
{
|
||||
if (!Uri.TryCreate(VerifyUrl.Trim(), UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps)
|
||||
problems.Add("Contact:Captcha:VerifyUrl must be an absolute https URL.");
|
||||
else if (!string.Equals(uri.Host, RegionHost, StringComparison.OrdinalIgnoreCase) && problems.All(p => !p.Contains(":Region")))
|
||||
problems.Add("Contact:Captcha:VerifyUrl does not match Contact:Captcha:Region (leave VerifyUrl empty to derive it).");
|
||||
}
|
||||
if (TimeoutSeconds is < 1 or > 30) problems.Add("Contact:Captcha:TimeoutSeconds must be between 1 and 30.");
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ public class ContactMessagesController(
|
||||
var settings = options.Value;
|
||||
// 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!)
|
||||
? new ContactCaptchaInfo(ContactCaptchaOptions.FriendlyCaptcha, c.SiteKey!, c.ApiEndpoint)
|
||||
: null;
|
||||
|
||||
return Ok(new ContactTokenResponse(tokens.Issue(), settings.MinSeconds, captcha));
|
||||
|
||||
@@ -17,7 +17,8 @@ public record ContactMessageRequest(
|
||||
string? CaptchaToken);
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactCaptchaInfo(string Provider, string SiteKey);
|
||||
/// <summary>What the website widget needs. <c>ApiEndpoint</c> is <c>global</c> or <c>eu</c> (Friendly Captcha data region).</summary>
|
||||
public record ContactCaptchaInfo(string Provider, string SiteKey, string ApiEndpoint = "global");
|
||||
|
||||
[ExcludeFromCodeCoverage]
|
||||
public record ContactTokenResponse(string Token, int MinSeconds, ContactCaptchaInfo? Captcha);
|
||||
|
||||
@@ -32,7 +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.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, apiEndpoint: \"global\"|\"eu\" } (Friendly Captcha v2; apiEndpoint is the widget's data region and follows the server configuration), 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);
|
||||
|
||||
@@ -49,7 +49,7 @@ public sealed class FriendlyCaptchaVerifier(
|
||||
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, captcha.VerifyUrl)
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, captcha.EffectiveVerifyUrl)
|
||||
{
|
||||
Content = JsonContent.Create(new VerifyRequest(captchaToken, captcha.SiteKey ?? string.Empty)),
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user