From 887821b7e853be7b49153b960b883a5d12f06ee9 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Thu, 26 Nov 2026 12:49:31 -0800 Subject: [PATCH 1/3] fix: unblock Microsoft Clarity in CSP and send consent with correct keys The CSP allowed only www.clarity.ms, but Clarity's tag loads its tracker from scripts.clarity.ms, so the browser blocked Clarity for every visitor. Allow https://*.clarity.ms and https://c.bing.com per Clarity's CSP docs, and allow js.monitor.azure.com in connect-src for the Application Insights CDN config fetch. Clarity's consentv2 API reads ad_Storage/analytics_Storage (capital S) and silently ignores lowercase keys, so our consent signal was a no-op and consent only reached Clarity indirectly through Google Consent Mode. Send both keys with the documented casing (ads always denied) from clarity-manager.js only, and drop the duplicate call in consent-manager.js. Explicitly deny ad_storage, ad_user_data and ad_personalization in the gtag consent default, since unset consent types are treated as granted. Extract the CSP into Program.BuildContentSecurityPolicy so tests can check the analytics hosts; the header is only emitted outside Development. --- .../ContentSecurityPolicyTests.cs | 38 +++++++++++ EssentialCSharp.Web/Program.cs | 67 +++++++++++-------- .../Views/Shared/_Layout.cshtml | 5 ++ .../wwwroot/js/clarity-manager.js | 6 +- .../wwwroot/js/consent-manager.js | 25 ++----- 5 files changed, 90 insertions(+), 51 deletions(-) create mode 100644 EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs diff --git a/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs b/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs new file mode 100644 index 00000000..4822ac42 --- /dev/null +++ b/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs @@ -0,0 +1,38 @@ +using Microsoft.Extensions.Configuration; + +namespace EssentialCSharp.Web.Tests; + +/// +/// Guards the third-party hosts that analytics scripts need. A missing host fails silently in +/// production: the browser blocks the request and the tool simply records nothing. +/// The CSP header is only emitted outside Development, so these tests check the policy string directly. +/// +public class ContentSecurityPolicyTests +{ + [Test] + // Clarity's tag on www.clarity.ms loads its tracker from scripts.clarity.ms (and other + // [a-z].clarity.ms hosts). https://learn.microsoft.com/clarity/setup-and-installation/clarity-csp + [Arguments("script-src", "https://*.clarity.ms")] + [Arguments("script-src", "https://c.bing.com")] + [Arguments("connect-src", "https://*.clarity.ms")] + [Arguments("connect-src", "https://c.bing.com")] + // Application Insights loads its SDK from, and fetches its CDN config from, js.monitor.azure.com. + [Arguments("script-src", "js.monitor.azure.com")] + [Arguments("connect-src", "https://js.monitor.azure.com")] + [Arguments("script-src", "www.googletagmanager.com")] + [Arguments("connect-src", "https://*.google-analytics.com")] + public async Task ContentSecurityPolicy_AllowsAnalyticsHosts(string directive, string source) + { + IConfiguration configuration = new ConfigurationBuilder().Build(); + + string csp = Program.BuildContentSecurityPolicy(configuration); + + string[] sources = csp + .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + .FirstOrDefault(parts => parts.Length > 0 && parts[0] == directive) ?? []; + + await Assert.That(sources).IsNotEmpty(); + await Assert.That(sources.Skip(1)).Contains(source); + } +} diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index 4fffe529..f527aff6 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -400,35 +400,7 @@ await McpJsonRpcResponseWriter.WriteErrorAsync( app.UseForwardedHeaders(); } - // Build dynamic CSP — TryDotNet origin comes from runtime config - string? tryDotNetOrigin = app.Configuration["TryDotNet:Origin"]; - string tryDotNetSources = string.Empty; - if (!string.IsNullOrWhiteSpace(tryDotNetOrigin)) - { - if (Uri.TryCreate(tryDotNetOrigin, UriKind.Absolute, out Uri? tryDotNetUri)) - { - tryDotNetSources = $" {tryDotNetUri.GetLeftPart(UriPartial.Authority)}"; - } - else - { - LogIgnoringInvalidTryDotNetOrigin(app.Logger, tryDotNetOrigin); - } - } - - string csp = string.Join("; ", - $"default-src 'self'", - $"script-src 'self' 'unsafe-inline' cdn.jsdelivr.net www.clarity.ms www.googletagmanager.com js.monitor.azure.com https://hcaptcha.com https://*.hcaptcha.com{tryDotNetSources}", - $"style-src 'self' 'nonce-{CspNonce.Placeholder}' cdnjs.cloudflare.com fonts.googleapis.com https://hcaptcha.com https://*.hcaptcha.com", - $"style-src-attr 'unsafe-inline'", - $"font-src 'self' fonts.gstatic.com cdnjs.cloudflare.com", - $"img-src 'self' data: https:", - $"connect-src 'self' https://hcaptcha.com https://*.hcaptcha.com https://api.pwnedpasswords.com https://*.algolia.net https://*.algolianet.com https://*.google-analytics.com https://*.clarity.ms https://*.in.applicationinsights.azure.com{GetApplicationInsightsCspSources(app.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"], app.Logger)}{tryDotNetSources}", - $"frame-src https://hcaptcha.com https://*.hcaptcha.com https://newassets.hcaptcha.com{tryDotNetSources}", - $"worker-src blob:", - $"frame-ancestors 'none'", - $"base-uri 'self'", - $"form-action 'self' https://login.microsoftonline.com https://github.com" - ); + string csp = BuildContentSecurityPolicy(app.Configuration, app.Logger); SecurityHeadersBuilder securityHeaders = new SecurityHeadersBuilder() .AddDefaultSecurePolicy() @@ -574,6 +546,43 @@ private static bool IsMcpTransportRequest(HttpRequest request) => [LoggerMessage(Level = LogLevel.Warning, Message = "Application Insights connection string has a non-HTTPS or unparseable IngestionEndpoint value ({Endpoint}); omitting from CSP connect-src.")] private static partial void LogInvalidApplicationInsightsIngestionEndpoint(ILogger logger, string? endpoint); + internal static string BuildContentSecurityPolicy(IConfiguration configuration, ILogger? logger = null) + { + // TryDotNet origin comes from runtime config + string? tryDotNetOrigin = configuration["TryDotNet:Origin"]; + string tryDotNetSources = string.Empty; + if (!string.IsNullOrWhiteSpace(tryDotNetOrigin)) + { + if (Uri.TryCreate(tryDotNetOrigin, UriKind.Absolute, out Uri? tryDotNetUri)) + { + tryDotNetSources = $" {tryDotNetUri.GetLeftPart(UriPartial.Authority)}"; + } + else if (logger is not null) + { + LogIgnoringInvalidTryDotNetOrigin(logger, tryDotNetOrigin); + } + } + + // Clarity's tag (www.clarity.ms) loads its tracker from scripts.clarity.ms and load-balances + // across [a-z].clarity.ms, so allow the wildcard plus c.bing.com as Clarity's CSP docs require: + // https://learn.microsoft.com/clarity/setup-and-installation/clarity-csp + // Application Insights fetches its CDN config from js.monitor.azure.com. + return string.Join("; ", + $"default-src 'self'", + $"script-src 'self' 'unsafe-inline' cdn.jsdelivr.net https://*.clarity.ms https://c.bing.com www.googletagmanager.com js.monitor.azure.com https://hcaptcha.com https://*.hcaptcha.com{tryDotNetSources}", + $"style-src 'self' 'nonce-{CspNonce.Placeholder}' cdnjs.cloudflare.com fonts.googleapis.com https://hcaptcha.com https://*.hcaptcha.com", + $"style-src-attr 'unsafe-inline'", + $"font-src 'self' fonts.gstatic.com cdnjs.cloudflare.com", + $"img-src 'self' data: https:", + $"connect-src 'self' https://hcaptcha.com https://*.hcaptcha.com https://api.pwnedpasswords.com https://*.algolia.net https://*.algolianet.com https://*.google-analytics.com https://*.clarity.ms https://c.bing.com https://js.monitor.azure.com https://*.in.applicationinsights.azure.com{GetApplicationInsightsCspSources(configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"], logger)}{tryDotNetSources}", + $"frame-src https://hcaptcha.com https://*.hcaptcha.com https://newassets.hcaptcha.com{tryDotNetSources}", + $"worker-src blob:", + $"frame-ancestors 'none'", + $"base-uri 'self'", + $"form-action 'self' https://login.microsoftonline.com https://github.com" + ); + } + private static string GetApplicationInsightsCspSources(string? connectionString, ILogger? logger = null) { if (string.IsNullOrWhiteSpace(connectionString)) diff --git a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml index 49c83dcd..cab6bfa6 100644 --- a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml +++ b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml @@ -89,6 +89,11 @@ window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('consent', 'default', { + // Unset consent types are treated as granted, so deny the ad types explicitly — + // the site has no advertising. Clarity also reads ad_storage from Consent Mode. + ad_storage: 'denied', + ad_user_data: 'denied', + ad_personalization: 'denied', analytics_storage: 'denied', functionality_storage: 'granted', security_storage: 'granted', diff --git a/EssentialCSharp.Web/wwwroot/js/clarity-manager.js b/EssentialCSharp.Web/wwwroot/js/clarity-manager.js index eafb8a5b..092f4f94 100644 --- a/EssentialCSharp.Web/wwwroot/js/clarity-manager.js +++ b/EssentialCSharp.Web/wwwroot/js/clarity-manager.js @@ -74,8 +74,12 @@ function updateConsent() { if (typeof window.clarity === "function") { try { + // Clarity's Consent API v2 requires both keys, spelled with a capital "S" + // (ad_Storage / analytics_Storage). Lowercase keys are silently ignored. + // https://learn.microsoft.com/clarity/setup-and-installation/clarity-consent-api-v2 window.clarity("consentv2", { - analytics_storage: hasAnalyticsConsent() ? "granted" : "denied" + ad_Storage: "denied", // The site uses no advertising cookies. + analytics_Storage: hasAnalyticsConsent() ? "granted" : "denied" }); } catch (error) { console.warn("Failed to update Clarity consent:", error); diff --git a/EssentialCSharp.Web/wwwroot/js/consent-manager.js b/EssentialCSharp.Web/wwwroot/js/consent-manager.js index cf7415cf..c37fea00 100644 --- a/EssentialCSharp.Web/wwwroot/js/consent-manager.js +++ b/EssentialCSharp.Web/wwwroot/js/consent-manager.js @@ -24,8 +24,6 @@ class ConsentManager { // Load saved consent preferences (signals GA if already consented) this.loadConsentPreferences(); - this.updateClarityConsent(); - // Show banner if no valid consent stored if (this.shouldShowConsentBanner()) { this.showConsentBanner(); @@ -220,12 +218,10 @@ class ConsentManager { }; this.setCookie(this.COOKIE_NAME, JSON.stringify(payload), this.COOKIE_DURATION); - // Update consent mode + // Update consent mode; the consent-changed event it raises lets + // clarity-manager.js and appinsights-manager.js apply the new state. this.updateConsentMode(); - - // Update Clarity consent - this.updateClarityConsent(); - + // Remove banner this.removeConsentBanner(); } @@ -243,19 +239,6 @@ class ConsentManager { } } - updateClarityConsent() { - // Send consent signal to Microsoft Clarity using Consent API v2 - if (window.clarity) { - try { - window.clarity('consentv2', { - analytics_storage: this.consentState.analytics_storage - }); - } catch (error) { - console.warn('Failed to update Clarity consent:', error); - } - } - } - removeConsentBanner() { const banner = document.getElementById('consent-banner'); if (banner) { @@ -317,7 +300,7 @@ class ConsentManager { this.rejectAllConsent(); // Also clear any existing tracking cookies this.clearTrackingCookies(); - // Note: Clarity consent signal is sent via updateClarityConsent() inside rejectAllConsent() → saveConsentAndClose() + // Note: Clarity receives the denied signal from clarity-manager.js via the consent-changed event } clearTrackingCookies() { From be15088425a5b7a7a75e869e73c1dcf4c4ba8b10 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Thu, 26 Nov 2026 14:31:57 -0800 Subject: [PATCH 2/3] refactor: build the CSP from a directive list Define each shared source group once (hCaptcha, Clarity) and splice it into the directives that need it with collection-expression spreads, instead of repeating hosts across interpolated strings. The TryDotNet origin and the Application Insights ingestion endpoint are now returned as source lists, so an absent or invalid value simply adds nothing (no leading-space strings). The emitted policy is unchanged except for dropping https://newassets.hcaptcha.com from frame-src, which https://*.hcaptcha.com already covers. Tests cover configured origins, invalid origins, and the directive order and spacing of the policy string. Co-Authored-By: Claude Opus 5.5 --- .../ContentSecurityPolicyTests.cs | 60 ++++++++++++-- EssentialCSharp.Web/Program.cs | 82 +++++++++++-------- 2 files changed, 100 insertions(+), 42 deletions(-) diff --git a/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs b/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs index 4822ac42..5d02d1c8 100644 --- a/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs +++ b/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs @@ -23,16 +23,60 @@ public class ContentSecurityPolicyTests [Arguments("connect-src", "https://*.google-analytics.com")] public async Task ContentSecurityPolicy_AllowsAnalyticsHosts(string directive, string source) { - IConfiguration configuration = new ConfigurationBuilder().Build(); + string csp = Program.BuildContentSecurityPolicy(new ConfigurationBuilder().Build()); - string csp = Program.BuildContentSecurityPolicy(configuration); + await Assert.That(GetSources(csp, directive)).Contains(source); + } - string[] sources = csp - .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries)) - .FirstOrDefault(parts => parts.Length > 0 && parts[0] == directive) ?? []; + [Test] + // Configured origins are reduced to scheme://host[:port] and added to the directives that need them. + [Arguments("script-src", "https://try.example.test")] + [Arguments("connect-src", "https://try.example.test")] + [Arguments("frame-src", "https://try.example.test")] + [Arguments("connect-src", "https://westus3-1.in.applicationinsights.azure.com")] + public async Task ContentSecurityPolicy_AddsConfiguredOrigins(string directive, string source) + { + string csp = Program.BuildContentSecurityPolicy(ConfigurationWith( + ("TryDotNet:Origin", "https://try.example.test/some/path"), + ("APPLICATIONINSIGHTS_CONNECTION_STRING", + "InstrumentationKey=00000000-0000-0000-0000-000000000000;IngestionEndpoint=https://westus3-1.in.applicationinsights.azure.com/"))); + + await Assert.That(GetSources(csp, directive)).Contains(source); + } + + [Test] + public async Task ContentSecurityPolicy_IgnoresInvalidOrigins() + { + string withInvalid = Program.BuildContentSecurityPolicy(ConfigurationWith( + ("TryDotNet:Origin", "not a url"), + ("APPLICATIONINSIGHTS_CONNECTION_STRING", "InstrumentationKey=x;IngestionEndpoint=http://insecure.example.test/"))); + string withNone = Program.BuildContentSecurityPolicy(new ConfigurationBuilder().Build()); - await Assert.That(sources).IsNotEmpty(); - await Assert.That(sources.Skip(1)).Contains(source); + await Assert.That(withInvalid).IsEqualTo(withNone); } + + [Test] + public async Task ContentSecurityPolicy_IsWellFormed() + { + string csp = Program.BuildContentSecurityPolicy(ConfigurationWith(("TryDotNet:Origin", "https://try.example.test"))); + + await Assert.That(csp).DoesNotContain(" "); + await Assert.That(csp).DoesNotContain(" ;"); + await Assert.That(csp.Split("; ").Select(d => d.Split(' ')[0])).IsEquivalentTo( + [ + "default-src", "script-src", "style-src", "style-src-attr", "font-src", "img-src", + "connect-src", "frame-src", "worker-src", "frame-ancestors", "base-uri", "form-action", + ]); + } + + private static IConfiguration ConfigurationWith(params (string Key, string Value)[] values) => + new ConfigurationBuilder() + .AddInMemoryCollection(values.Select(v => new KeyValuePair(v.Key, v.Value))) + .Build(); + + private static string[] GetSources(string csp, string directive) => + csp.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + .FirstOrDefault(parts => parts.Length > 0 && parts[0] == directive)? + .Skip(1).ToArray() ?? []; } diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index f527aff6..b6412714 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -548,46 +548,60 @@ private static bool IsMcpTransportRequest(HttpRequest request) => internal static string BuildContentSecurityPolicy(IConfiguration configuration, ILogger? logger = null) { - // TryDotNet origin comes from runtime config - string? tryDotNetOrigin = configuration["TryDotNet:Origin"]; - string tryDotNetSources = string.Empty; - if (!string.IsNullOrWhiteSpace(tryDotNetOrigin)) - { - if (Uri.TryCreate(tryDotNetOrigin, UriKind.Absolute, out Uri? tryDotNetUri)) - { - tryDotNetSources = $" {tryDotNetUri.GetLeftPart(UriPartial.Authority)}"; - } - else if (logger is not null) - { - LogIgnoringInvalidTryDotNetOrigin(logger, tryDotNetOrigin); - } - } - + string[] hCaptcha = ["https://hcaptcha.com", "https://*.hcaptcha.com"]; // Clarity's tag (www.clarity.ms) loads its tracker from scripts.clarity.ms and load-balances // across [a-z].clarity.ms, so allow the wildcard plus c.bing.com as Clarity's CSP docs require: // https://learn.microsoft.com/clarity/setup-and-installation/clarity-csp - // Application Insights fetches its CDN config from js.monitor.azure.com. - return string.Join("; ", - $"default-src 'self'", - $"script-src 'self' 'unsafe-inline' cdn.jsdelivr.net https://*.clarity.ms https://c.bing.com www.googletagmanager.com js.monitor.azure.com https://hcaptcha.com https://*.hcaptcha.com{tryDotNetSources}", - $"style-src 'self' 'nonce-{CspNonce.Placeholder}' cdnjs.cloudflare.com fonts.googleapis.com https://hcaptcha.com https://*.hcaptcha.com", - $"style-src-attr 'unsafe-inline'", - $"font-src 'self' fonts.gstatic.com cdnjs.cloudflare.com", - $"img-src 'self' data: https:", - $"connect-src 'self' https://hcaptcha.com https://*.hcaptcha.com https://api.pwnedpasswords.com https://*.algolia.net https://*.algolianet.com https://*.google-analytics.com https://*.clarity.ms https://c.bing.com https://js.monitor.azure.com https://*.in.applicationinsights.azure.com{GetApplicationInsightsCspSources(configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"], logger)}{tryDotNetSources}", - $"frame-src https://hcaptcha.com https://*.hcaptcha.com https://newassets.hcaptcha.com{tryDotNetSources}", - $"worker-src blob:", - $"frame-ancestors 'none'", - $"base-uri 'self'", - $"form-action 'self' https://login.microsoftonline.com https://github.com" - ); + string[] clarity = ["https://*.clarity.ms", "https://c.bing.com"]; + string[] tryDotNet = GetTryDotNetCspSources(configuration["TryDotNet:Origin"], logger); + string[] applicationInsights = GetApplicationInsightsCspSources(configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"], logger); + + (string Directive, string[] Sources)[] policy = + [ + ("default-src", ["'self'"]), + ("script-src", ["'self'", "'unsafe-inline'", "cdn.jsdelivr.net", .. clarity, "www.googletagmanager.com", "js.monitor.azure.com", .. hCaptcha, .. tryDotNet]), + ("style-src", ["'self'", $"'nonce-{CspNonce.Placeholder}'", "cdnjs.cloudflare.com", "fonts.googleapis.com", .. hCaptcha]), + ("style-src-attr", ["'unsafe-inline'"]), + ("font-src", ["'self'", "fonts.gstatic.com", "cdnjs.cloudflare.com"]), + ("img-src", ["'self'", "data:", "https:"]), + // Application Insights fetches its CDN config from js.monitor.azure.com. + ("connect-src", ["'self'", .. hCaptcha, "https://api.pwnedpasswords.com", "https://*.algolia.net", "https://*.algolianet.com", + "https://*.google-analytics.com", .. clarity, "https://js.monitor.azure.com", "https://*.in.applicationinsights.azure.com", + .. applicationInsights, .. tryDotNet]), + ("frame-src", [.. hCaptcha, .. tryDotNet]), + ("worker-src", ["blob:"]), + ("frame-ancestors", ["'none'"]), + ("base-uri", ["'self'"]), + ("form-action", ["'self'", "https://login.microsoftonline.com", "https://github.com"]), + ]; + + return string.Join("; ", policy.Select(entry => $"{entry.Directive} {string.Join(' ', entry.Sources)}")); + } + + private static string[] GetTryDotNetCspSources(string? origin, ILogger? logger) + { + if (string.IsNullOrWhiteSpace(origin)) + { + return []; + } + + if (Uri.TryCreate(origin, UriKind.Absolute, out Uri? uri)) + { + return [uri.GetLeftPart(UriPartial.Authority)]; + } + + if (logger is not null) + { + LogIgnoringInvalidTryDotNetOrigin(logger, origin); + } + return []; } - private static string GetApplicationInsightsCspSources(string? connectionString, ILogger? logger = null) + private static string[] GetApplicationInsightsCspSources(string? connectionString, ILogger? logger = null) { if (string.IsNullOrWhiteSpace(connectionString)) { - return string.Empty; + return []; } string? ingestionEndpoint = GetConnectionStringValue(connectionString, "IngestionEndpoint"); @@ -599,10 +613,10 @@ private static string GetApplicationInsightsCspSources(string? connectionString, { LogInvalidApplicationInsightsIngestionEndpoint(logger, ingestionEndpoint); } - return string.Empty; + return []; } - return $" {ingestionUri.GetLeftPart(UriPartial.Authority)}"; + return [ingestionUri.GetLeftPart(UriPartial.Authority)]; } private static string? GetConnectionStringValue(string connectionString, string key) From 17f62b8b55069f08a8b174c994a697f0ee1f4d60 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Thu, 26 Nov 2026 14:39:07 -0800 Subject: [PATCH 3/3] feat: report-only CSP in Development; limit jsDelivr to DocSearch - Development now sends the same policy as Content-Security-Policy-Report-Only, so a host the policy would block shows up as a browser console violation locally instead of failing silently in production (as Clarity did). Nothing is blocked in Development. - script-src allows only https://cdn.jsdelivr.net/npm/@docsearch/ instead of all of cdn.jsdelivr.net; DocSearch is the only script loaded from jsDelivr. Co-Authored-By: Claude Opus 5.5 --- .../ContentSecurityPolicyTests.cs | 9 +++++++ .../DevelopmentContentSecurityPolicyTests.cs | 24 +++++++++++++++++++ .../Middleware/SecurityHeadersBuilder.cs | 9 +++++++ EssentialCSharp.Web/Program.cs | 8 ++++++- 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 EssentialCSharp.Web.Tests/DevelopmentContentSecurityPolicyTests.cs diff --git a/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs b/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs index 5d02d1c8..e91ac427 100644 --- a/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs +++ b/EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs @@ -44,6 +44,15 @@ public async Task ContentSecurityPolicy_AddsConfiguredOrigins(string directive, await Assert.That(GetSources(csp, directive)).Contains(source); } + [Test] + public async Task ContentSecurityPolicy_LimitsJsDelivrToDocSearch() + { + string[] scriptSrc = GetSources(Program.BuildContentSecurityPolicy(new ConfigurationBuilder().Build()), "script-src"); + + await Assert.That(scriptSrc).Contains("https://cdn.jsdelivr.net/npm/@docsearch/"); + await Assert.That(scriptSrc).DoesNotContain("cdn.jsdelivr.net"); + } + [Test] public async Task ContentSecurityPolicy_IgnoresInvalidOrigins() { diff --git a/EssentialCSharp.Web.Tests/DevelopmentContentSecurityPolicyTests.cs b/EssentialCSharp.Web.Tests/DevelopmentContentSecurityPolicyTests.cs new file mode 100644 index 00000000..0afde310 --- /dev/null +++ b/EssentialCSharp.Web.Tests/DevelopmentContentSecurityPolicyTests.cs @@ -0,0 +1,24 @@ +using EssentialCSharp.Web.Middleware; + +namespace EssentialCSharp.Web.Tests; + +/// +/// The test host runs in Development, where the policy is sent report-only so violations surface +/// locally without blocking anything. +/// +public class DevelopmentContentSecurityPolicyTests : IntegrationTestBase +{ + [Test] + public async Task Development_SendsTheReportOnlyPolicy() + { + using HttpClient client = CreateClientWithoutAutoRedirect(); + + using HttpResponseMessage response = await client.GetAsync("/health"); + + await Assert.That(response.Headers.Contains("Content-Security-Policy")).IsFalse(); + await Assert.That(response.Headers.TryGetValues("Content-Security-Policy-Report-Only", out IEnumerable? values)).IsTrue(); + string policy = values!.Single(); + await Assert.That(policy).Contains("script-src"); + await Assert.That(policy).DoesNotContain(CspNonce.Placeholder); + } +} diff --git a/EssentialCSharp.Web/Middleware/SecurityHeadersBuilder.cs b/EssentialCSharp.Web/Middleware/SecurityHeadersBuilder.cs index 6251da12..b7a81c73 100644 --- a/EssentialCSharp.Web/Middleware/SecurityHeadersBuilder.cs +++ b/EssentialCSharp.Web/Middleware/SecurityHeadersBuilder.cs @@ -182,6 +182,15 @@ public SecurityHeadersBuilder AddContentSecurityPolicy(string value) return AddCustomHeader("Content-Security-Policy", value); } + /// + /// Adds a Content-Security-Policy-Report-Only header: the browser reports violations but blocks nothing. + /// + /// The CSP directive string. + public SecurityHeadersBuilder AddContentSecurityPolicyReportOnly(string value) + { + return AddCustomHeader("Content-Security-Policy-Report-Only", value); + } + /// /// Add a custom header to all requests /// diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index b6412714..38d55fb0 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -432,6 +432,11 @@ await McpJsonRpcResponseWriter.WriteErrorAsync( { app.UseForwardedHeaders(); } + + // Report-only in Development: a host the policy would block shows up as a console + // violation locally, without breaking dev tooling. + app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder() + .AddContentSecurityPolicyReportOnly(BuildContentSecurityPolicy(app.Configuration, app.Logger))); } app.MapHealthChecks("/health").DisableRateLimiting(); @@ -559,7 +564,8 @@ internal static string BuildContentSecurityPolicy(IConfiguration configuration, (string Directive, string[] Sources)[] policy = [ ("default-src", ["'self'"]), - ("script-src", ["'self'", "'unsafe-inline'", "cdn.jsdelivr.net", .. clarity, "www.googletagmanager.com", "js.monitor.azure.com", .. hCaptcha, .. tryDotNet]), + // jsDelivr is only used for DocSearch (wwwroot/js/algoliaDocSearch.js), so allow just that package path. + ("script-src", ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net/npm/@docsearch/", .. clarity, "www.googletagmanager.com", "js.monitor.azure.com", .. hCaptcha, .. tryDotNet]), ("style-src", ["'self'", $"'nonce-{CspNonce.Placeholder}'", "cdnjs.cloudflare.com", "fonts.googleapis.com", .. hCaptcha]), ("style-src-attr", ["'unsafe-inline'"]), ("font-src", ["'self'", "fonts.gstatic.com", "cdnjs.cloudflare.com"]),