Pyjoyment.Plugin.SecurityHeaders - Security headers plugin

# Pyjoyment
app.plugin('SecurityHeaders')

# Pyjoyment.Lite
plugin('SecurityHeaders')

# A policy of its own, tried out with the reports of the browser before it is enforced
app.plugin(
    'SecurityHeaders',
    csp_report_only={'default-src': ["'self'"], 'img-src': ["'self'", 'data:']},
    permissions={'camera': [], 'geolocation': ['self'], 'microphone': []},
)

# Another policy for the responses of a route
app.routes.get('/embed').to('embed#show', security_headers={'csp': {'frame-ancestors': ['https:']}})

Pyjoyment.Plugin.SecurityHeaders adds the headers that protect the pages of an application in the browser to every response, of the actions, the static files and the pages of errors alike: Strict-Transport-Security, Content-Security-Policy, Permissions-Policy, X-Content-Type-Options, Referrer-Policy and Cross-Origin-Opener-Policy. A header that the response has already, as one that an action sets, is kept.

Its defaults restrict nothing that a page usually needs: Content-Security-Policy keeps other sites from framing the pages and from changing their base URL, without a policy of the scripts and the styles, which the application gives with csp or tries out first with csp_report_only.

Strict-Transport-Security is sent with a response of a secure request only, as Pyjo.Message.Request.Pyjo_Message_Request.is_secure says, also of a request that a reverse proxy has received with HTTPS, and not for localhost and its subdomains, as a browser would then take every server on the machine of a developer for one of HTTPS only, on any port. A browser ignores it for an IP address.

The options of the policies take Python values, which the plugin turns into the headers, or a string, which is the header as it is, and None or False leaves the header out.

See Pyjoyment.Plugins for a list of plugins that are available by default.

Options

Pyjoyment.Plugin.SecurityHeaders supports the following options.

content_type_options

app.plugin('SecurityHeaders', content_type_options=None)

``X-Content-Type-Options``, defaults to ``nosniff``, so that a browser
takes the type of a response from ``Content-Type`` only.

csp

app.plugin('SecurityHeaders', csp={'default-src': ["'self'"], 'upgrade-insecure-requests': []})
app.plugin('SecurityHeaders', csp="default-src 'self'")

``Content-Security-Policy``, the directives and their sources, defaults
to ``{'base-uri': ["'self'"], 'frame-ancestors': ["'self'"],
'object-src': ["'none'"]}``. A directive with no sources, as
``upgrade-insecure-requests``, has an empty list.

csp_report_only

app.plugin('SecurityHeaders', csp_report_only={'default-src': ["'self'"], 'report-uri': ['/csp-reports']})

``Content-Security-Policy-Report-Only``, a policy that the browser
reports the violations of without enforcing it, as ``csp`` has it,
defaults to ``None``. It goes with ``csp``, so that a stricter policy is
tried out while the current one is enforced.

embedder_policy

app.plugin('SecurityHeaders', embedder_policy='require-corp')

``Cross-Origin-Embedder-Policy``, defaults to ``None``, as
``require-corp`` blocks the resources of other sites that do not allow
it.

hsts

app.plugin('SecurityHeaders', hsts={'max_age': 300})
app.plugin('SecurityHeaders', hsts={'max_age': 63072000, 'include_subdomains': True, 'preload': True})

``Strict-Transport-Security``, with ``max_age`` in seconds,
``include_subdomains`` and ``preload``, defaults to
``{'max_age': 31536000}``, a year. A browser keeps it for that long, so
a site that starts to use it starts with a short one, and
``include_subdomains`` and ``preload`` come once every subdomain has
HTTPS.

max_report_size

app.plugin('SecurityHeaders', reports='/csp-reports', max_report_size=16384)

Largest body of a request to the route of ``reports``, in bytes, defaults
to ``65536``, 64 KiB. A larger one gets ``413 Request Entity Too
Large``.

opener_policy

app.plugin('SecurityHeaders', opener_policy='same-origin-allow-popups')

``Cross-Origin-Opener-Policy``, defaults to ``same-origin``, so that a
page of another site that opens one of the application, or that it
opens, has no reference to its window.

permissions

app.plugin('SecurityHeaders', permissions={'camera': [], 'fullscreen': ['self'], 'geolocation': '*'})

``Permissions-Policy``, the features of the browser and the origins that
may use them, defaults to ``{'camera': [], 'geolocation': [],
'microphone': []}``. An empty list allows a feature to no one, ``self``
to the origin of the page, ``*`` to every origin, and an origin, as
``https://example.com``, to that origin.

referrer_policy

app.plugin('SecurityHeaders', referrer_policy='no-referrer')

``Referrer-Policy``, defaults to ``strict-origin-when-cross-origin``, the
origin alone for the requests to other sites, and nothing for a request
from HTTPS to HTTP.

reports

app.plugin('SecurityHeaders', reports='/csp-reports', csp_report_only={'default-src': ["'self'"]})

The path of a route, named ``csp_reports``, that takes the reports of
the violations of the policies, defaults to ``None``. The policies of
``csp`` and ``csp_report_only`` of a dict without ``report-uri`` or
``report-to`` get both, ``report-uri`` for the browsers without the
Reporting API, and the responses ``Reporting-Endpoints``, as
``csp="/csp-reports"``, which a browser takes from a page of HTTPS only,
with the prefix of an application that is mounted. The route takes the
reports of both, as ``application/csp-report`` and
``application/reports+json``, logs each violation with ``warn``, emits
the hook ``csp_report``, and answers ``204 No Content``.

The route is public and takes the reports of any client, so a report is
what a client says, not what a browser has seen: its values are cut in
the log, and an application that stores the reports limits how many.

resource_policy

app.plugin('SecurityHeaders', resource_policy='same-site')

``Cross-Origin-Resource-Policy``, defaults to ``None``, as a resource of
the application that other sites load, as an image of a CDN, would be
blocked.

Hooks

Pyjoyment.Plugin.SecurityHeaders emits the following hooks.

csp_report

@app.hook('csp_report')
def csp_report(c, report):
    c.app.log.info(f'{report["effectiveDirective"]} blocked {report["blockedURL"]}')

Emitted for each violation of a request to the route of ``reports``,
with the controller and the violation, as the body of a report of the
Reporting API has it, with ``documentURL``, ``blockedURL``,
``effectiveDirective``, ``disposition`` and the others, also for a
report of ``report-uri``, whose fields it renames.

Helpers

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

security_headers

app.routes.get('/embed').to('embed#show', security_headers={'csp': {'frame-ancestors': ['https:']}})

c.stash(security_headers={'permissions': None})

Options of the response, which replace the ones of the plugin, as for a
route whose pages other sites may frame.

See also

Pyjoyment, https://mojolicious.org.

It has no counterpart in Mojolicious.

Classes

class Pyjoyment.Plugin.SecurityHeaders.Pyjoyment_Plugin_SecurityHeaders[source]

Pyjoyment.Plugin.SecurityHeaders inherits all methods from Pyjoyment.Plugin and implements the following new ones.

register(app: Pyjoyment_App, conf: dict[str, Any] | None = None) → None[source]
plugin.register(Pyjoyment.new())
plugin.register(Pyjoyment.new(), {'hsts': {'max_age': 300}})

Register the hook and the helper in Pyjoyment application.