diff --git a/Pyjoyment/Plugin/CORS.py b/Pyjoyment/Plugin/CORS.py new file mode 100644 index 00000000..b38d142b --- /dev/null +++ b/Pyjoyment/Plugin/CORS.py @@ -0,0 +1,258 @@ +""" +Pyjoyment.Plugin.CORS - Cross-Origin Resource Sharing plugin +============================================================ +:: + + # Pyjoyment + app.plugin('CORS') + + # Pyjoyment.Lite + plugin('CORS') + + # The pages of two sites, with their cookies, for the API only + app.plugin( + 'CORS', + origins=['https://app.example.com', 'https://admin.example.com'], + credentials=True, + paths=['/api'], + max_age=600, + ) + +:mod:`Pyjoyment.Plugin.CORS` lets the pages of other sites read the +responses of the application, with the protocol of +`CORS `_ of Fetch. It +answers a preflight request, an ``OPTIONS`` request with +``Access-Control-Request-Method`` that a browser sends before a request that +a page of another site could not send without CORS, with +``204 No Content`` before the routes, and adds +``Access-Control-Allow-Origin`` to the responses, of the actions and the +static files alike, for a request with an ``Origin`` header of one of its +origins. A response that has ``Access-Control-Allow-Origin`` already, as one +that an action sets, is kept. + +A request of an origin that is not one of the origins gets no headers of +CORS, so that the browser does not give the response to the page, and its +preflight request is answered without them too, so that it reaches no +action. CORS protects what a page of another site may read, not what it may +request: a form of another site can still post to the application, which +the CSRF protection of the forms is for. + +With :mod:`Pyjoyment.Plugin.AllowedHosts`, which rejects a request of an +origin that is not one of its own with ``403 Forbidden``, the origins of +CORS are among its origins too. + +See :mod:`Pyjoyment.Plugins` for a list of plugins that are available by +default. + +Options +------- + +:mod:`Pyjoyment.Plugin.CORS` supports the following options. + +``credentials`` :: + + app.plugin('CORS', origins=['https://app.example.com'], credentials=True) + + Let the pages send their cookies and the authentication of HTTP with the + requests, with ``Access-Control-Allow-Credentials: true``, defaults to + ``False``. It needs the origins of their own, as a browser does not take + ``*`` with credentials, and a page of any site that the user visits + would read the responses for the user otherwise. + +``expose`` :: + + app.plugin('CORS', expose=['Server-Timing', 'X-Request-Id']) + + The headers of the responses, other than the ones that every page may + read, as ``Content-Type``, that a page may read, with + ``Access-Control-Expose-Headers``, defaults to none. + +``headers`` :: + + app.plugin('CORS', headers=['Authorization', 'Content-Type']) + + The headers that the requests of the pages may have, with + ``Access-Control-Allow-Headers``, defaults to ``None``, the ones that a + preflight request asks for in ``Access-Control-Request-Headers``. + +``max_age`` :: + + app.plugin('CORS', max_age=600) + + How long a browser keeps the answer of a preflight request, in seconds, + with ``Access-Control-Max-Age``, defaults to ``None``, for which a + browser keeps it for 5 seconds. Chromium keeps it for 2 hours at most. + +``methods`` :: + + app.plugin('CORS', methods=['GET', 'POST']) + + The methods that the requests of the pages may have, with + ``Access-Control-Allow-Methods``, defaults to ``GET``, ``HEAD``, + ``POST``, ``PUT``, ``PATCH`` and ``DELETE``. + +``origins`` :: + + app.plugin('CORS', origins=['https://app.example.com', 'http://localhost:5173']) + app.plugin('CORS', origins=[re.compile(r'^https://pr-\\d+\\.example\\.com$')]) + app.plugin('CORS', origins=lambda c, origin: origin.endswith('.example.com')) + + The origins of the pages that may read the responses, defaults to + ``*``, every origin, without credentials. An origin is a scheme, a host + and a port, as ``Origin`` has it, compared without its case, a regular + expression searches it, and a function takes the controller and the + origin, and returns true for an origin that may. + +``paths`` :: + + app.plugin('CORS', paths=['/api', re.compile(r'^/v\\d+/')]) + + The paths of the requests that CORS is for, defaults to ``None``, every + path. A path is the one of a request and its subpaths, as ``/api`` of + ``/api`` and ``/api/users``, and a regular expression searches the path + of a request. + +See also +-------- + +:mod:`Pyjoyment`, https://mojolicious.org. + +It has no counterpart in Mojolicious. + +Classes +------- +""" + +import Pyjo.Exception +import Pyjoyment.Plugin + +import re + +from collections.abc import Callable, Iterable +from typing import TYPE_CHECKING, Any + + +if TYPE_CHECKING: + import Pyjoyment + import Pyjoyment.Controller + +type _Origins = str | Iterable[str | re.Pattern[str]] | Callable[['Pyjoyment.Controller.object', str], bool] +type _Paths = Iterable[str | re.Pattern[str]] | None + +_METHODS = ('GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE') +_OPTIONS = {'credentials', 'expose', 'headers', 'max_age', 'methods', 'origins', 'paths'} + + +class Pyjoyment_Plugin_CORS(Pyjoyment.Plugin.object): + """ + :mod:`Pyjoyment.Plugin.CORS` 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(), {'origins': ['https://app.example.com']}) + + Register the hooks in :mod:`Pyjoyment` application. + """ + conf = conf or {} + if unknown := sorted(set(conf) - _OPTIONS): + raise Pyjo.Exception.new(f'Unknown option of CORS: {unknown[0]}') + origins: _Origins = conf.get('origins', '*') + credentials = bool(conf.get('credentials')) + if credentials and origins == '*': + raise Pyjo.Exception.new('Option credentials of CORS needs origins of its own') + if not isinstance(origins, str) and not callable(origins): + origins = list(origins) + paths: _Paths = conf.get('paths') + if paths is not None: + paths = list(paths) + methods = ', '.join(conf.get('methods') or _METHODS) + headers: list[str] | None = conf.get('headers') + expose = ', '.join(conf.get('expose') or []) + max_age: int | None = conf.get('max_age') + + def allowed(c: 'Pyjoyment.Controller.object') -> str | None: + # The value of Access-Control-Allow-Origin of the request, or None for one of another origin + if paths is not None and not _path(c.req.url.path.to_str(), paths): + return None + if (origin := c.req.headers.origin) is None: + return None + if origins == '*': + return '*' + return origin if _origin(c, origins, origin) else None + + def before_dispatch(c: 'Pyjoyment.Controller.object') -> None: + # A preflight request, which a route would not know, answered before the routes + req = c.req + if req.method != 'OPTIONS' or req.headers.access_control_request_method is None: + return + if paths is not None and not _path(req.url.path.to_str(), paths): + return + res_headers = c.res.headers + if (origin := allowed(c)) is not None: + res_headers.access_control_allow_origin = origin + res_headers.access_control_allow_methods = methods + if requested := req.headers.access_control_request_headers if headers is None else ', '.join(headers): + res_headers.access_control_allow_headers = requested + if credentials: + res_headers.access_control_allow_credentials = 'true' + if max_age is not None: + res_headers.access_control_max_age = max_age + if origins != '*': + res_headers.append('Vary', 'Origin') + if headers is None: + res_headers.append('Vary', 'Access-Control-Request-Headers') + c.stash()['cors.preflight'] = True + c.rendered(204) + + def after_dispatch(c: 'Pyjoyment.Controller.object') -> None: + res_headers = c.res.headers + if 'cors.preflight' in c.stash() or res_headers.access_control_allow_origin is not None: + return + if paths is not None and not _path(c.req.url.path.to_str(), paths): + return + # A cache keeps the responses of the origins apart + if origins != '*': + res_headers.append('Vary', 'Origin') + if (origin := allowed(c)) is None: + return + res_headers.access_control_allow_origin = origin + if credentials: + res_headers.access_control_allow_credentials = 'true' + if expose: + res_headers.access_control_expose_headers = expose + + app.hook('before_dispatch', before_dispatch) + app.hook('after_dispatch', after_dispatch) + + +def _origin(c: 'Pyjoyment.Controller.object', origins: _Origins, origin: str) -> bool: + if callable(origins): + return origins(c, origin) + for allowed in origins: + if isinstance(allowed, re.Pattern): + if allowed.search(origin): + return True + elif allowed.lower() == origin.lower(): + return True + return False + + +def _path(path: str, paths: Iterable[str | re.Pattern[str]]) -> bool: + for allowed in paths: + if isinstance(allowed, re.Pattern): + if allowed.search(path): + return True + continue + prefix = allowed.rstrip('/') + if path == prefix or path.startswith(f'{prefix}/'): + return True + return False + + +new = Pyjoyment_Plugin_CORS.new +object = Pyjoyment_Plugin_CORS +CORS = Pyjoyment_Plugin_CORS diff --git a/Pyjoyment/Plugins.py b/Pyjoyment/Plugins.py index 9712ba4e..a2811375 100644 --- a/Pyjoyment/Plugins.py +++ b/Pyjoyment/Plugins.py @@ -29,6 +29,9 @@ :mod:`Pyjoyment.Plugin.AllowedHosts` Validation of ``Host`` and ``Origin`` against DNS rebinding. +:mod:`Pyjoyment.Plugin.CORS` + Cross-Origin Resource Sharing, for the pages of other sites. + :mod:`Pyjoyment.Plugin.Config` Python-ish configuration files. diff --git a/docs/api/Pyjoyment_Plugin_CORS.rst b/docs/api/Pyjoyment_Plugin_CORS.rst new file mode 100644 index 00000000..cd494135 --- /dev/null +++ b/docs/api/Pyjoyment_Plugin_CORS.rst @@ -0,0 +1,2 @@ +.. automodule:: Pyjoyment.Plugin.CORS + :members: diff --git a/docs/guides/index.rst b/docs/guides/index.rst index 58944c15..a06f0178 100644 --- a/docs/guides/index.rst +++ b/docs/guides/index.rst @@ -377,6 +377,7 @@ This is the class hierarchy of the :mod:`Pyjoyment` distribution. - :mod:`Pyjoyment.Plugin.AccessLog` - :mod:`Pyjoyment.Plugin.AllowedHosts` + - :mod:`Pyjoyment.Plugin.CORS` - :mod:`Pyjoyment.Plugin.DefaultHelpers` - :mod:`Pyjoyment.Plugin.EPLRenderer` diff --git a/pyproject.toml b/pyproject.toml index b3b5e0cb..9660f32a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -395,6 +395,7 @@ strict = [ "Pyjoyment/Plugin/__init__.py", "Pyjoyment/Plugin/AccessLog.py", "Pyjoyment/Plugin/AllowedHosts.py", + "Pyjoyment/Plugin/CORS.py", "Pyjoyment/Plugin/Config.py", "Pyjoyment/Plugin/DefaultHelpers.py", "Pyjoyment/Plugin/EPLRenderer.py", diff --git a/t/Pyjoyment/cors_lite_app.py b/t/Pyjoyment/cors_lite_app.py new file mode 100644 index 00000000..0d83aff4 --- /dev/null +++ b/t/Pyjoyment/cors_lite_app.py @@ -0,0 +1,181 @@ +import os + + +os.environ['PYJO_MODE'] = 'development' + +import Pyjo.Test.Pyjo +import Pyjoyment + +from Pyjo.File import tempdir +from Pyjo.Test import * +from Pyjoyment.Lite import any, app, get, plugin + +import re + + +# Not in Mojolicious: Pyjoyment.Plugin.CORS, the Cross-Origin Resource Sharing of the pages of other sites + +app.log.level = 'fatal' + +plugin('CORS') + +get('/', {'text': 'Hello!'}) + +actions = [] + + +@any('/any') +def any_method(c): + actions.append(c.req.method) + c.render(text='Any!') + + +@get('/own') +def own(c): + c.res.headers.access_control_allow_origin = 'https://own.example.com' + c.render(text='Own!') + + +public = tempdir() +public.child('font.woff2').spew('woff2') +app.static.paths.insert(0, public.to_str()) + +t = Pyjo.Test.Pyjo.new() + +PAGE = {'Origin': 'https://app.example.com'} +PREFLIGHT = { + 'Origin': 'https://app.example.com', + 'Access-Control-Request-Method': 'PUT', + 'Access-Control-Request-Headers': 'content-type, x-token', +} + + +def application(conf): + # An application of its own, with the options of the plugin + other = Pyjoyment.new() + other.log.level = 'fatal' + other.plugin('CORS', conf) + other.routes.get('/', lambda c: c.render(text='Hello!')) + other.routes.get('/api/users', lambda c: c.render(json=[])) + other.routes.any('/api/any', lambda c: c.render(text='Any!')) + return Pyjo.Test.Pyjo.new(other) + + +with subtest('Every origin'): + ( + t.get_ok('/', PAGE) + .status_is(200) + .content_is('Hello!') + .header_is('Access-Control-Allow-Origin', '*') + .header_exists_not('Access-Control-Allow-Credentials') + .header_exists_not('Vary') + ) + t.get_ok('/font.woff2', PAGE).status_is(200).header_is('Access-Control-Allow-Origin', '*') + t.get_ok('/missing', PAGE).status_is(404).header_is('Access-Control-Allow-Origin', '*') + t.get_ok('/').status_is(200).header_exists_not('Access-Control-Allow-Origin') + t.get_ok('/own', PAGE).status_is(200).header_is('Access-Control-Allow-Origin', 'https://own.example.com') + +with subtest('Preflight'): + ( + t.options_ok('/any', PREFLIGHT) + .status_is(204) + .content_is('') + .header_is('Access-Control-Allow-Origin', '*') + .header_is('Access-Control-Allow-Methods', 'GET, HEAD, POST, PUT, PATCH, DELETE') + .header_is('Access-Control-Allow-Headers', 'content-type, x-token') + .header_is('Vary', 'Access-Control-Request-Headers') + .header_exists_not('Access-Control-Max-Age') + ) + is_deeply_ok(actions, [], 'no action for a preflight request') + t.options_ok('/missing', PREFLIGHT).status_is(204).header_is('Access-Control-Allow-Origin', '*') + + # An OPTIONS request that is not a preflight one reaches the routes + t.options_ok('/any', PAGE).status_is(200).content_is('Any!').header_is('Access-Control-Allow-Origin', '*') + t.options_ok('/any').status_is(200).content_is('Any!') + is_deeply_ok(actions, ['OPTIONS', 'OPTIONS'], 'actions of the other requests') + +with subtest('Origins of their own'): + other = application( + { + 'origins': ['https://APP.example.com', re.compile(r'^https://pr-\d+\.example\.com$')], + 'credentials': True, + 'headers': ['Content-Type'], + 'methods': ['GET', 'PUT'], + 'expose': ['Server-Timing', 'X-Request-Id'], + 'max_age': 600, + } + ) + ( + other.get_ok('/', PAGE) + .status_is(200) + .header_is('Access-Control-Allow-Origin', 'https://app.example.com') + .header_is('Access-Control-Allow-Credentials', 'true') + .header_is('Access-Control-Expose-Headers', 'Server-Timing, X-Request-Id') + .header_is('Vary', 'Origin') + ) + other.get_ok('/', {'Origin': 'https://pr-12.example.com'}).header_is( + 'Access-Control-Allow-Origin', 'https://pr-12.example.com' + ) + ( + other.get_ok('/', {'Origin': 'https://evil.com'}) + .status_is(200) + .content_is('Hello!') + .header_exists_not('Access-Control-Allow-Origin') + .header_exists_not('Access-Control-Allow-Credentials') + .header_is('Vary', 'Origin') + ) + other.get_ok('/').status_is(200).header_exists_not('Access-Control-Allow-Origin').header_is('Vary', 'Origin') + ( + other.options_ok('/api/any', PREFLIGHT) + .status_is(204) + .header_is('Access-Control-Allow-Origin', 'https://app.example.com') + .header_is('Access-Control-Allow-Methods', 'GET, PUT') + .header_is('Access-Control-Allow-Headers', 'Content-Type') + .header_is('Access-Control-Allow-Credentials', 'true') + .header_is('Access-Control-Max-Age', '600') + .header_is('Vary', 'Origin') + .header_exists_not('Access-Control-Expose-Headers') + ) + # The preflight request of another origin gets no headers of CORS, and reaches no action + ( + other.options_ok('/api/any', {**PREFLIGHT, 'Origin': 'https://evil.com'}) + .status_is(204) + .header_exists_not('Access-Control-Allow-Origin') + .header_exists_not('Access-Control-Allow-Methods') + .header_is('Vary', 'Origin') + ) + + other = application({'origins': lambda c, origin: origin.endswith('.example.com')}) + other.get_ok('/', PAGE).header_is('Access-Control-Allow-Origin', 'https://app.example.com') + other.get_ok('/', {'Origin': 'https://evil.com'}).header_exists_not('Access-Control-Allow-Origin') + +with subtest('Paths'): + other = application({'paths': ['/api/', re.compile(r'^/v\d+/')]}) + other.get_ok('/api/users', PAGE).status_is(200).header_is('Access-Control-Allow-Origin', '*') + other.get_ok('/', PAGE).status_is(200).header_exists_not('Access-Control-Allow-Origin') + other.options_ok('/api/any', PREFLIGHT).status_is(204).header_is('Access-Control-Allow-Origin', '*') + other.options_ok('/', PREFLIGHT).status_is(404).header_exists_not('Access-Control-Allow-Origin') + other.options_ok('/v2/x', PREFLIGHT).status_is(204) + other.options_ok('/apix', PREFLIGHT).status_is(404) + +with subtest('AllowedHosts'): + # The origins of CORS among the origins of AllowedHosts, which rejects the other ones before + other = Pyjoyment.new() + other.log.level = 'fatal' + other.plugin('AllowedHosts', origins=['https://app.example.com']) + other.plugin('CORS', origins=['https://app.example.com']) + other.routes.get('/', lambda c: c.render(text='Hello!')) + other = Pyjo.Test.Pyjo.new(other) + other.get_ok('/', PAGE).status_is(200).header_is('Access-Control-Allow-Origin', 'https://app.example.com') + other.options_ok('/', PREFLIGHT).status_is(204).header_is('Access-Control-Allow-Origin', 'https://app.example.com') + other.get_ok('/', {'Origin': 'https://evil.com'}).status_is(403).header_exists_not('Access-Control-Allow-Origin') + +with subtest('Errors of the options'): + throws_ok( + lambda: Pyjoyment.new().plugin('CORS', credentials=True), + Exception, + 'Option credentials of CORS needs origins of its own', + ) + throws_ok(lambda: Pyjoyment.new().plugin('CORS', origin=['x']), Exception, 'Unknown option of CORS: origin') + +done_testing() diff --git a/t/docs/Pyjoyment_Plugin_CORS.py b/t/docs/Pyjoyment_Plugin_CORS.py new file mode 100644 index 00000000..1b8ac417 --- /dev/null +++ b/t/docs/Pyjoyment_Plugin_CORS.py @@ -0,0 +1,117 @@ +import Pyjo.Test.Pyjo +import Pyjoyment + +from Pyjo.Test import * +from Pyjoyment.Lite import app as lite +from Pyjoyment.Lite import get, plugin + +import re + + +lite.log.level = 'fatal' + +PAGE = {'Origin': 'https://app.example.com'} + + +def application(): + app = Pyjoyment.new() + app.log.level = 'fatal' + app.routes.get('/', lambda c: c.render(text='Hello!')) + app.routes.get('/api/users', lambda c: c.render(json=[])) + return app + + +with subtest('Synopsis'): + # Pyjoyment + app = application() + app.plugin('CORS') + Pyjo.Test.Pyjo.new(app).get_ok('/', PAGE).status_is(200).header_is('Access-Control-Allow-Origin', '*') + + # Pyjoyment.Lite + plugin('CORS') + get('/', {'text': 'Hello!'}) + Pyjo.Test.Pyjo.new().get_ok('/', PAGE).status_is(200).header_is('Access-Control-Allow-Origin', '*') + + # The pages of two sites, with their cookies, for the API only + app = application() + app.plugin( + 'CORS', + origins=['https://app.example.com', 'https://admin.example.com'], + credentials=True, + paths=['/api'], + max_age=600, + ) + t = Pyjo.Test.Pyjo.new(app) + ( + t.get_ok('/api/users', {'Origin': 'https://admin.example.com'}) + .header_is('Access-Control-Allow-Origin', 'https://admin.example.com') + .header_is('Access-Control-Allow-Credentials', 'true') + ) + t.get_ok('/', PAGE).header_exists_not('Access-Control-Allow-Origin') + preflight = {**PAGE, 'Access-Control-Request-Method': 'DELETE'} + t.options_ok('/api/users', preflight).status_is(204).header_is('Access-Control-Max-Age', '600') + +with subtest('credentials'): + app = application() + app.plugin('CORS', origins=['https://app.example.com'], credentials=True) + Pyjo.Test.Pyjo.new(app).get_ok('/', PAGE).header_is('Access-Control-Allow-Credentials', 'true') + +with subtest('expose'): + app = application() + app.plugin('CORS', expose=['Server-Timing', 'X-Request-Id']) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/', PAGE).header_is('Access-Control-Expose-Headers', 'Server-Timing, X-Request-Id') + +with subtest('headers'): + app = application() + app.plugin('CORS', headers=['Authorization', 'Content-Type']) + preflight = {**PAGE, 'Access-Control-Request-Method': 'PUT', 'Access-Control-Request-Headers': 'x-other'} + t = Pyjo.Test.Pyjo.new(app) + t.options_ok('/', preflight).header_is('Access-Control-Allow-Headers', 'Authorization, Content-Type') + +with subtest('max_age'): + app = application() + app.plugin('CORS', max_age=600) + preflight = {**PAGE, 'Access-Control-Request-Method': 'PUT'} + Pyjo.Test.Pyjo.new(app).options_ok('/', preflight).header_is('Access-Control-Max-Age', '600') + +with subtest('methods'): + app = application() + app.plugin('CORS', methods=['GET', 'POST']) + preflight = {**PAGE, 'Access-Control-Request-Method': 'PUT'} + Pyjo.Test.Pyjo.new(app).options_ok('/', preflight).header_is('Access-Control-Allow-Methods', 'GET, POST') + +with subtest('origins'): + app = application() + app.plugin('CORS', origins=['https://app.example.com', 'http://localhost:5173']) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/', {'Origin': 'http://localhost:5173'}).header_is('Access-Control-Allow-Origin', 'http://localhost:5173') + t.get_ok('/', {'Origin': 'http://localhost:3000'}).header_exists_not('Access-Control-Allow-Origin') + app = application() + app.plugin('CORS', origins=[re.compile(r'^https://pr-\d+\.example\.com$')]) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/', {'Origin': 'https://pr-1.example.com'}).header_is( + 'Access-Control-Allow-Origin', 'https://pr-1.example.com' + ) + app = application() + app.plugin('CORS', origins=lambda c, origin: origin.endswith('.example.com')) + Pyjo.Test.Pyjo.new(app).get_ok('/', PAGE).header_is('Access-Control-Allow-Origin', 'https://app.example.com') + +with subtest('paths'): + app = application() + app.plugin('CORS', paths=['/api', re.compile(r'^/v\d+/')]) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/api/users', PAGE).header_is('Access-Control-Allow-Origin', '*') + t.get_ok('/', PAGE).header_exists_not('Access-Control-Allow-Origin') + +with subtest('register'): + app = application() + plugin = app.plugins.load_plugin('CORS') + plugin.register(app) + Pyjo.Test.Pyjo.new(app).get_ok('/', PAGE).header_is('Access-Control-Allow-Origin', '*') + app = application() + plugin.register(app, {'origins': ['https://app.example.com']}) + t = Pyjo.Test.Pyjo.new(app) + t.get_ok('/', PAGE).header_is('Access-Control-Allow-Origin', 'https://app.example.com') + +done_testing()