Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions EssentialCSharp.Web.Tests/ContentSecurityPolicyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
using Microsoft.Extensions.Configuration;

namespace EssentialCSharp.Web.Tests;

/// <summary>
/// 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.
/// </summary>
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)
{
string csp = Program.BuildContentSecurityPolicy(new ConfigurationBuilder().Build());

await Assert.That(GetSources(csp, directive)).Contains(source);
}

[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_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()
{
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(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<string, string?>(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() ?? [];
}
24 changes: 24 additions & 0 deletions EssentialCSharp.Web.Tests/DevelopmentContentSecurityPolicyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using EssentialCSharp.Web.Middleware;

namespace EssentialCSharp.Web.Tests;

/// <summary>
/// The test host runs in Development, where the policy is sent report-only so violations surface
/// locally without blocking anything.
/// </summary>
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<string>? values)).IsTrue();
string policy = values!.Single();
await Assert.That(policy).Contains("script-src");
await Assert.That(policy).DoesNotContain(CspNonce.Placeholder);
}
}
9 changes: 9 additions & 0 deletions EssentialCSharp.Web/Middleware/SecurityHeadersBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,15 @@ public SecurityHeadersBuilder AddContentSecurityPolicy(string value)
return AddCustomHeader("Content-Security-Policy", value);
}

/// <summary>
/// Adds a Content-Security-Policy-Report-Only header: the browser reports violations but blocks nothing.
/// </summary>
/// <param name="value">The CSP directive string.</param>
public SecurityHeadersBuilder AddContentSecurityPolicyReportOnly(string value)
{
return AddCustomHeader("Content-Security-Policy-Report-Only", value);
}

/// <summary>
/// Add a custom header to all requests
/// </summary>
Expand Down
95 changes: 62 additions & 33 deletions EssentialCSharp.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -460,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();
Expand Down Expand Up @@ -574,11 +551,63 @@ 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);

private static string GetApplicationInsightsCspSources(string? connectionString, ILogger? logger = null)
internal static string BuildContentSecurityPolicy(IConfiguration configuration, ILogger? logger = null)
{
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
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'"]),
// 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"]),
("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)
{
if (string.IsNullOrWhiteSpace(connectionString))
{
return string.Empty;
return [];
}

string? ingestionEndpoint = GetConnectionStringValue(connectionString, "IngestionEndpoint");
Expand All @@ -590,10 +619,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)
Expand Down
5 changes: 5 additions & 0 deletions EssentialCSharp.Web/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
6 changes: 5 additions & 1 deletion EssentialCSharp.Web/wwwroot/js/clarity-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
25 changes: 4 additions & 21 deletions EssentialCSharp.Web/wwwroot/js/consent-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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();
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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() {
Expand Down
Loading