From 873b3e54a567ee2283b6ea0d6caa9f0abfdcc2b0 Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 12 Jul 2026 22:36:44 +0200 Subject: [PATCH] security(#319): enforcing CSP + Permissions-Policy on the host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .../SecurityHeadersMiddlewareTests.cs | 111 +++++++++++++++++- .../Middleware/SecurityHeadersMiddleware.cs | 65 +++++++++- docs/decisions.md | 29 +++++ 3 files changed, 198 insertions(+), 7 deletions(-) diff --git a/ErsatzTV.Tests/Middleware/SecurityHeadersMiddlewareTests.cs b/ErsatzTV.Tests/Middleware/SecurityHeadersMiddlewareTests.cs index 0f2d40452..1ba24774b 100644 --- a/ErsatzTV.Tests/Middleware/SecurityHeadersMiddlewareTests.cs +++ b/ErsatzTV.Tests/Middleware/SecurityHeadersMiddlewareTests.cs @@ -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 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"); + } + } + + /// + /// Guards against drift from the + /// SPA's index.html: every inline <script> 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 (web/index.html, + /// which — unlike the gitignored built wwwroot/app — exists in the CI checkout) matches + /// the served bytes. + /// + [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 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 ", 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 = /ErsatzTV.Tests/Middleware/SecurityHeadersMiddlewareTests.cs + string repoRoot = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(callerFilePath)!, "..", "..")); + return Path.Combine(repoRoot, "web", "index.html"); } } diff --git a/ErsatzTV/Middleware/SecurityHeadersMiddleware.cs b/ErsatzTV/Middleware/SecurityHeadersMiddleware.cs index 3ce81b0ba..278af31d0 100644 --- a/ErsatzTV/Middleware/SecurityHeadersMiddleware.cs +++ b/ErsatzTV/Middleware/SecurityHeadersMiddleware.cs @@ -3,21 +3,76 @@ using Microsoft.AspNetCore.Http; namespace ErsatzTV.Middleware; /// -/// 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). /// nosniff 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 (/docs) and the OpenAPI document (/openapi) — see +/// . 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). /// public class SecurityHeadersMiddleware(RequestDelegate next) { + /// + /// sha256 of the inline theme-bootstrap <script> in the built SPA + /// index.html (ErsatzTV/wwwroot/app). 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 web/index.html's inline script changes, this hash must change with it; + /// SecurityHeadersMiddlewareTests.Csp_Script_Hash_Should_Match_The_Spa_Index + /// guards the two against drift. + /// + public const string SpaInlineScriptHash = "sha256-5qq06L57XDT8IqaUeyjnI1l7bZ+ggOaE4GXF4TpnGwM="; + + /// + /// Enforcing CSP for the SPA plus the API/artwork/IPTV responses. Notes on the choices: + /// + /// script-src 'self' (the Vite module bundle) + the inline theme-bootstrap + /// hash — no 'unsafe-inline'/'unsafe-eval' (the SPA has no eval/CSS-in-JS). + /// style-src 'unsafe-inline': React writes inline style="" attributes + /// (there is no styled-components/emotion in the SPA to hash <style> blocks). + /// fonts.googleapis.com is the Geist web-font stylesheet the SPA CSS @imports + /// (with fonts.gstatic.com in font-src for the font files). Self-hosting the + /// font to drop the Google dependency is a follow-on hardening, not this issue. + /// img-src data: blob:: favicon/generated-image data URIs and object-URL + /// upload previews. + /// connect-src 'self': the SPA only ever fetches same-origin + /// /api, /artwork, /iptv. + /// + /// Non-HTML responses (JSON, images, m3u) never exercise the script/style directives, so the + /// same policy is safe to apply to them. + /// + 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); } } diff --git a/docs/decisions.md b/docs/decisions.md index 73d3fb834..2ab9325bd 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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' ''` (**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 `