Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TDEAL-27: Fix Content Security Policy with Browser Link #248

Merged
merged 22 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
using static Lombiq.HelpfulLibraries.AspNetCore.Security.ContentSecurityPolicyDirectives;
using static Lombiq.HelpfulLibraries.AspNetCore.Security.ContentSecurityPolicyDirectives.CommonValues;
Expand All @@ -27,6 +27,10 @@ public static class ApplicationBuilderExtensions
/// If <see langword="true"/> then inline styles are permitted. Note that even if your site has no embedded style
/// blocks and no style attributes, some Javascript libraries may still create some from code.
/// </param>
[SuppressMessage(
"Critical Code Smell",
"S3776:Cognitive Complexity of methods should not be too high",
Justification = "It's not that complex, calculation is skewed by the logic being inside an anonymous function.")]
public static IApplicationBuilder UseContentSecurityPolicyHeader(
this IApplicationBuilder app,
bool allowInlineScript,
Expand Down Expand Up @@ -63,18 +67,26 @@ public static IApplicationBuilder UseContentSecurityPolicyHeader(

context.Response.OnStarting(async () =>
{
// No need to do content security policy on non-HTML responses.
if (context.Response.ContentType?.ContainsOrdinalIgnoreCase(MediaTypeNames.Text.Html) != true) return;
var providers = context.RequestServices.GetServices<IContentSecurityPolicyProvider>().AsList();

// Additional extension point for scenarios where it's desirable to skip the Content-Security-Policy
// entirely.
foreach (var provider in providers)
{
if (await provider.ShouldSuppressHeaderAsync(context)) return;
}

// The thought behind this provider model is that if you need something else than the default, you
// should add a provider that only applies the additional directive on screens where it's actually
// needed. This way we maintain minimal permissions. Also if you need additional permissions for a
// specific action you can use the [ContentSecurityPolicyAttribute(value, name, parentName)] attribute.
foreach (var provider in context.RequestServices.GetServices<IContentSecurityPolicyProvider>())
foreach (var provider in providers)
{
await provider.UpdateAsync(securityPolicies, context);
}

if (securityPolicies.Count == 0) return;

var policy = string.Join("; ", securityPolicies.Select(pair => $"{pair.Key} {pair.Value}"));
context.Response.Headers[key] = policy;
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

using static Lombiq.HelpfulLibraries.AspNetCore.Security.ContentSecurityPolicyDirectives;

namespace Lombiq.HelpfulLibraries.AspNetCore.Security;

/// <summary>
/// A content security policy directive provider that permits wide local access for <see cref="ConnectSrc"/> so it can
/// be used in Visual Studio's debug mode feature Browser Link.
/// </summary>
public class BrowserLinkContentSecurityPolicyProvider : IContentSecurityPolicyProvider
{
public ValueTask UpdateAsync(IDictionary<string, string> securityPolicies, HttpContext context)
{
if (context.IsDevelopmentAndLocalhost())
{
// Browser Link is accessed through multiple random ports on localhost.
securityPolicies[ConnectSrc] = ContentSecurityPolicyProvider
.GetDirective(securityPolicies, ConnectSrc)
.MergeWordSets("http://localhost:* ws://localhost:*");
}

return ValueTask.CompletedTask;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ public class CdnContentSecurityPolicyProvider : IContentSecurityPolicyProvider
new Uri("https://fonts.gstatic.com/"),
new Uri("https://cdn.jsdelivr.net/npm"),
new Uri("https://fastly.jsdelivr.net/npm"),
new Uri("https://cdnjs.cloudflare.com/"),
new Uri("https://maxcdn.bootstrapcdn.com/"),
});

/// <summary>
Expand All @@ -32,7 +34,10 @@ public class CdnContentSecurityPolicyProvider : IContentSecurityPolicyProvider
public static ConcurrentBag<Uri> PermittedScriptSources { get; } = new(new[]
{
new Uri("https://cdn.jsdelivr.net/npm"),
new Uri("https://code.jquery.com/"),
new Uri("https://fastly.jsdelivr.net/npm"),
new Uri("https://cdnjs.cloudflare.com/"),
new Uri("https://maxcdn.bootstrapcdn.com/"),
});

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@ public interface IContentSecurityPolicyProvider
/// Updates the <paramref name="securityPolicies"/> dictionary where the keys are the <c>Content-Security-Policy</c>
/// directives names and the values are the matching directive values.
/// </summary>
public ValueTask UpdateAsync(IDictionary<string, string> securityPolicies, HttpContext context);
public ValueTask UpdateAsync(IDictionary<string, string> securityPolicies, HttpContext context) =>
ValueTask.CompletedTask;

/// <summary>
/// Returns a value indicating whether the <c>Content-Security-Policy</c> header should not be added to the current
/// page.
/// </summary>
public ValueTask<bool> ShouldSuppressHeaderAsync(HttpContext context) =>
new(result: false);

/// <summary>
/// Returns the first non-empty directive from the <paramref name="names"/> or <see cref="DefaultSrc"/> or an empty
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Lombiq.HelpfulLibraries.AspNetCore.Security;
using Lombiq.HelpfulLibraries.AspNetCore.Security;
using Lombiq.HelpfulLibraries.OrchardCore.DependencyInjection;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
Expand Down Expand Up @@ -34,6 +34,30 @@ public static OrchardCoreBuilder ConfigureAntiForgeryAlwaysSecure(this OrchardCo
/// </item>
/// <item>
/// <description>
/// Add <see cref="VueContentSecurityPolicyProvider"/> to permit script evaluation when the <c>vuejs</c>
/// resource is included.
/// </description>
/// </item>
/// <item>
/// <description>
/// Add <see cref="ContentSecurityPolicyAttributeContentSecurityPolicyProvider"/> to amend the content
/// security policy using the <see cref="ContentSecurityPolicyAttribute"/>.
/// </description>
/// </item>
/// <item>
/// <description>
/// Add <see cref="SkipContentSecurityPolicyProvider"/> to skip declaring a content security policy on
/// responses where it makes no sense.
/// </description>
/// </item>
/// <item>
/// <description>
/// Add <see cref="BrowserLinkContentSecurityPolicyProvider"/> to permit accessing other ports on
/// <c>localhost</c> during local development.
/// </description>
/// </item>
/// <item>
/// <description>
/// Make the session token's cookie always secure.
/// </description>
/// </item>
Expand Down Expand Up @@ -94,6 +118,8 @@ private static OrchardCoreBuilder ConfigureSecurityDefaultsInner(
.AddContentSecurityPolicyProvider<CdnContentSecurityPolicyProvider>()
.AddContentSecurityPolicyProvider<VueContentSecurityPolicyProvider>()
.AddContentSecurityPolicyProvider<ContentSecurityPolicyAttributeContentSecurityPolicyProvider>()
.AddContentSecurityPolicyProvider<SkipContentSecurityPolicyProvider>()
.AddContentSecurityPolicyProvider<BrowserLinkContentSecurityPolicyProvider>()
.ConfigureSessionCookieAlwaysSecure(),
(app, _, serviceProvider) =>
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Lombiq.HelpfulLibraries.AspNetCore.Security;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using OrchardCore.Admin;
using System;
using System.Net.Mime;
using System.Threading.Tasks;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// A provider for some common scenarios where the header should not be applied at all.
/// </summary>
public class SkipContentSecurityPolicyProvider : IContentSecurityPolicyProvider
{
private readonly string _adminPathPrefix;

public SkipContentSecurityPolicyProvider(IOptions<AdminOptions> adminOptions) =>
_adminPathPrefix = '/' + adminOptions.Value.AdminUrlPrefix;

public ValueTask<bool> ShouldSuppressHeaderAsync(HttpContext context) =>
new(ShouldSuppressHeaderInner(context));

private static bool ShouldSuppressHeaderInner(HttpContext context) =>
// No need to do content security policy on non-HTML responses.
context.Response.ContentType?.ContainsOrdinalIgnoreCase(MediaTypeNames.Text.Html) != true;
}