diff --git a/plugins/pyjoyment/skills/api/SKILL.md b/plugins/pyjoyment/skills/api/SKILL.md index 0fcad0dc..ad77ad21 100644 --- a/plugins/pyjoyment/skills/api/SKILL.md +++ b/plugins/pyjoyment/skills/api/SKILL.md @@ -22,6 +22,10 @@ from Pyjoyment.Lite import * from typing import NotRequired, TypedDict +# CORS, for the pages of every other site, with the answers of the preflight requests of PUT, PATCH and DELETE +plugin('CORS') + + class Item(TypedDict): name: str price: float @@ -79,12 +83,6 @@ def remove(c): c.rendered(204) -# CORS, for each response -@hook('after_dispatch') -def cors(c): - c.res.headers.header('Access-Control-Allow-Origin', '*') - - app.start() ``` @@ -98,6 +96,10 @@ app.start() object reports it as `/: Expected object - got null.`. - `c.rendered(204)` ends a response without a body; `c.reply.json_not_found()` renders 404 as JSON. +- `plugin('CORS', origins=['https://app.example.com'], credentials=True, paths=['/api'])` + lets the pages of a frontend read the API with the cookies of its user; the + origins are also those of `plugin('AllowedHosts', origins=...)`, which + rejects the other ones. ## JSON-RPC @@ -148,9 +150,15 @@ app.start() `text`, `status` or `format`, which `render` and the router reserve. - `json.dumps` of Python with `c.render(data=...)` or `text=` skips the `Content-Type` of JSON, which `c.render(json=...)` sets. +- `Access-Control-Allow-Origin` set by hand misses the preflight requests, + which a browser sends before a `PUT` or a request of JSON, and `Vary: Origin`; + `credentials=True` needs origins of their own, as browsers refuse `*` with + cookies, and reflecting any `Origin` would let every site read the data of the + user. ## Documentation - Pyjo.JSON.Schema: https://pyjoyment.readthedocs.io/en/stable/api/Pyjo_JSON_Schema.html - Pyjo.JSON.RPC: https://pyjoyment.readthedocs.io/en/stable/api/Pyjo_JSON_RPC.html - Rendering JSON: https://pyjoyment.readthedocs.io/en/stable/guides/rendering.html +- Pyjoyment.Plugin.CORS: https://pyjoyment.readthedocs.io/en/stable/api/Pyjoyment_Plugin_CORS.html diff --git a/plugins/pyjoyment/skills/deploy/SKILL.md b/plugins/pyjoyment/skills/deploy/SKILL.md index f0b626c3..47434178 100644 --- a/plugins/pyjoyment/skills/deploy/SKILL.md +++ b/plugins/pyjoyment/skills/deploy/SKILL.md @@ -1,6 +1,6 @@ --- name: deploy -description: Run and deploy a Pyjoyment application. Use for its servers (daemon, prefork, prethread, the zero downtime of pyjo-hot, pyjo-reload in development), their options and PYJO_* variables, the options of gunicorn translated into prefork, reverse proxies and TLS, graceful stops, the Health plugin for probes and the AccessLog plugin for the access log of the requests, the Cache-Control and the precompressed gzip, brotli and zstd variants of the static files, and the generators of a pyproject.toml, a Dockerfile, the manifests of Kubernetes and the ZIP files of AWS Lambda, and WSGI, ASGI and FastCGI servers in front of it. +description: Run and deploy a Pyjoyment application. Use for its servers (daemon, prefork, prethread, the zero downtime of pyjo-hot, pyjo-reload in development), their options and PYJO_* variables, the options of gunicorn translated into prefork, reverse proxies and TLS, the security headers of HSTS, CSP with its reports and nonce, and Permissions-Policy, graceful stops, the Health plugin for probes and the AccessLog plugin for the access log of the requests, the Cache-Control and the precompressed gzip, brotli and zstd variants of the static files, and the generators of a pyproject.toml, a Dockerfile, the manifests of Kubernetes and the ZIP files of AWS Lambda, and WSGI, ASGI and FastCGI servers in front of it. --- # Deployment @@ -29,6 +29,9 @@ app.secrets = [os.environ.get('APP_SECRET', 'Change this secret')] ready = {'db': True} plugin('Health', checks={'db': lambda c: ready['db']}) +# HSTS, a CSP that the browsers report the violations of before it is enforced, Permissions-Policy and the others +plugin('SecurityHeaders', csp_report_only={'default-src': ["'self'"]}, reports='/csp-reports') + @get('/') def index(c): @@ -138,6 +141,37 @@ Apache and nginx, which a container, Kubernetes and log analyzers take: response, `101` the handshake of a WebSocket, and the size of a chunked response is the one of its body as the server wrote it. +## Security headers + +`plugin('SecurityHeaders')` adds to every response, of the routes, the static +files and the pages of errors, the headers that a review checks first: +`Strict-Transport-Security`, `Content-Security-Policy`, `Permissions-Policy`, +`X-Content-Type-Options: nosniff`, `Referrer-Policy` and +`Cross-Origin-Opener-Policy`. A header that an action sets is kept, and +`security_headers={...}` in the defaults of a route replaces the options for +its responses. + +- HSTS, `max-age=31536000` by default, goes only with the responses of HTTPS, + of a reverse proxy too with `-p`, never for `localhost`. A site that starts + with it starts with `hsts={'max_age': 300}`, as browsers keep it and it + cannot be taken back, and adds `include_subdomains` and `preload` once every + subdomain has HTTPS. +- The default CSP, `base-uri 'self'; frame-ancestors 'self'; object-src + 'none'`, restricts no script or style. A policy of the pages goes into + `csp_report_only` with `reports='/csp-reports'`, a route that logs the + violations and emits the hook `csp_report`, and into `csp` once the reports + are clean. +- An inline script or style needs the nonce of the response, which the tag + helpers `javascript` and `stylesheet` and `csp_nonce()` give, and a response + with a nonce gets `Cache-Control: private`: a page that a CDN keeps loads its + scripts and styles from files, allowed by the sources of the policy, as + `'self'`, not by a nonce, which the CDN would give to every client. +- `Permissions-Policy` turns off the camera, the geolocation and the microphone + by default: `permissions={'geolocation': ['self']}` allows a feature to the + pages. +- CORS, for the pages of other sites that read the application, is + `plugin('CORS')`, of the skill `api`. + ## Containers, Kubernetes and AWS Lambda ```sh @@ -257,6 +291,13 @@ PYJO_LISTEN='fcgi://127.0.0.1:9000' python app.py daemon # FastCGI behind ngi application with its own: `healthz=None` leaves it to the application. - A blocking request handler under `daemon` blocks every connection: more workers of `prefork`, `-c 1`, or code that does not block. +- No `Strict-Transport-Security` behind a reverse proxy without `-p` + (`PYJO_REVERSE_PROXY=1`): the application takes the request for one of HTTP, + as `X-Forwarded-Proto` is ignored without it. +- A CSP in `csp` before its reports are read blocks the scripts of the pages + in production; `'unsafe-inline'` next to a nonce is ignored by browsers, and + a `style` or `onclick` attribute is blocked by a policy of the styles or the + scripts with a nonce. - The log goes to the standard error, which a container, Kubernetes and AWS Lambda collect as it is written; `PYJO_LOG_FORMAT=json` makes each line JSON for a collector of logs, and `PYJO_LOG_LEVEL` its level. `print` goes @@ -270,3 +311,5 @@ PYJO_LISTEN='fcgi://127.0.0.1:9000' python app.py daemon # FastCGI behind ngi - From gunicorn: https://pyjoyment.readthedocs.io/en/stable/guides/gunicorn.html - generate dockerfile: https://pyjoyment.readthedocs.io/en/stable/api/Pyjoyment_Command_Author_generate_dockerfile.html - Rendering, precompressed static files: https://pyjoyment.readthedocs.io/en/stable/guides/rendering.html#precompressed-static-files +- Cookbook, security headers: https://pyjoyment.readthedocs.io/en/stable/guides/cookbook.html#security-headers +- Pyjoyment.Plugin.SecurityHeaders: https://pyjoyment.readthedocs.io/en/stable/api/Pyjoyment_Plugin_SecurityHeaders.html diff --git a/plugins/pyjoyment/skills/templates/SKILL.md b/plugins/pyjoyment/skills/templates/SKILL.md index 944ace2a..7576a1ee 100644 --- a/plugins/pyjoyment/skills/templates/SKILL.md +++ b/plugins/pyjoyment/skills/templates/SKILL.md @@ -1,6 +1,6 @@ --- name: templates -description: Write the templates of a Pyjoyment application. Use for ep templates of Embedded Python (tags, lines, blocks with end, escaping, the values of the stash as variables), layouts, partial templates, content blocks, helpers and tag helpers in templates, forms with CSRF protection and validation, templates of __DATA__ and templates/, and the template strings of PyRenderer. +description: Write the templates of a Pyjoyment application. Use for ep templates of Embedded Python (tags, lines, blocks with end, escaping, the values of the stash as variables), layouts, partial templates, content blocks, helpers and tag helpers in templates, forms with CSRF protection and validation, the nonce of a Content-Security-Policy for inline scripts and styles, templates of __DATA__ and templates/, and the template strings of PyRenderer. --- # Templates @@ -132,6 +132,12 @@ app.start() HTML that renders values from outside without the renderer `ep` takes `Pyjo.Template.new(auto_escape=True)`, or it is a hole for cross-site scripting. +- An inline script or style goes through `%= javascript(begin` or + `%= stylesheet(begin` ... `%= end)`, which give it the nonce of the + Content-Security-Policy of `plugin('SecurityHeaders')`, or has + `nonce="<%= csp_nonce() %>"`; a policy with a nonce blocks the attributes + `style` and `onclick`, so their styles and handlers go into the stylesheet + and the script. ## Template strings @@ -185,3 +191,4 @@ app.start() - Tag helpers: https://pyjoyment.readthedocs.io/en/stable/api/Pyjoyment_Plugin_TagHelpers.html - Default helpers: https://pyjoyment.readthedocs.io/en/stable/api/Pyjoyment_Plugin_DefaultHelpers.html - PyRenderer: https://pyjoyment.readthedocs.io/en/stable/api/Pyjoyment_Plugin_PyRenderer.html +- Pyjoyment.Plugin.SecurityHeaders: https://pyjoyment.readthedocs.io/en/stable/api/Pyjoyment_Plugin_SecurityHeaders.html diff --git a/t/docs/skills_api.py b/t/docs/skills_api.py index 57ba21a8..13b21363 100644 --- a/t/docs/skills_api.py +++ b/t/docs/skills_api.py @@ -32,7 +32,10 @@ def load(name): with subtest('REST'): t = load('rest.py') t.get_ok('/items').status_is(200).json_is([{'id': 1, 'name': 'Pen', 'price': 1.5}]) - t.header_is('Access-Control-Allow-Origin', '*') + page = {'Origin': 'https://app.example.com'} + t.get_ok('/items', page).status_is(200).header_is('Access-Control-Allow-Origin', '*') + preflight = {**page, 'Access-Control-Request-Method': 'DELETE'} + t.options_ok('/items/1', preflight).status_is(204).header_like('Access-Control-Allow-Methods', r'DELETE') t.post_ok('/items', json={'name': 'Book', 'price': 'cheap'}).status_is(422) t.json_is('/errors/0', '/price: Expected number - got string.') t.post_ok('/items', json={'name': 'Book', 'price': 9.9, 'tags': ['paper']}).status_is(201) diff --git a/t/docs/skills_deploy.py b/t/docs/skills_deploy.py index f620af15..4cc9899c 100644 --- a/t/docs/skills_deploy.py +++ b/t/docs/skills_deploy.py @@ -2,6 +2,7 @@ import Pyjo.IOLoop import Pyjo.Log import Pyjo.Test.Pyjo +import Pyjoyment.Plugin.SecurityHeaders from Pyjo.Test import * @@ -41,6 +42,28 @@ def run(*args): t.get_ok('/healthz').status_is(200) t.get_ok('/readyz').status_is(200).content_is('ok') +with subtest('Security headers'): + t = Pyjo.Test.Pyjo.new(app) + t.app.log.level = 'fatal' + ( + t.get_ok('/') + .status_is(200) + .header_is('X-Content-Type-Options', 'nosniff') + .header_like('Content-Security-Policy', r"^base-uri 'self'; frame-ancestors 'self'; object-src 'none'; ") + .header_is('Content-Security-Policy-Report-Only', "default-src 'self'; report-uri /csp-reports; report-to csp") + .header_is('Reporting-Endpoints', 'csp="/csp-reports"') + .header_is('Permissions-Policy', 'camera=(), geolocation=(), microphone=()') + .header_exists_not('Strict-Transport-Security') + ) + t.post_ok('/csp-reports', json={'csp-report': {'blocked-uri': 'inline'}}).status_is(204) + skill = Skills.read('deploy') + section = re.search(r'^## Security headers\n(.*?)^## ', skill, re.M | re.S)[1] + # The options that the section names are the ones of the plugin, and the value of the stash of a route + known = {*Pyjoyment.Plugin.SecurityHeaders._HEADERS, 'max_report_size', 'reports', 'security_headers'} + for option in re.findall(r'`(\w+)=', section): + ok(option in known, f'option {option}') + t.get_ok('/livez').status_is(200).header_is('Referrer-Policy', 'strict-origin-when-cross-origin') + with subtest('Generators'): for generator in (['pyproject'], ['dockerfile', '-p', '8080'], ['kubernetes', '-i', 'myapp']): stdout, status = run('app.py', 'generate', *generator) diff --git a/t/docs/skills_templates.py b/t/docs/skills_templates.py index e94fe480..ce1659e0 100644 --- a/t/docs/skills_templates.py +++ b/t/docs/skills_templates.py @@ -1,10 +1,12 @@ import Pyjo.File import Pyjo.Test.Pyjo +import Pyjoyment from Pyjo.Test import * import importlib import os +import re import sys @@ -44,4 +46,22 @@ def load(n): t.get_ok('/hello/Joe').status_is(200).text_is('p', 'Hello Joe! ').text_is('p a[href="/"]', 'Home') t.get_ok('/hello/%3Cb%3E').status_is(200).content_is('
Hello <b>! Home
') +with subtest('Nonce'): + # The forms of the inline scripts and styles of the skill, with the Content-Security-Policy of SecurityHeaders + app = Pyjoyment.new() + app.log.level = 'fatal' + app.plugin('SecurityHeaders', csp={'script-src': ["'self'"], 'style-src': ["'self'"]}) + template = ( + '%= javascript(begin\n hello();\n%= end)\n' + '%= stylesheet(begin\n p {color: red}\n%= end)\n' + '\n' + ) + app.routes.get('/', lambda c: c.render(inline=template)) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/').status_is(200) + nonce = t.tx.res.dom().at('script').attr('nonce') + ok(nonce, 'nonce') + is_ok(len(t.tx.res.dom(f'script[nonce="{nonce}"], style[nonce="{nonce}"]')), 3, 'every inline script and style') + t.header_like('Content-Security-Policy', rf"script-src 'self' 'nonce-{re.escape(nonce)}'") + done_testing()