From 42cf49eb6fc4b26f906e2d46b7e49a96a2cc680b Mon Sep 17 00:00:00 2001 From: Piotr Roszatycki Date: Wed, 18 Nov 2026 17:53:38 +0100 Subject: [PATCH] Pyjoyment.Plugin.SecurityHeaders: csp_nonce, the nonce of the response The helper csp_nonce makes a nonce of 128 random bits when it is first used, and the hook adds it to the directives of the scripts and the styles of the policies, and Cache-Control: private to a response without one, as a shared cache would give the nonce to every client. The inline scripts and styles of the tag helpers javascript and stylesheet get it when the application has the helper, and the bundled templates use them, with no style attribute, so that a strict policy does not block them. Co-Authored-By: Claude Opus 5.5 --- Pyjoyment/Plugin/SecurityHeaders.py | 83 +++++++++++++++++-- Pyjoyment/Plugin/TagHelpers.py | 23 ++++- .../resources/templates/pyjo/debug.html.ep | 23 +++-- .../templates/pyjo/exception.html.ep | 6 +- .../templates/pyjo/not_found.html.ep | 6 +- t/Pyjoyment/security_headers_lite_app.py | 80 ++++++++++++++++++ t/docs/Pyjoyment_Plugin_SecurityHeaders.py | 23 +++++ 7 files changed, 222 insertions(+), 22 deletions(-) diff --git a/Pyjoyment/Plugin/SecurityHeaders.py b/Pyjoyment/Plugin/SecurityHeaders.py index b06023c3..6f9b9d69 100644 --- a/Pyjoyment/Plugin/SecurityHeaders.py +++ b/Pyjoyment/Plugin/SecurityHeaders.py @@ -131,6 +131,39 @@ the application that other sites load, as an image of a CDN, would be blocked. +Helpers +------- + +:mod:`Pyjoyment.Plugin.SecurityHeaders` implements the following helpers. + +``csp_nonce`` :: + + nonce = c.csp_nonce() + + %= javascript(begin + hljs.highlightAll(); + %= end) + + + The nonce of the response, 128 random bits, made when it is first used, + which the hook adds to the directives ``default-src``, ``script-src``, + ``script-src-elem``, ``style-src`` and ``style-src-elem`` that the + policies of ``csp`` and ``csp_report_only`` have, so that the scripts and + the styles of the response with that nonce run, and the ones that an + attacker would inject do not. The helpers ``javascript`` and + ``stylesheet`` of :mod:`Pyjoyment.Plugin.TagHelpers` give it to their + inline scripts and styles, as the bundled templates use them. A script of + a URL needs no nonce with a source as ``'self'``; with + ``'strict-dynamic'``, it gets one with ``javascript('/app.js', + nonce=c.csp_nonce())``. A nonce has no effect on the ``style`` + attributes, which a policy of the styles blocks. + + A response whose policy has the nonce gets ``Cache-Control: private``, + unless it has a ``Cache-Control`` already, as a shared cache, as a CDN, + would give the same nonce to every client, which would no longer be a + secret. A page that a CDN keeps is better without inline scripts and + styles, with a policy of their sources alone. + Stash ----- @@ -157,7 +190,10 @@ import Pyjo.Exception import Pyjoyment.Plugin -from typing import TYPE_CHECKING, Any +import base64 +import secrets + +from typing import TYPE_CHECKING, Any, cast if TYPE_CHECKING: @@ -176,6 +212,8 @@ 'referrer_policy': 'Referrer-Policy', 'resource_policy': 'Cross-Origin-Resource-Policy', } +# The directives of the scripts and the styles, and the default one of both, which the nonce goes into +_NONCE_DIRECTIVES = ('default-src', 'script-src', 'script-src-elem', 'style-src', 'style-src-elem') _DEFAULTS: dict[str, Any] = { 'content_type_options': 'nosniff', 'csp': {'base-uri': ["'self'"], 'frame-ancestors': ["'self'"], 'object-src': ["'none'"]}, @@ -201,18 +239,23 @@ def register(self, app: 'Pyjoyment.object', conf: dict[str, Any] | None = None) plugin.register(Pyjoyment.new()) plugin.register(Pyjoyment.new(), {'hsts': {'max_age': 300}}) - Register the hook in :mod:`Pyjoyment` application. + Register the hook and the helper in :mod:`Pyjoyment` application. """ options = {**_DEFAULTS, **_options(conf or {})} headers = _headers(options) def after_dispatch(c: 'Pyjoyment.Controller.object') -> None: # An unknown option of the stash is logged, as the response has been rendered already - values = headers - if own := c.stash().get('security_headers'): + values, nonced = headers, False + stash = c.stash() + own: dict[str, Any] = stash.get('security_headers') or {} + if own or 'security_headers.nonce' in stash: if unknown := sorted(set(own) - set(_HEADERS)): c.helpers.log().error(f'Unknown option of SecurityHeaders: {unknown[0]}') - values = _headers({**options, **{k: v for k, v in own.items() if k in _HEADERS}}) + current = {**options, **{k: v for k, v in own.items() if k in _HEADERS}} + current, nonced = _nonce(current, stash.get('security_headers.nonce')) + values = _headers(current) + res_headers = c.res.headers for name, value in values.items(): if name == 'Strict-Transport-Security' and not _secure(c): @@ -220,9 +263,22 @@ def after_dispatch(c: 'Pyjoyment.Controller.object') -> None: if res_headers.header(name) is None: res_headers.header(name, value) + # A shared cache, as a CDN, would give the nonce of the response to every client + if nonced and res_headers.cache_control is None: + res_headers.cache_control = 'private' + + app.helper('csp_nonce', _csp_nonce) app.hook('after_dispatch', after_dispatch) +def _csp_nonce(c: 'Pyjoyment.Controller.object') -> str: + # A nonce of 128 random bits for each response, made when a template or an action first needs it + stash = c.stash() + if (nonce := stash.get('security_headers.nonce')) is None: + nonce = stash['security_headers.nonce'] = base64.b64encode(secrets.token_bytes(16)).decode() + return nonce + + def _csp(policy: dict[str, list[str]]) -> str: return '; '.join(' '.join([directive, *sources]) for directive, sources in policy.items()) @@ -250,6 +306,23 @@ def _hsts(hsts: dict[str, Any]) -> str: return value +def _nonce(options: dict[str, Any], nonce: str | None) -> tuple[dict[str, Any], bool]: + # The nonce in the directives of the scripts and the styles that a policy of a dict has, as a policy without them + # restricts neither, and whether a policy has it, for the Cache-Control of the response + if nonce is None: + return options, False + options = dict(options) + nonced = False + for option in ('csp', 'csp_report_only'): + if isinstance(policy := options[option], dict): + options[option] = { + d: [*sources, f"'nonce-{nonce}'"] if d in _NONCE_DIRECTIVES else sources + for d, sources in cast(dict[str, list[str]], policy).items() + } + nonced = nonced or any(d in _NONCE_DIRECTIVES for d in cast(dict[str, list[str]], policy)) + return options, nonced + + def _options(conf: dict[str, Any]) -> dict[str, Any]: if unknown := sorted(set(conf) - set(_HEADERS)): raise Pyjo.Exception.new(f'Unknown option of SecurityHeaders: {unknown[0]}') diff --git a/Pyjoyment/Plugin/TagHelpers.py b/Pyjoyment/Plugin/TagHelpers.py index bc0a9ec8..cc51b8aa 100644 --- a/Pyjoyment/Plugin/TagHelpers.py +++ b/Pyjoyment/Plugin/TagHelpers.py @@ -281,7 +281,9 @@ const a = 'b'; %= end) -Generate portable ``script`` tag for JavaScript asset. :: +Generate portable ``script`` tag for JavaScript asset. An inline script +gets the nonce of the helper ``csp_nonce``, if the application has one, as +:mod:`Pyjoyment.Plugin.SecurityHeaders` gives it. :: @@ -472,7 +474,9 @@ body {color: #000} %= end) -Generate portable ``style`` or ``link`` tag for CSS asset. :: +Generate portable ``style`` or ``link`` tag for CSS asset. An inline style +gets the nonce of the helper ``csp_nonce``, if the application has one, as +:mod:`Pyjoyment.Plugin.SecurityHeaders` gives it. :: @@ -800,7 +804,8 @@ def _input(c: 'Controller', name: str, /, *args: Any, **attrs: Any) -> Pyjo.Stri def _javascript(c: 'Controller', /, *args: Any, **attrs: Any) -> Pyjo.String.HTML.object: rest = list(args) content = f'//' if rest and callable(rest[-1]) else '' - src = {'src': _file_url(c, rest[0])} if rest else {} + # Not in Mojolicious: the nonce of an inline script, for a Content-Security-Policy + src = {'src': _file_url(c, rest[0])} if rest else _nonce(c) return _tag('script', lambda: content, **{**src, **attrs}) @@ -825,6 +830,15 @@ def _link_to(c: 'Controller', content: Any, /, *args: Any, **attrs: Any) -> Pyjo return _tag('a', content, **{'href': c.url_for(*url), **attrs}) +# Not in Mojolicious: the nonce of the inline script or style, of a helper csp_nonce, as the one of +# Pyjoyment.Plugin.SecurityHeaders, for a Content-Security-Policy +def _nonce(c: 'Controller') -> dict[str, Any]: + if c.app.renderer.get_helper('csp_nonce') is None: + return {} + helpers: Any = c.helpers + return {'nonce': helpers.csp_nonce()} + + # Unlike Mojolicious: the attributes of an option or a group are a dict after its value, where Mojo takes a flat list of # names and values, as a list of Python keeps them as one value def _option(values: set[str], pair: Any) -> Pyjo.String.HTML.object: @@ -864,7 +878,8 @@ def _stylesheet(c: 'Controller', /, *args: Any, **attrs: Any) -> Pyjo.String.HTM rest = list(args) content = f'/**/' if rest and callable(rest[-1]) else '' if not rest: - return _tag('style', lambda: content, **attrs) + # Not in Mojolicious: the nonce of an inline style, for a Content-Security-Policy + return _tag('style', lambda: content, **{**_nonce(c), **attrs}) return _tag('link', **{'rel': 'stylesheet', 'href': _file_url(c, rest[0]), **attrs}) diff --git a/Pyjoyment/resources/templates/pyjo/debug.html.ep b/Pyjoyment/resources/templates/pyjo/debug.html.ep index 06d9d08e..0b8e184b 100644 --- a/Pyjoyment/resources/templates/pyjo/debug.html.ep +++ b/Pyjoyment/resources/templates/pyjo/debug.html.ep @@ -2,6 +2,8 @@ %# Renamed from Mojolicious: the files of the page are in pyjo/, where Mojo has them in mojo/, its stylesheet is %# pyjo/pyjo.css, where Mojo has mojo/mojo.css, and the language of highlight.js for templates is pyjoyment, where Mojo %# has mojolicious; the links of the page are those of Pyjoyment +%# Unlike Mojolicious: the inline styles and scripts are of the tag helpers, which give them the nonce of a +%# Content-Security-Policy @@ -18,7 +20,7 @@ %= stylesheet('/pyjo/bootstrap/bootstrap.css') %= stylesheet('/pyjo/highlight.js/highlight-mojo-dark.css') %= stylesheet('/pyjo/pyjo.css') - - + .social-icon svg { + height: 23px; + } + %= end)
@@ -87,7 +92,7 @@
- + %= end)
@@ -160,7 +165,7 @@
tap for more
- + %= end) % }
@@ -335,7 +340,7 @@
%# The icon of GitHub is mark-github of Octicons, under the MIT License, https://github.com/primer/octicons %# Left out from Mojolicious: the links of Mastodon and LinkedIn, where Pyjoyment has no profiles
diff --git a/Pyjoyment/resources/templates/pyjo/exception.html.ep b/Pyjoyment/resources/templates/pyjo/exception.html.ep index 76908232..3334b861 100644 --- a/Pyjoyment/resources/templates/pyjo/exception.html.ep +++ b/Pyjoyment/resources/templates/pyjo/exception.html.ep @@ -1,11 +1,13 @@ %# Renamed from Mojolicious: the image of the unicat is pyjo/failunicat.png, where Mojo has mojo/failraptor.png, and %# its element is #unicat, where Mojo has #raptor +%# Unlike Mojolicious: the inline styles and scripts are of the tag helpers, which give them the nonce of a +%# Content-Security-Policy Server Error - + %= end) %= favicon()
diff --git a/Pyjoyment/resources/templates/pyjo/not_found.html.ep b/Pyjoyment/resources/templates/pyjo/not_found.html.ep index 40253975..04de94c0 100644 --- a/Pyjoyment/resources/templates/pyjo/not_found.html.ep +++ b/Pyjoyment/resources/templates/pyjo/not_found.html.ep @@ -1,11 +1,13 @@ %# Renamed from Mojolicious: the image of the unicat is pyjo/nounicat.png, where Mojo has mojo/noraptor.png, and its %# element is #nounicat, where Mojo has #noraptor +%# Unlike Mojolicious: the inline styles and scripts are of the tag helpers, which give them the nonce of a +%# Content-Security-Policy Page Not Found - + %= end) %= favicon() diff --git a/t/Pyjoyment/security_headers_lite_app.py b/t/Pyjoyment/security_headers_lite_app.py index 7349a8b6..d3c18c7f 100644 --- a/t/Pyjoyment/security_headers_lite_app.py +++ b/t/Pyjoyment/security_headers_lite_app.py @@ -12,6 +12,8 @@ from Pyjo.Test import * from Pyjoyment.Lite import app, get, plugin +import re + # Not in Mojolicious: Pyjoyment.Plugin.SecurityHeaders, the headers that protect the pages in the browser @@ -146,6 +148,84 @@ def application(conf=None): other.header_is(name, value) like_ok(str(logs), r'\[error\] .*Unknown option of SecurityHeaders: cps', 'right message') +INLINE = """ +%= javascript(begin + const a = 'b'; +%= end) +%= stylesheet(begin + body {color: #000} +%= end) +%= javascript('/app.js') +""" + + +def nonce_of(t, header='Content-Security-Policy'): + # The nonce of the policy, which every inline script and style of the page has, and no style attribute + m = re.search(r"'nonce-([A-Za-z0-9+/=]+)'", t.tx.res.headers.header(header) or '') + if not ok(m, 'nonce in the policy'): + return None + dom = t.tx.res.dom() + inline = dom.find('script:not([src]), style') + ok(len(inline) > 0, 'inline scripts or styles') + is_deeply_ok(sorted({e.attr('nonce') for e in inline}), [m[1]], 'nonce of every inline script and style') + is_ok(len(dom.find('[style]')), 0, 'no style attributes') + return m[1] + + +with subtest('Nonce'): + other = application({'csp': {'default-src': ["'self'"], 'script-src': ["'self'"], 'img-src': ["'self'", 'data:']}}) + other.app.routes.get('/inline', lambda c: c.render(inline=INLINE)) + other.app.routes.get('/cached', lambda c: c.res.headers.set(cache_control='no-store') and c.render(inline=INLINE)) + other.app.routes.get('/dies', lambda c: c.helpers.reply.exception('Oops!')) + other.get_ok('/inline').status_is(200).header_is('Cache-Control', 'private') + nonce = nonce_of(other) + like_ok( + other.tx.res.headers.content_security_policy, + rf"^default-src 'self' 'nonce-{re.escape(nonce)}'; script-src 'self' 'nonce-{re.escape(nonce)}'; img-src 'self' data:$", + 'nonce in the directives of the scripts and the styles', + ) + other.element_exists('script[src="/app.js"]:not([nonce])') + other.get_ok('/inline') + isnt_ok(nonce_of(other), nonce, 'a new nonce for each response') + other.get_ok('/cached').status_is(200).header_is('Cache-Control', 'no-store') + other.get_ok('/').status_is(200).header_is( + 'Content-Security-Policy', "default-src 'self'; script-src 'self'; img-src 'self' data:" + ).header_exists_not('Cache-Control') + + # The bundled pages, of production and of development + for mode in ('production', 'development'): + other.app.mode = mode + other.get_ok('/missing').status_is(404).header_is('Cache-Control', 'private') + nonce_of(other) + other.get_ok('/dies').status_is(500).header_is('Cache-Control', 'private') + nonce_of(other) + other.app.mode = 'development' + + # The policy of the report-only header gets the nonce too + other = application({'csp': None, 'csp_report_only': {'default-src': ["'self'"]}}) + other.app.routes.get('/inline', lambda c: c.render(inline=INLINE)) + other.get_ok('/inline').status_is(200).header_exists_not('Content-Security-Policy') + nonce_of(other, 'Content-Security-Policy-Report-Only') + + # A policy without the directives of the scripts and the styles restricts neither + other = application() + other.app.routes.get('/inline', lambda c: c.render(inline=INLINE)) + ( + other.get_ok('/inline') + .status_is(200) + .header_is('Content-Security-Policy', HEADERS['Content-Security-Policy']) + .header_exists_not('Cache-Control') + .element_exists('script[nonce]') + ) + + # Without the plugin, no nonce + plain = Pyjoyment.new() + plain.log.level = 'fatal' + plain.routes.get('/inline', lambda c: c.render(inline=INLINE)) + Pyjo.Test.Pyjo.new(plain).get_ok('/inline').status_is(200).element_exists('script:not([nonce])').element_exists_not( + '[nonce]' + ) + with subtest('Unknown option'): throws_ok( lambda: Pyjoyment.new().plugin('SecurityHeaders', {'cps': {}}), diff --git a/t/docs/Pyjoyment_Plugin_SecurityHeaders.py b/t/docs/Pyjoyment_Plugin_SecurityHeaders.py index ae11ad16..ea6e3d6d 100644 --- a/t/docs/Pyjoyment_Plugin_SecurityHeaders.py +++ b/t/docs/Pyjoyment_Plugin_SecurityHeaders.py @@ -11,6 +11,8 @@ from Pyjoyment.Lite import app as lite from Pyjoyment.Lite import get, plugin +import re + lite.log.level = 'fatal' @@ -130,6 +132,27 @@ def embed(c): app.plugin('SecurityHeaders', resource_policy='same-site') Pyjo.Test.Pyjo.new(app).get_ok('/').header_is('Cross-Origin-Resource-Policy', 'same-site') +with subtest('csp_nonce'): + app = application() + app.plugin('SecurityHeaders', csp={'script-src': ["'self'"]}) + app.routes.get('/nonce', lambda c: c.render(text=c.csp_nonce())) + template = ( + '%= javascript(begin\n' + ' hljs.highlightAll();\n' + '%= end)\n' + '\n' + "%= javascript('/app.js', nonce=c.csp_nonce())\n" + ) + app.routes.get('/page', lambda c: c.render(inline=template)) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/nonce').status_is(200) + nonce = t.tx.res.text + t.header_is('Content-Security-Policy', f"script-src 'self' 'nonce-{nonce}'").header_is('Cache-Control', 'private') + t.get_ok('/page').status_is(200) + nonces = {e.attr('nonce') for e in t.tx.res.dom('script')} + is_ok(len(nonces), 1, 'one nonce') + like_ok(t.tx.res.headers.content_security_policy, rf"'nonce-{re.escape(nonces.pop())}'$", 'nonce of the page') + with subtest('security_headers'): app = application() app.plugin('SecurityHeaders')