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
92 changes: 92 additions & 0 deletions test/Classes/CspPolicyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using Microsoft.Net.Http.Headers;
using Viper.Classes;

namespace Viper.test.Classes;

/// <summary>Built Vue SPA responses must not permit dynamic code evaluation. See CspPolicy.</summary>
public class CspPolicyTests
{
// Shape of the emitted header. Joonasw's CspOptions joins directives with ';' and no space.
private const string ApplicationPolicy =
"script-src 'self' 'nonce-abc123' 'unsafe-eval';style-src 'self' fonts.googleapis.com 'unsafe-inline';img-src 'self' data:;frame-src 'none'";

private const string TightenedPolicy =
"script-src 'self' 'nonce-abc123';style-src 'self' fonts.googleapis.com 'unsafe-inline';img-src 'self' data:;frame-src 'none'";

[Fact]
public void WithoutUnsafeEval_ApplicationPolicy_DropsOnlyTheAllowance()
{
Assert.Equal(TightenedPolicy, CspPolicy.WithoutUnsafeEval(ApplicationPolicy));
}

[Theory]
[InlineData("script-src 'self' 'unsafe-eval'", "script-src 'self'")]
[InlineData("script-src 'unsafe-eval' 'self'", "script-src 'self'")]
[InlineData("script-src 'self' 'unsafe-eval' 'nonce-x'", "script-src 'self' 'nonce-x'")]
public void WithoutUnsafeEval_HandlesEveryPositionInADirective(string policy, string expected)
{
Assert.Equal(expected, CspPolicy.WithoutUnsafeEval(policy));
}

[Theory]
[InlineData("script-src 'unsafe-eval'", "script-src 'none'")]
[InlineData("script-src 'unsafe-eval';img-src 'self'", "script-src 'none';img-src 'self'")]
public void WithoutUnsafeEval_SoleSourceExpression_FallsBackToNone(string policy, string expected)
{
Assert.Equal(expected, CspPolicy.WithoutUnsafeEval(policy));
}

[Fact]
public void WithoutUnsafeEval_ValuelessDirective_IsNotGivenASource()
{
Assert.Equal(
"script-src 'self';upgrade-insecure-requests",
CspPolicy.WithoutUnsafeEval("script-src 'self' 'unsafe-eval';upgrade-insecure-requests"));
}

[Fact]
public void WithoutUnsafeEval_PolicyWithoutTheAllowance_IsUnchanged()
{
const string policy = "script-src 'self' 'nonce-abc123';img-src 'self'";

Assert.Equal(policy, CspPolicy.WithoutUnsafeEval(policy));
}

[Theory]
[InlineData(null)]
[InlineData("")]
public void WithoutUnsafeEval_MissingHeader_ReturnsEmpty(string? policy)
{
Assert.Equal(string.Empty, CspPolicy.WithoutUnsafeEval(policy));
}

[Fact]
public void TightenForBuiltSpa_RewritesThePolicyOnTheResponse()
{
var http = new DefaultHttpContext();
http.Response.Headers[HeaderNames.ContentSecurityPolicy] = ApplicationPolicy;

CspPolicy.TightenForBuiltSpa(ResponseContextFor(http));

Assert.Equal(TightenedPolicy, http.Response.Headers[HeaderNames.ContentSecurityPolicy].ToString());
}

[Fact]
public void TightenForBuiltSpa_NoPolicyOnTheResponse_AddsNoHeader()
{
// The CSP middleware is skipped for HealthChecks UI paths, so the header can be absent.
var http = new DefaultHttpContext();

CspPolicy.TightenForBuiltSpa(ResponseContextFor(http));

Assert.False(http.Response.Headers.ContainsKey(HeaderNames.ContentSecurityPolicy));
}

private static StaticFileResponseContext ResponseContextFor(HttpContext http)
{
return new StaticFileResponseContext(http, new NotFoundFileInfo("index.html"));
}
}
51 changes: 51 additions & 0 deletions web/Classes/CspPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Net.Http.Headers;

namespace Viper.Classes
{
/// <summary>
/// The app-wide policy keeps 'unsafe-eval': _VIPERLayout Razor pages mount Vue's full build on
/// the document body, compiling that in-DOM template via Function(code)(). Dropping it blanks them.
/// </summary>
public static class CspPolicy
{
private const string UnsafeEval = "'unsafe-eval'";

/// <summary>Drops the allowance from a built SPA response with precompiled templates.</summary>
public static void TightenForBuiltSpa(StaticFileResponseContext ctx)
{
var headers = ctx.Context.Response.Headers;
if (headers.TryGetValue(HeaderNames.ContentSecurityPolicy, out var policy))
{
headers[HeaderNames.ContentSecurityPolicy] = WithoutUnsafeEval(policy.ToString());
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

/// <summary>Returns the policy with every 'unsafe-eval' source expression removed.</summary>
public static string WithoutUnsafeEval(string? headerValue)
{
return string.IsNullOrEmpty(headerValue)
? string.Empty
: string.Join(';', headerValue.Split(';').Select(StripUnsafeEval));
}

private static string StripUnsafeEval(string directive)
{
// Without this, a valueless directive like upgrade-insecure-requests would gain 'none'.
if (!directive.Contains(UnsafeEval, StringComparison.Ordinal))
{
return directive;
}

string[] kept = directive
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Where(token => !string.Equals(token, UnsafeEval, StringComparison.Ordinal))
.ToArray();

// A bare directive name already matches nothing; 'none' states that explicitly.
return kept.Length == 1
? kept[0] + " 'none'"
: string.Join(' ', kept);
}
}
}
8 changes: 6 additions & 2 deletions web/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Net;

Check warning on line 1 in web/Program.cs

View workflow job for this annotation

GitHub Actions / Backend Tests

'<Main>$' has a cyclomatic complexity of '31'. Rewrite or refactor the code to decrease its complexity below '26'. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1502)
using System.Reflection;
using System.Security.Claims;
using System.Text.Json.Serialization;
Expand Down Expand Up @@ -43,7 +43,7 @@

// Load .env.local for local development only (multiple-instance support)
// Avoid loading in production - guard by ASPNETCORE_ENVIRONMENT.
var envPath = Path.Join(Directory.GetCurrentDirectory(), "../.env.local");

Check warning on line 46 in web/Program.cs

View workflow job for this annotation

GitHub Actions / Backend Tests

'Program' has a maintainability index of '5'. Rewrite or refactor the code to increase its maintainability index (MI) above '9'. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1505)
var aspNetEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(aspNetEnv, "Development", StringComparison.OrdinalIgnoreCase)
&& File.Exists(envPath))
Expand Down Expand Up @@ -326,11 +326,12 @@
ctx => !HealthCheckExtensions.IsUIPath(ctx.Request.Path),
branch => branch.UseCsp(csp =>
{
// Legacy Razor pages need 'unsafe-eval'; the /2/vue branch below drops it. See CspPolicy.
// Allow JavaScript from:
csp.AllowScripts
.FromSelf() // This domain
.AddNonce() // Inline scripts only with Nonce
.AllowUnsafeEval(); // allow JS eval command (must also fit within other restrictions)
.AllowUnsafeEval();

// Allow connections for WebSocket HMR and legacy systems in development
if (app.Environment.IsDevelopment())
Expand Down Expand Up @@ -487,11 +488,14 @@
// Prod (and dev fallback): rewrite SPA routes to the built SPA shell,
// then serve the static file from wwwroot/vue.
branch.UseRewriter(rewriteOptions);
// Only the SPA shell reaches here; under /2, assets are served above and keep the
// permissive header, which is harmless since CSP on a subresource governs nothing.
branch.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Join(builder.Environment.WebRootPath, "vue")),
RequestPath = "/2/vue"
RequestPath = "/2/vue",
OnPrepareResponse = CspPolicy.TightenForBuiltSpa
});
});

Expand Down
Loading