security(#319): enforcing CSP + Permissions-Policy on the host
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 11s
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 11s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 13s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 1m48s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 3m49s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m16s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 11s
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 11s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 13s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 1m48s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 3m49s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m16s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Completes the CSP the #279 baseline-headers middleware deferred. Surfaced by the #314 ZAP baseline (missing CSP/Permissions-Policy WARNs); a #197 exit item. SecurityHeadersMiddleware now also sets Permissions-Policy (deny-all for camera/mic/geolocation/payment/usb) and an enforcing Content-Security-Policy on every response EXCEPT /docs (Scalar) and /openapi — those rely on inline bootstrap scripts/styles a strict policy would break (baseline headers still apply; hardening that admin surface is a #197 follow-up). CSP: default-src 'self'; script-src 'self' + the hash of the SPA's inline theme-bootstrap script (no 'unsafe-inline'/'unsafe-eval'); style-src adds 'unsafe-inline' (React inline styles) + fonts.googleapis.com; font-src adds fonts.gstatic.com; img-src adds data:/blob:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'. The Google Fonts allowance (the SPA CSS @imports the Geist web font) was caught by live-E2E, which the static recon missed. A guard test hashes the committed web/index.html inline script and fails if it drifts from the middleware constant (the built wwwroot/app is gitignored/absent in CI, and Vite copies the inline script verbatim). Verified: full test pass, live-E2E (SPA renders clean, zero CSP violations), curl (CSP present on /app + /api, absent on /docs + /openapi). Docs: docs/decisions.md entry. fixes #319 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,7 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using ErsatzTV.Middleware;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NUnit.Framework;
|
||||
@@ -8,8 +12,7 @@ namespace ErsatzTV.Tests.Middleware;
|
||||
[TestFixture]
|
||||
public class SecurityHeadersMiddlewareTests
|
||||
{
|
||||
[Test]
|
||||
public async Task Should_Set_Baseline_Security_Headers()
|
||||
private static async Task<HttpContext> Invoke(string path)
|
||||
{
|
||||
var nextCalled = false;
|
||||
var middleware = new SecurityHeadersMiddleware(_ =>
|
||||
@@ -18,12 +21,116 @@ public class SecurityHeadersMiddlewareTests
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
var context = new DefaultHttpContext();
|
||||
context.Request.Path = path;
|
||||
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
nextCalled.ShouldBeTrue();
|
||||
return context;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Set_Baseline_Security_Headers()
|
||||
{
|
||||
HttpContext context = await Invoke("/app");
|
||||
|
||||
context.Response.Headers["X-Content-Type-Options"].ToString().ShouldBe("nosniff");
|
||||
context.Response.Headers["X-Frame-Options"].ToString().ShouldBe("DENY");
|
||||
context.Response.Headers["Referrer-Policy"].ToString().ShouldBe("strict-origin-when-cross-origin");
|
||||
context.Response.Headers["Permissions-Policy"].ToString().ShouldNotBeEmpty();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Enforce_Csp_On_Spa_And_Api_Responses()
|
||||
{
|
||||
foreach (string path in new[] { "/", "/app", "/api/channels", "/artwork/x.jpg", "/iptv/channels.m3u" })
|
||||
{
|
||||
HttpContext context = await Invoke(path);
|
||||
string csp = context.Response.Headers["Content-Security-Policy"].ToString();
|
||||
|
||||
csp.ShouldNotBeEmpty($"CSP should be enforced on {path}");
|
||||
csp.ShouldContain("default-src 'self'");
|
||||
csp.ShouldContain("script-src 'self' '" + SecurityHeadersMiddleware.SpaInlineScriptHash + "'");
|
||||
csp.ShouldContain("connect-src 'self'");
|
||||
csp.ShouldContain("frame-ancestors 'none'");
|
||||
csp.ShouldContain("object-src 'none'");
|
||||
// The SPA CSS @imports the Geist web font from Google (verified by live-E2E).
|
||||
csp.ShouldContain("style-src 'self' 'unsafe-inline' https://fonts.googleapis.com");
|
||||
csp.ShouldContain("font-src 'self' data: https://fonts.gstatic.com");
|
||||
// No 'unsafe-inline'/'unsafe-eval' in the script directive.
|
||||
csp.ShouldNotContain("script-src 'self' 'unsafe");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Should_Not_Send_Csp_On_Scalar_Docs_Or_Openapi()
|
||||
{
|
||||
// Scalar (/docs) and the OpenAPI document (/openapi) rely on inline bootstrap scripts/styles
|
||||
// a strict CSP would break; they are intentionally excluded (baseline headers still apply).
|
||||
foreach (string path in new[] { "/docs", "/docs/", "/openapi/v1.json" })
|
||||
{
|
||||
HttpContext context = await Invoke(path);
|
||||
|
||||
context.Response.Headers.ContainsKey("Content-Security-Policy").ShouldBeFalse($"CSP must not be set on {path}");
|
||||
// The cheap baseline headers still apply everywhere.
|
||||
context.Response.Headers["X-Content-Type-Options"].ToString().ShouldBe("nosniff");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Guards <see cref="SecurityHeadersMiddleware.SpaInlineScriptHash" /> against drift from the
|
||||
/// SPA's <c>index.html</c>: every inline <c><script></c> the browser will hash-check must
|
||||
/// be allow-listed by the CSP, or the enforcing policy silently breaks the SPA. Vite copies
|
||||
/// inline scripts into the build verbatim, so hashing the committed source (<c>web/index.html</c>,
|
||||
/// which — unlike the gitignored built <c>wwwroot/app</c> — exists in the CI checkout) matches
|
||||
/// the served bytes.
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void Csp_Script_Hash_Should_Match_The_Spa_Index()
|
||||
{
|
||||
string indexPath = SpaIndexSourcePath();
|
||||
File.Exists(indexPath).ShouldBeTrue($"SPA source index.html not found at {indexPath}");
|
||||
|
||||
List<string> inlineHashes = InlineScriptHashes(File.ReadAllText(indexPath));
|
||||
|
||||
inlineHashes.ShouldNotBeEmpty("expected the SPA index.html to contain the inline theme-bootstrap script");
|
||||
foreach (string hash in inlineHashes)
|
||||
{
|
||||
hash.ShouldBe(
|
||||
SecurityHeadersMiddleware.SpaInlineScriptHash,
|
||||
"an inline <script> in wwwroot/app/index.html is not allow-listed by the CSP — " +
|
||||
"update SecurityHeadersMiddleware.SpaInlineScriptHash to this value");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> InlineScriptHashes(string html)
|
||||
{
|
||||
var hashes = new List<string>();
|
||||
foreach (Match m in Regex.Matches(html, "<script([^>]*)>(.*?)</script>", RegexOptions.Singleline))
|
||||
{
|
||||
// Skip external scripts (they load from 'self', not by hash) and empty bodies.
|
||||
if (m.Groups[1].Value.Contains("src", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
string body = m.Groups[2].Value;
|
||||
if (string.IsNullOrWhiteSpace(body))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
byte[] digest = SHA256.HashData(Encoding.UTF8.GetBytes(body));
|
||||
hashes.Add("sha256-" + Convert.ToBase64String(digest));
|
||||
}
|
||||
|
||||
return hashes;
|
||||
}
|
||||
|
||||
private static string SpaIndexSourcePath([CallerFilePath] string callerFilePath = "")
|
||||
{
|
||||
// callerFilePath = <repo>/ErsatzTV.Tests/Middleware/SecurityHeadersMiddlewareTests.cs
|
||||
string repoRoot = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(callerFilePath)!, "..", ".."));
|
||||
return Path.Combine(repoRoot, "web", "index.html");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,21 +3,76 @@ using Microsoft.AspNetCore.Http;
|
||||
namespace ErsatzTV.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// Adds baseline security response headers to every response (API, IPTV, artwork, static, and
|
||||
/// error responses alike — which is why this is middleware rather than an MVC filter).
|
||||
/// Adds security response headers to every response (API, IPTV, artwork, static, and error
|
||||
/// responses alike — which is why this is middleware rather than an MVC filter).
|
||||
/// <c>nosniff</c> in particular blunts the MIME-sniffing half of the artwork content-type
|
||||
/// reflection risk (issue #197). CSP and HSTS are intentionally left out here: CSP needs to be
|
||||
/// validated against the ChicoryTV SPA's inline assets, and HSTS is a deployment/TLS decision —
|
||||
/// both are part of the #197 posture design, not this baseline.
|
||||
/// reflection risk (issue #197). A Content-Security-Policy is enforced everywhere except the
|
||||
/// Scalar API-reference UI (<c>/docs</c>) and the OpenAPI document (<c>/openapi</c>) — see
|
||||
/// <see cref="InvokeAsync" />. HSTS is intentionally left out: it is a deployment/TLS decision
|
||||
/// that belongs with the go-live reverse-proxy posture, not this host middleware.
|
||||
/// Baseline headers landed for #197; the CSP + Permissions-Policy were added for #319 (ZAP
|
||||
/// baseline hardening).
|
||||
/// </summary>
|
||||
public class SecurityHeadersMiddleware(RequestDelegate next)
|
||||
{
|
||||
/// <summary>
|
||||
/// sha256 of the inline theme-bootstrap <c><script></c> in the built SPA
|
||||
/// <c>index.html</c> (<c>ErsatzTV/wwwroot/app</c>). The SPA is served as a static file, so a
|
||||
/// per-response CSP nonce is not possible — the one inline script is allow-listed by hash
|
||||
/// instead. If <c>web/index.html</c>'s inline script changes, this hash must change with it;
|
||||
/// <c>SecurityHeadersMiddlewareTests.Csp_Script_Hash_Should_Match_The_Spa_Index</c>
|
||||
/// guards the two against drift.
|
||||
/// </summary>
|
||||
public const string SpaInlineScriptHash = "sha256-5qq06L57XDT8IqaUeyjnI1l7bZ+ggOaE4GXF4TpnGwM=";
|
||||
|
||||
/// <summary>
|
||||
/// Enforcing CSP for the SPA plus the API/artwork/IPTV responses. Notes on the choices:
|
||||
/// <list type="bullet">
|
||||
/// <item><c>script-src 'self'</c> (the Vite module bundle) + the inline theme-bootstrap
|
||||
/// hash — no <c>'unsafe-inline'</c>/<c>'unsafe-eval'</c> (the SPA has no eval/CSS-in-JS).</item>
|
||||
/// <item><c>style-src 'unsafe-inline'</c>: React writes inline <c>style=""</c> attributes
|
||||
/// (there is no styled-components/emotion in the SPA to hash <c><style></c> blocks).
|
||||
/// <c>fonts.googleapis.com</c> is the Geist web-font stylesheet the SPA CSS <c>@import</c>s
|
||||
/// (with <c>fonts.gstatic.com</c> in <c>font-src</c> for the font files). Self-hosting the
|
||||
/// font to drop the Google dependency is a follow-on hardening, not this issue.</item>
|
||||
/// <item><c>img-src data: blob:</c>: favicon/generated-image data URIs and object-URL
|
||||
/// upload previews.</item>
|
||||
/// <item><c>connect-src 'self'</c>: the SPA only ever fetches same-origin
|
||||
/// <c>/api</c>, <c>/artwork</c>, <c>/iptv</c>.</item>
|
||||
/// </list>
|
||||
/// Non-HTML responses (JSON, images, m3u) never exercise the script/style directives, so the
|
||||
/// same policy is safe to apply to them.
|
||||
/// </summary>
|
||||
private static readonly string ContentSecurityPolicy = string.Join(
|
||||
"; ",
|
||||
"default-src 'self'",
|
||||
"script-src 'self' '" + SpaInlineScriptHash + "'",
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
||||
"img-src 'self' data: blob:",
|
||||
"font-src 'self' data: https://fonts.gstatic.com",
|
||||
"connect-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"form-action 'self'");
|
||||
|
||||
public Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
IHeaderDictionary headers = context.Response.Headers;
|
||||
headers["X-Content-Type-Options"] = "nosniff";
|
||||
headers["X-Frame-Options"] = "DENY";
|
||||
headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
|
||||
headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=(), usb=()";
|
||||
|
||||
// The Scalar API-reference UI (/docs) and the OpenAPI document (/openapi) rely on inline
|
||||
// bootstrap scripts/styles that a strict policy would break; hardening that admin surface is
|
||||
// a #197 follow-up. Everything else — the SPA, /api, /artwork, /iptv — gets the CSP.
|
||||
PathString path = context.Request.Path;
|
||||
if (!path.StartsWithSegments("/docs") && !path.StartsWithSegments("/openapi"))
|
||||
{
|
||||
headers["Content-Security-Policy"] = ContentSecurityPolicy;
|
||||
}
|
||||
|
||||
return next(context);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,7 @@ keep append-only from accreting stale, contradictory, or unreadably-large histor
|
||||
- [2026-07-12 — Merge-consent gate auto-grants when satisfied (no redundant prompt); state IS the consent (#314)](#2026-07-12--merge-consent-gate-auto-grants-when-satisfied-no-redundant-prompt-state-is-the-consent-314)
|
||||
- [2026-07-12 — Release path rehearses migrations on a prod-DB copy before promoting (#315)](#2026-07-12--release-path-rehearses-migrations-on-a-prod-db-copy-before-promoting-315)
|
||||
- [2026-07-12 — #295 PR2: SPA session cutover + #301 side-effecting-GET POST-ification](#2026-07-12--295-pr2-spa-session-cutover--301-side-effecting-get-post-ification)
|
||||
- [2026-07-12 — Enforcing CSP + Permissions-Policy on the host (#319, ZAP baseline)](#2026-07-12--enforcing-csp--permissions-policy-on-the-host-319-zap-baseline)
|
||||
|
||||
---
|
||||
|
||||
@@ -1616,3 +1617,31 @@ residual (OIDC logout):** `POST /api/auth/logout` ends the *app* cookie but not
|
||||
who clicks "Sign out" then "Sign in with SSO" returns without re-entering credentials — a `returnUrl`/RP-initiated
|
||||
logout is a future nicety. Docs: `spa-conventions.md §5e` (SPA seams), `api-conventions.md §9`, `e2e-local.md`
|
||||
(browser setup/login flow). Refs #295 #301 #197.
|
||||
|
||||
## 2026-07-12 — Enforcing CSP + Permissions-Policy on the host (#319, ZAP baseline)
|
||||
|
||||
Completes the CSP that the #279 baseline-headers entry deferred ("CSP must be validated against the ChicoryTV
|
||||
SPA's inline assets"). Surfaced by the #314 out-of-ecosystem ZAP baseline (missing CSP/Permissions-Policy WARNs);
|
||||
a **#197 exit item**. `SecurityHeadersMiddleware` now also sets `Permissions-Policy` (deny-all for
|
||||
camera/microphone/geolocation/payment/usb) and an **enforcing** `Content-Security-Policy`.
|
||||
|
||||
- **Enforce, not report-only.** Report-only was the issue's acceptable fallback, but the SPA's asset graph is
|
||||
small and fully knowable, so we ship an enforcing policy (report-only leaves the ZAP WARN and provides no real
|
||||
protection). The policy: `default-src 'self'`; `script-src 'self' '<sha256 of the inline theme-bootstrap
|
||||
script>'` (**no** `'unsafe-inline'`/`'unsafe-eval'` — the real XSS win); `style-src 'self' 'unsafe-inline'
|
||||
https://fonts.googleapis.com`; `img-src 'self' data: blob:`; `font-src 'self' data: https://fonts.gstatic.com`;
|
||||
`connect-src 'self'`; `object-src 'none'`; `base-uri 'self'`; `frame-ancestors 'none'`; `form-action 'self'`.
|
||||
- **Why each relaxation.** The SPA is a static file, so a per-response nonce is impossible → the one inline
|
||||
theme-bootstrap `<script>` is allow-listed **by hash**; `SecurityHeadersMiddlewareTests.Csp_Script_Hash_Should_
|
||||
Match_The_Spa_Index` hashes the committed `web/index.html` (Vite copies the inline script verbatim, and the
|
||||
built `wwwroot/app` is gitignored/absent in CI) and fails if the two drift. `style-src 'unsafe-inline'` covers
|
||||
React's inline `style=""` attributes (no CSS-in-JS lib to hash). The **Google Fonts** hosts are required — the
|
||||
SPA CSS `@import`s the Geist web font (caught by **live-E2E**, which the static grep missed); self-hosting the
|
||||
font to drop the Google dependency is a follow-on hardening, not this issue. `img-src data: blob:` covers
|
||||
favicon/generated-image data URIs and object-URL upload previews.
|
||||
- **Scoped: `/docs` (Scalar) and `/openapi` are excluded.** The Scalar API-reference UI relies on inline bootstrap
|
||||
scripts/styles a strict CSP would break; it keeps the baseline headers (nosniff/frame/referrer) but no CSP.
|
||||
Hardening that admin surface (self-hosted Scalar or a Scalar-tuned CSP) is a #197 follow-up. Everything else —
|
||||
SPA, `/api`, `/artwork`, `/iptv` — gets the CSP (non-HTML responses simply never exercise the script/style
|
||||
directives). Verified by live-E2E (SPA renders clean, zero CSP violations) + curl (CSP present on `/app`/`/api`,
|
||||
absent on `/docs`/`/openapi`). HSTS remains out (proxy/TLS decision). Refs #319 #314 #197.
|
||||
|
||||
Reference in New Issue
Block a user