From e45ad06997f7aa044f44a0b506c8f48c3717bd45 Mon Sep 17 00:00:00 2001 From: Piotr Roszatycki Date: Wed, 18 Nov 2026 17:44:33 +0100 Subject: [PATCH] Pyjoyment.Plugin.SecurityHeaders: the headers that protect the pages Strict-Transport-Security for secure requests, but not for localhost, Content-Security-Policy and its report-only policy, Permissions-Policy, X-Content-Type-Options, Referrer-Policy and the Cross-Origin-*-Policy headers on every response, as Python values or strings. A header that the action sets is kept, and the stash security_headers replaces the options for a response. Co-Authored-By: Claude Opus 5.5 --- Pyjoyment/Plugin/SecurityHeaders.py | 284 ++++++++++++++++++ Pyjoyment/Plugins.py | 4 + docs/api/Pyjoyment_Plugin_SecurityHeaders.rst | 2 + docs/guides/index.rst | 1 + pyproject.toml | 1 + t/Pyjoyment/security_headers_lite_app.py | 156 ++++++++++ t/docs/Pyjoyment_Plugin_SecurityHeaders.py | 153 ++++++++++ 7 files changed, 601 insertions(+) create mode 100644 Pyjoyment/Plugin/SecurityHeaders.py create mode 100644 docs/api/Pyjoyment_Plugin_SecurityHeaders.rst create mode 100644 t/Pyjoyment/security_headers_lite_app.py create mode 100644 t/docs/Pyjoyment_Plugin_SecurityHeaders.py diff --git a/Pyjoyment/Plugin/SecurityHeaders.py b/Pyjoyment/Plugin/SecurityHeaders.py new file mode 100644 index 00000000..b06023c3 --- /dev/null +++ b/Pyjoyment/Plugin/SecurityHeaders.py @@ -0,0 +1,284 @@ +""" +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:']}}) + +:mod:`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 :attr:`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 :mod:`Pyjoyment.Plugins` for a list of plugins that are available by +default. + +Options +------- + +:mod:`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. + +``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. + +``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. + +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 +-------- + +:mod:`Pyjoyment`, https://mojolicious.org. + +It has no counterpart in Mojolicious. + +Classes +------- +""" + +import Pyjo.Exception +import Pyjoyment.Plugin + +from typing import TYPE_CHECKING, Any + + +if TYPE_CHECKING: + import Pyjoyment + import Pyjoyment.Controller + +# The headers of the options, and their defaults +_HEADERS = { + 'content_type_options': 'X-Content-Type-Options', + 'csp': 'Content-Security-Policy', + 'csp_report_only': 'Content-Security-Policy-Report-Only', + 'embedder_policy': 'Cross-Origin-Embedder-Policy', + 'hsts': 'Strict-Transport-Security', + 'opener_policy': 'Cross-Origin-Opener-Policy', + 'permissions': 'Permissions-Policy', + 'referrer_policy': 'Referrer-Policy', + 'resource_policy': 'Cross-Origin-Resource-Policy', +} +_DEFAULTS: dict[str, Any] = { + 'content_type_options': 'nosniff', + 'csp': {'base-uri': ["'self'"], 'frame-ancestors': ["'self'"], 'object-src': ["'none'"]}, + 'csp_report_only': None, + 'embedder_policy': None, + 'hsts': {'max_age': 31536000}, + 'opener_policy': 'same-origin', + 'permissions': {'camera': [], 'geolocation': [], 'microphone': []}, + 'referrer_policy': 'strict-origin-when-cross-origin', + 'resource_policy': None, +} + + +class Pyjoyment_Plugin_SecurityHeaders(Pyjoyment.Plugin.object): + """ + :mod:`Pyjoyment.Plugin.SecurityHeaders` inherits all methods from + :mod:`Pyjoyment.Plugin` and implements the following new ones. + """ + + def register(self, app: 'Pyjoyment.object', conf: dict[str, Any] | None = None) -> None: + """:: + + plugin.register(Pyjoyment.new()) + plugin.register(Pyjoyment.new(), {'hsts': {'max_age': 300}}) + + Register the hook 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'): + 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}}) + 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) + + app.hook('after_dispatch', after_dispatch) + + +def _csp(policy: dict[str, list[str]]) -> str: + return '; '.join(' '.join([directive, *sources]) for directive, sources in policy.items()) + + +def _headers(options: dict[str, Any]) -> dict[str, str]: + # The values of the headers of the options, without the ones that are left out + headers: dict[str, str] = {} + for option, name in _HEADERS.items(): + if (value := options[option]) is None or value is False: + continue + if not isinstance(value, str): + value = ( + _hsts(value) if option == 'hsts' else _permissions(value) if option == 'permissions' else _csp(value) + ) + headers[name] = value + return headers + + +def _hsts(hsts: dict[str, Any]) -> str: + value = f'max-age={int(hsts.get("max_age", 31536000))}' + if hsts.get('include_subdomains'): + value += '; includeSubDomains' + if hsts.get('preload'): + value += '; preload' + return value + + +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]}') + return conf + + +def _permissions(policy: dict[str, list[str] | str]) -> str: + # The allowlists of the structured fields of RFC 8941, as (self "https://example.com"), or * for every origin + features: list[str] = [] + for feature, origins in policy.items(): + if isinstance(origins, str): + origins = [origins] + if origins == ['*']: + features.append(f'{feature}=*') + continue + tokens = [o.strip("'") if o.strip("'") in ('self', 'src') else f'"{o}"' for o in origins] + features.append(f'{feature}=({" ".join(tokens)})') + return ', '.join(features) + + +def _secure(c: 'Pyjoyment.Controller.object') -> bool: + # Not for localhost, whose servers on every port a browser would take for ones of HTTPS only + req = c.req + if not req.is_secure: + return False + host = (req.url.to_abs().host or '').lower() + return host != 'localhost' and not host.endswith('.localhost') + + +new = Pyjoyment_Plugin_SecurityHeaders.new +object = Pyjoyment_Plugin_SecurityHeaders +SecurityHeaders = Pyjoyment_Plugin_SecurityHeaders diff --git a/Pyjoyment/Plugins.py b/Pyjoyment/Plugins.py index dc5776e5..9712ba4e 100644 --- a/Pyjoyment/Plugins.py +++ b/Pyjoyment/Plugins.py @@ -60,6 +60,10 @@ :mod:`Pyjoyment.Plugin.PyRenderer` Renderer for template strings, loaded automatically. +:mod:`Pyjoyment.Plugin.SecurityHeaders` + Headers that protect the pages in the browser, as HSTS, CSP and + Permissions-Policy. + :mod:`Pyjoyment.Plugin.TagHelpers` Template specific helper collection, loaded automatically. diff --git a/docs/api/Pyjoyment_Plugin_SecurityHeaders.rst b/docs/api/Pyjoyment_Plugin_SecurityHeaders.rst new file mode 100644 index 00000000..b97fc24e --- /dev/null +++ b/docs/api/Pyjoyment_Plugin_SecurityHeaders.rst @@ -0,0 +1,2 @@ +.. automodule:: Pyjoyment.Plugin.SecurityHeaders + :members: diff --git a/docs/guides/index.rst b/docs/guides/index.rst index 8869b466..58944c15 100644 --- a/docs/guides/index.rst +++ b/docs/guides/index.rst @@ -386,6 +386,7 @@ This is the class hierarchy of the :mod:`Pyjoyment` distribution. - :mod:`Pyjoyment.Plugin.HeaderCondition` - :mod:`Pyjoyment.Plugin.Mount` - :mod:`Pyjoyment.Plugin.PyRenderer` + - :mod:`Pyjoyment.Plugin.SecurityHeaders` - :mod:`Pyjoyment.Plugin.TagHelpers` - :mod:`Pyjoyment.Renderer` diff --git a/pyproject.toml b/pyproject.toml index 02f90b28..b3b5e0cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -405,6 +405,7 @@ strict = [ "Pyjoyment/Plugin/JSONConfig.py", "Pyjoyment/Plugin/Mount.py", "Pyjoyment/Plugin/PyRenderer.py", + "Pyjoyment/Plugin/SecurityHeaders.py", "Pyjoyment/Plugin/TagHelpers.py", "Pyjoyment/Plugin/TOMLConfig.py", "Pyjoyment/Plugin/YAMLConfig.py", diff --git a/t/Pyjoyment/security_headers_lite_app.py b/t/Pyjoyment/security_headers_lite_app.py new file mode 100644 index 00000000..7349a8b6 --- /dev/null +++ b/t/Pyjoyment/security_headers_lite_app.py @@ -0,0 +1,156 @@ +import os + + +os.environ['PYJO_MODE'] = 'development' +# The requests of HTTPS through a reverse proxy, as X-Forwarded-Proto says, for Strict-Transport-Security +os.environ['PYJO_REVERSE_PROXY'] = '1' + +import Pyjo.Test.Pyjo +import Pyjoyment + +from Pyjo.File import tempdir +from Pyjo.Test import * +from Pyjoyment.Lite import app, get, plugin + + +# Not in Mojolicious: Pyjoyment.Plugin.SecurityHeaders, the headers that protect the pages in the browser + +app.log.level = 'fatal' + +plugin('SecurityHeaders') + +get('/', {'text': 'Hello!'}) + + +@get('/own') +def own(c): + c.res.headers.content_security_policy = "default-src 'none'" + c.res.headers.referrer_policy = 'no-referrer' + c.render(text='Own!') + + +@get('/dies') +def dies(c): + raise Exception('Oops!') + + +public = tempdir() +public.child('hello.txt').spew('Hello static!') +app.static.paths.insert(0, public.to_str()) + +t = Pyjo.Test.Pyjo.new() + +HEADERS = { + 'Content-Security-Policy': "base-uri 'self'; frame-ancestors 'self'; object-src 'none'", + 'Cross-Origin-Opener-Policy': 'same-origin', + 'Permissions-Policy': 'camera=(), geolocation=(), microphone=()', + 'Referrer-Policy': 'strict-origin-when-cross-origin', + 'X-Content-Type-Options': 'nosniff', +} + + +def application(conf=None): + # An application of its own, with the options of the plugin + other = Pyjoyment.new() + other.log.level = 'fatal' + other.plugin('SecurityHeaders', conf) + other.routes.get('/', lambda c: c.render(text='Hello!')) + return Pyjo.Test.Pyjo.new(other) + + +with subtest('Every response'): + for path, code in (('/', 200), ('/hello.txt', 200), ('/missing', 404), ('/dies', 500)): + t.get_ok(path).status_is(code) + for name, value in HEADERS.items(): + t.header_is(name, value) + +with subtest('Headers of the action'): + ( + t.get_ok('/own') + .status_is(200) + .header_is('Content-Security-Policy', "default-src 'none'") + .header_is('Referrer-Policy', 'no-referrer') + .header_is('X-Content-Type-Options', 'nosniff') + ) + +with subtest('Strict-Transport-Security'): + t.get_ok('/', {'Host': 'example.com'}).status_is(200).header_exists_not('Strict-Transport-Security') + t.get_ok('/', {'Host': 'example.com', 'X-Forwarded-Proto': 'https'}).header_is( + 'Strict-Transport-Security', 'max-age=31536000' + ) + t.get_ok('/hello.txt', {'Host': 'example.com', 'X-Forwarded-Proto': 'https'}).header_is( + 'Strict-Transport-Security', 'max-age=31536000' + ) + # Not for localhost, whose servers on every port would be ones of HTTPS only + for host in ('localhost', 'LocalHost:3000', 'app.localhost'): + t.get_ok('/', {'Host': host, 'X-Forwarded-Proto': 'https'}).header_exists_not('Strict-Transport-Security') + other = application({'hsts': {'max_age': 0}}) + other.get_ok('/', {'Host': 'example.com', 'X-Forwarded-Proto': 'https'}).header_is( + 'Strict-Transport-Security', 'max-age=0' + ) + other = application({'hsts': 'max-age=60; includeSubDomains'}) + other.get_ok('/', {'Host': 'example.com', 'X-Forwarded-Proto': 'https'}).header_is( + 'Strict-Transport-Security', 'max-age=60; includeSubDomains' + ) + +with subtest('Left out'): + other = application( + { + 'content_type_options': None, + 'csp': False, + 'hsts': None, + 'opener_policy': None, + 'permissions': None, + 'referrer_policy': None, + } + ) + other.get_ok('/', {'Host': 'example.com', 'X-Forwarded-Proto': 'https'}).status_is(200) + for name in (*HEADERS, 'Strict-Transport-Security'): + other.header_exists_not(name) + +with subtest('Permissions-Policy'): + other = application({'permissions': {'geolocation': ["'self'", 'https://maps.example.com'], 'fullscreen': ['*']}}) + other.get_ok('/').header_is('Permissions-Policy', 'geolocation=(self "https://maps.example.com"), fullscreen=*') + other = application({'permissions': {'autoplay': 'self'}}) + other.get_ok('/').header_is('Permissions-Policy', 'autoplay=(self)') + other = application({'permissions': 'camera=()'}) + other.get_ok('/').header_is('Permissions-Policy', 'camera=()') + +with subtest('Content-Security-Policy and its reports'): + other = application( + { + 'csp': {'default-src': ["'self'"]}, + 'csp_report_only': {'default-src': ["'self'"], 'script-src': ["'self'"], 'report-uri': ['/csp-reports']}, + } + ) + ( + other.get_ok('/') + .header_is('Content-Security-Policy', "default-src 'self'") + .header_is( + 'Content-Security-Policy-Report-Only', "default-src 'self'; script-src 'self'; report-uri /csp-reports" + ) + ) + +with subtest('Options of the response'): + other = application() + other.app.routes.get('/frame').to(cb=lambda c: c.render(text='Frame!'), security_headers={'csp': None}) + other.app.routes.get('/typo').to(cb=lambda c: c.render(text='Typo!'), security_headers={'cps': None}) + other.get_ok('/frame').status_is(200).header_exists_not('Content-Security-Policy').header_is( + 'X-Content-Type-Options', 'nosniff' + ) + other.get_ok('/').header_is('Content-Security-Policy', HEADERS['Content-Security-Policy']) + # An unknown option of the response is logged, as the response has been rendered already + with other.app.log.capture('error') as logs: + other.get_ok('/typo').status_is(200).content_is('Typo!') + for name, value in HEADERS.items(): + other.header_is(name, value) + like_ok(str(logs), r'\[error\] .*Unknown option of SecurityHeaders: cps', 'right message') + +with subtest('Unknown option'): + throws_ok( + lambda: Pyjoyment.new().plugin('SecurityHeaders', {'cps': {}}), + Exception, + 'Unknown option of SecurityHeaders: cps', + ) + +done_testing() diff --git a/t/docs/Pyjoyment_Plugin_SecurityHeaders.py b/t/docs/Pyjoyment_Plugin_SecurityHeaders.py new file mode 100644 index 00000000..ae11ad16 --- /dev/null +++ b/t/docs/Pyjoyment_Plugin_SecurityHeaders.py @@ -0,0 +1,153 @@ +import os + + +# The requests of HTTPS through a reverse proxy, as X-Forwarded-Proto says, for Strict-Transport-Security +os.environ['PYJO_REVERSE_PROXY'] = '1' + +import Pyjo.Test.Pyjo +import Pyjoyment + +from Pyjo.Test import * +from Pyjoyment.Lite import app as lite +from Pyjoyment.Lite import get, plugin + + +lite.log.level = 'fatal' + +HTTPS = {'Host': 'example.com', 'X-Forwarded-Proto': 'https'} + + +def application(): + app = Pyjoyment.new() + app.log.level = 'fatal' + app.routes.get('/', lambda c: c.render(text='Hello!')) + return app + + +def embed(c): + c.render(text='Embedded!') + + +with subtest('Synopsis'): + # Pyjoyment + app = application() + app.plugin('SecurityHeaders') + t = Pyjo.Test.Pyjo.new(app) + ( + t.get_ok('/', HTTPS) + .status_is(200) + .header_is('Strict-Transport-Security', 'max-age=31536000') + .header_is('Content-Security-Policy', "base-uri 'self'; frame-ancestors 'self'; object-src 'none'") + .header_is('Permissions-Policy', 'camera=(), geolocation=(), microphone=()') + .header_is('X-Content-Type-Options', 'nosniff') + .header_is('Referrer-Policy', 'strict-origin-when-cross-origin') + .header_is('Cross-Origin-Opener-Policy', 'same-origin') + .header_exists_not('Content-Security-Policy-Report-Only') + .header_exists_not('Cross-Origin-Embedder-Policy') + .header_exists_not('Cross-Origin-Resource-Policy') + ) + + # Pyjoyment.Lite + plugin('SecurityHeaders') + get('/', {'text': 'Hello!'}) + t = Pyjo.Test.Pyjo.new() + t.get_ok('/').status_is(200).header_is('X-Content-Type-Options', 'nosniff') + + # A policy of its own, tried out with the reports of the browser before it is enforced + app = application() + app.plugin( + 'SecurityHeaders', + csp_report_only={'default-src': ["'self'"], 'img-src': ["'self'", 'data:']}, + permissions={'camera': [], 'geolocation': ['self'], 'microphone': []}, + ) + t = Pyjo.Test.Pyjo.new(app) + ( + t.get_ok('/') + .status_is(200) + .header_is('Content-Security-Policy-Report-Only', "default-src 'self'; img-src 'self' data:") + .header_is('Content-Security-Policy', "base-uri 'self'; frame-ancestors 'self'; object-src 'none'") + .header_is('Permissions-Policy', 'camera=(), geolocation=(self), microphone=()') + ) + + # Another policy for the responses of a route + app.routes.get('/embed').to(cb=embed, security_headers={'csp': {'frame-ancestors': ['https:']}}) + t.get_ok('/embed').status_is(200).header_is('Content-Security-Policy', 'frame-ancestors https:') + t.get_ok('/').status_is(200).header_like('Content-Security-Policy', r"^base-uri 'self'") + +with subtest('content_type_options'): + app = application() + app.plugin('SecurityHeaders', content_type_options=None) + Pyjo.Test.Pyjo.new(app).get_ok('/').status_is(200).header_exists_not('X-Content-Type-Options') + +with subtest('csp'): + app = application() + app.plugin('SecurityHeaders', csp={'default-src': ["'self'"], 'upgrade-insecure-requests': []}) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/').header_is('Content-Security-Policy', "default-src 'self'; upgrade-insecure-requests") + app = application() + app.plugin('SecurityHeaders', csp="default-src 'self'") + Pyjo.Test.Pyjo.new(app).get_ok('/').header_is('Content-Security-Policy', "default-src 'self'") + +with subtest('csp_report_only'): + app = application() + app.plugin('SecurityHeaders', csp_report_only={'default-src': ["'self'"], 'report-uri': ['/csp-reports']}) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/').header_is('Content-Security-Policy-Report-Only', "default-src 'self'; report-uri /csp-reports") + +with subtest('embedder_policy'): + app = application() + app.plugin('SecurityHeaders', embedder_policy='require-corp') + Pyjo.Test.Pyjo.new(app).get_ok('/').header_is('Cross-Origin-Embedder-Policy', 'require-corp') + +with subtest('hsts'): + app = application() + app.plugin('SecurityHeaders', hsts={'max_age': 300}) + Pyjo.Test.Pyjo.new(app).get_ok('/', HTTPS).header_is('Strict-Transport-Security', 'max-age=300') + app = application() + app.plugin('SecurityHeaders', hsts={'max_age': 63072000, 'include_subdomains': True, 'preload': True}) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/', HTTPS).header_is('Strict-Transport-Security', 'max-age=63072000; includeSubDomains; preload') + +with subtest('opener_policy'): + app = application() + app.plugin('SecurityHeaders', opener_policy='same-origin-allow-popups') + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/').header_is('Cross-Origin-Opener-Policy', 'same-origin-allow-popups') + +with subtest('permissions'): + app = application() + app.plugin('SecurityHeaders', permissions={'camera': [], 'fullscreen': ['self'], 'geolocation': '*'}) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/').header_is('Permissions-Policy', 'camera=(), fullscreen=(self), geolocation=*') + +with subtest('referrer_policy'): + app = application() + app.plugin('SecurityHeaders', referrer_policy='no-referrer') + Pyjo.Test.Pyjo.new(app).get_ok('/').header_is('Referrer-Policy', 'no-referrer') + +with subtest('resource_policy'): + app = application() + app.plugin('SecurityHeaders', resource_policy='same-site') + Pyjo.Test.Pyjo.new(app).get_ok('/').header_is('Cross-Origin-Resource-Policy', 'same-site') + +with subtest('security_headers'): + app = application() + app.plugin('SecurityHeaders') + app.routes.get('/embed').to(cb=embed, security_headers={'csp': {'frame-ancestors': ['https:']}}) + app.routes.get('/stash', lambda c: c.stash(security_headers={'permissions': None}).render(text='Stash!')) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/embed').header_is('Content-Security-Policy', 'frame-ancestors https:') + t.get_ok('/stash').status_is(200).header_exists_not('Permissions-Policy').header_is( + 'Referrer-Policy', 'strict-origin-when-cross-origin' + ) + +with subtest('register'): + app = application() + plugin = app.plugins.load_plugin('SecurityHeaders') + plugin.register(app) + Pyjo.Test.Pyjo.new(app).get_ok('/', HTTPS).header_is('Strict-Transport-Security', 'max-age=31536000') + app = application() + plugin.register(app, {'hsts': {'max_age': 300}}) + Pyjo.Test.Pyjo.new(app).get_ok('/', HTTPS).header_is('Strict-Transport-Security', 'max-age=300') + +done_testing()