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:
2026-11-10 23:11:07 +01:00
co-authored by Claude Sonnet 5.5
parent 3275092401
commit 5378c21799
15 changed files with 291 additions and 34 deletions
@@ -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)),
};