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
83 changes: 78 additions & 5 deletions Pyjoyment/Plugin/SecurityHeaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
<script nonce="<%= csp_nonce() %>">hljs.highlightAll();</script>

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
-----

Expand All @@ -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:
Expand All @@ -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'"]},
Expand All @@ -201,28 +239,46 @@ 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):
continue
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())

Expand Down Expand Up @@ -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]}')
Expand Down
23 changes: 19 additions & 4 deletions Pyjoyment/Plugin/TagHelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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. ::

<script src="/path/to/script.js"></script>
<script defer src="/path/to/script.js"></script>
Expand Down Expand Up @@ -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. ::

<link href="/path/to/foo.css" rel="stylesheet">
<link href="/path/to/foo.css" rel="stylesheet" title="Foo style">
Expand Down Expand Up @@ -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'//<![CDATA[\n{rest.pop()()}\n//]]>' 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})


Expand All @@ -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:
Expand Down Expand Up @@ -864,7 +878,8 @@ def _stylesheet(c: 'Controller', /, *args: Any, **attrs: Any) -> Pyjo.String.HTM
rest = list(args)
content = f'/*<![CDATA[*/\n{rest.pop()()}\n/*]]>*/' 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})


Expand Down
23 changes: 14 additions & 9 deletions Pyjoyment/resources/templates/pyjo/debug.html.ep
Original file line number Diff line number Diff line change
Expand Up @@ -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
<!DOCTYPE html>
<!-- Request ID: <%= c.req.request_id %> -->
<html>
Expand All @@ -18,7 +20,7 @@
%= stylesheet('/pyjo/bootstrap/bootstrap.css')
%= stylesheet('/pyjo/highlight.js/highlight-mojo-dark.css')
%= stylesheet('/pyjo/pyjo.css')
<script>
%= javascript(begin
'use strict';
%# Unlike Mojolicious: highlightAll of highlight.js 11, where Mojo calls initHighlightingOnLoad of highlight.js 10,
%# which highlight.js 11 deprecates
Expand All @@ -28,14 +30,17 @@
new bootstrap.Tooltip(tooltip);
}
});
</script>
<style>
%= end)
%= stylesheet(begin
.social-icon {
width: 32px;
display: inline-block;
line-height: 24px;
}
</style>
.social-icon svg {
height: 23px;
}
%= end)
</head>
<body class="d-flex flex-column h-100">
<header>
Expand Down Expand Up @@ -87,7 +92,7 @@
</div>
</nav>
</header>
<script>
%= javascript(begin
'use strict';
function mojoDrawer(handle, drawer) {
const handleEl = document.querySelector(handle);
Expand All @@ -105,7 +110,7 @@
mojoDrawer('#trace', '#frames');
mojoDrawer('#more', '#infos');
});
</script>
%= end)
<div class="container flex-grow-1">
<div class="row flex-wrap">
<main class="col-sm-12 col-md-8 col-lg-10 py-md-3 pl-md-5">
Expand Down Expand Up @@ -160,7 +165,7 @@
</table>
</div>
<div class="tap">tap for more</div>
<script>
%= javascript(begin
'use strict';
let current = '#context';
function mojoShowcase() {
Expand All @@ -179,7 +184,7 @@
mojoShowcase();
const insightEl = document.querySelector('#insight');
insightEl.classList.toggle('d-none');
</script>
%= end)
% }
</div>
<div id="trace" class="box no-padding more no-top-border border-radius-bottom">
Expand Down Expand Up @@ -335,7 +340,7 @@
<div class="col-sm align-self-center text-center mojo-social">
%# The icon of GitHub is mark-github of Octicons, under the MIT License, https://github.com/primer/octicons
<a alt="GitHub" href="https://github.com/pyjoyment/Pyjoyment" class="social-icon">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" style="height: 23px;"><path fill="currentColor" d="M10.226 17.284c-2.965-.36-5.054-2.493-5.054-5.256 0-1.123.404-2.336 1.078-3.144-.292-.741-.247-2.314.09-2.965.898-.112 2.111.36 2.83 1.01.853-.269 1.752-.404 2.853-.404 1.1 0 1.999.135 2.807.382.696-.629 1.932-1.1 2.83-.988.315.606.36 2.179.067 2.942.72.854 1.101 2 1.101 3.167 0 2.763-2.089 4.852-5.098 5.234.763.494 1.28 1.572 1.28 2.807v2.336c0 .674.561 1.056 1.235.786 4.066-1.55 7.255-5.615 7.255-10.646C23.5 6.188 18.334 1 11.978 1 5.62 1 .5 6.188.5 12.545c0 4.986 3.167 9.12 7.435 10.669.606.225 1.19-.18 1.19-.786V20.63a2.9 2.9 0 0 1-1.078.224c-1.483 0-2.359-.808-2.987-2.313-.247-.607-.517-.966-1.034-1.033-.27-.023-.359-.135-.359-.27 0-.27.45-.471.898-.471.652 0 1.213.404 1.797 1.235.45.651.921.943 1.483.943.561 0 .92-.202 1.437-.719.382-.381.674-.718.944-.943"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="currentColor" d="M10.226 17.284c-2.965-.36-5.054-2.493-5.054-5.256 0-1.123.404-2.336 1.078-3.144-.292-.741-.247-2.314.09-2.965.898-.112 2.111.36 2.83 1.01.853-.269 1.752-.404 2.853-.404 1.1 0 1.999.135 2.807.382.696-.629 1.932-1.1 2.83-.988.315.606.36 2.179.067 2.942.72.854 1.101 2 1.101 3.167 0 2.763-2.089 4.852-5.098 5.234.763.494 1.28 1.572 1.28 2.807v2.336c0 .674.561 1.056 1.235.786 4.066-1.55 7.255-5.615 7.255-10.646C23.5 6.188 18.334 1 11.978 1 5.62 1 .5 6.188.5 12.545c0 4.986 3.167 9.12 7.435 10.669.606.225 1.19-.18 1.19-.786V20.63a2.9 2.9 0 0 1-1.078.224c-1.483 0-2.359-.808-2.987-2.313-.247-.607-.517-.966-1.034-1.033-.27-.023-.359-.135-.359-.27 0-.27.45-.471.898-.471.652 0 1.213.404 1.797 1.235.45.651.921.943 1.483.943.561 0 .92-.202 1.437-.719.382-.381.674-.718.944-.943"/></svg>
</a>
%# Left out from Mojolicious: the links of Mastodon and LinkedIn, where Pyjoyment has no profiles
</div>
Expand Down
6 changes: 4 additions & 2 deletions Pyjoyment/resources/templates/pyjo/exception.html.ep
Original file line number Diff line number Diff line change
@@ -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
<!DOCTYPE html>
<!-- Request ID: <%= c.req.request_id %> -->
<html>
<head>
<title>Server Error</title>
<style>
%= stylesheet(begin
body {
background-color: #caecf6;
}
Expand All @@ -19,7 +21,7 @@
top: 50%;
width: 743px;
}
</style>
%= end)
%= favicon()
</head>
<body><div id="unicat"></div></body>
Expand Down
6 changes: 4 additions & 2 deletions Pyjoyment/resources/templates/pyjo/not_found.html.ep
Original file line number Diff line number Diff line change
@@ -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
<!DOCTYPE html>
<!-- Request ID: <%= c.req.request_id %> -->
<html>
<head>
<title>Page Not Found</title>
<style>
%= stylesheet(begin
a img {
border: 0;
}
Expand All @@ -27,7 +29,7 @@
top: 50%;
width: 306px;
}
</style>
%= end)
%= favicon()
</head>
<body>
Expand Down
Loading
Loading