wsgicors-0.7.0/0000775000175000017500000000000013054644036014173 5ustar normannorman00000000000000wsgicors-0.7.0/MANIFEST.in0000664000175000017500000000005712550535140015726 0ustar normannorman00000000000000include *.rst include test*.py include LICENSE wsgicors-0.7.0/wsgicors.py0000664000175000017500000002133213054642025016402 0ustar normannorman00000000000000# -*- encoding: utf-8 -*- # # This file is part of wsgicors # # wsgicors is a WSGI middleware that answers CORS preflight requests # # copyright 2014-2015 Norman Krämer # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import fnmatch from functools import reduce from collections import namedtuple try: from functools import lru_cache except ImportError: from backports.functools_lru_cache import lru_cache class CORS(object): "WSGI middleware allowing CORS requests to succeed" @staticmethod def matchpattern(accu, pattern, host): return accu or fnmatch.fnmatch(host, pattern) @staticmethod def matchlist(origin, allowed_origins, case_sensitive=False): return reduce(lambda accu, x: CORS.matchpattern(accu, x, origin.lower() if not case_sensitive else origin), allowed_origins, False) def __init__(self, application, cfg=None, **kw): Policy = namedtuple("Policy", ["name", "origin", "methods", "headers", "expose_headers", "credentials", "maxage", "match"]) self.policies = {} if kw and "policy" not in kw: # direct config self.activepolicies = ["direct"] self.matchstrategy = "firstmatch" self.policies["direct"]=kw else: # multiple policies programatically or via configfile (paster factory for instance) cfg = kw or cfg or {} self.activepolicies = list(map(lambda x: x.strip(), cfg.get("policy", "deny").split(","))) self.matchstrategy = cfg.get("matchstrategy", "firstmatch") for policy in self.activepolicies: kw = {} prefix = policy + "_" for k, v in filter(lambda key_value: key_value[0].startswith(prefix), cfg.items()): kw[k.split(prefix)[-1]] = v self.policies[policy]=kw for policy in self.activepolicies: kw = self.policies[policy] # copy or * or a space separated list of hostnames, possibly with filename wildcards "*" and "?" pol_origin = kw.get("origin", "") if pol_origin not in ("copy", "*"): match = list(filter(lambda x: x != "*", map(lambda x: x.strip(), pol_origin.split(" ")))) else: match = [] pol_methods = kw.get("methods", "") methods = list(map(lambda x: x.strip(), pol_methods.split(","))) # copy or * or a space separated list of hostnames, possibly with filename wildcards "*" and "?" pol_headers = kw.get("headers", "") # * or list of headers pol_expose_headers = kw.get("expose_headers", "") # * or list of headers to expose to the client pol_credentials = kw.get("credentials", "false") # true or false pol_maxage = kw.get("maxage", "") # in seconds pol=Policy(name=policy, origin=pol_origin, methods=methods, headers=pol_headers, expose_headers=pol_expose_headers, credentials=pol_credentials, maxage=pol_maxage, match=match) self.policies[policy] = pol # a little sanity check configkeys="origin,methods,headers,expose_headers,credentials,maxage".split(",") existingkeys=[k for k in configkeys if k in kw] if "origin" not in kw: if existingkeys: print("The policy '%s' was referenced but has no value for 'origin' set. Nothing good can come from this." % policy) elif policy != "deny": print("The policy '%s' was referenced but hasn't defined any keys. This might be an case sensitivity issue." % policy) self.application = application @lru_cache(maxsize=200) def selectPolicy(self, origin, request_method=None): "Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned." ret_origin = None policyname = None if self.matchstrategy in ("firstmatch", "verbmatch"): for pol in self.activepolicies: policy=self.policies[pol] ret_origin = None policyname = policy.name if policyname == "deny": break if self.matchstrategy == "verbmatch": if policy.methods != "*" and not CORS.matchlist(request_method, policy.methods, case_sensitive=True): continue if origin and policy.match: if CORS.matchlist(origin, policy.match): ret_origin = origin elif policy.origin == "copy": ret_origin = origin elif policy.origin: ret_origin = policy.origin if ret_origin: break return policyname, ret_origin def __call__(self, environ, start_response): # we handle the request ourself only if it is identified as a prefilght request if 'OPTIONS' == environ['REQUEST_METHOD'] and environ.get("HTTP_ACCESS_CONTROL_REQUEST_METHOD") is not None \ and environ.get("HTTP_ORIGIN") is not None: resp = [] orig = environ.get("HTTP_ORIGIN") ac_request_method = environ.get("HTTP_ACCESS_CONTROL_REQUEST_METHOD") policyname, origin = self.selectPolicy(orig, ac_request_method) if policyname == "deny": pass else: policy = self.policies[policyname] methods = None headers = None credentials = None maxage = None if "*" in policy.methods: methods = environ.get("HTTP_ACCESS_CONTROL_REQUEST_METHOD", None) elif policy.methods: methods = ", ".join(policy.methods) if policy.headers == "*": headers = environ.get("HTTP_ACCESS_CONTROL_REQUEST_HEADERS", None) elif policy.headers: headers = policy.headers if policy.credentials == "true": credentials = "true" if policy.maxage: maxage = policy.maxage if origin: resp.append(('Access-Control-Allow-Origin', origin)) if methods: resp.append(('Access-Control-Allow-Methods', methods)) if headers: resp.append(('Access-Control-Allow-Headers', headers)) if credentials: resp.append(('Access-Control-Allow-Credentials', credentials)) if maxage: resp.append(('Access-Control-Max-Age', maxage)) status = '204 OK' start_response(status, resp) return [] orig = environ.get("HTTP_ORIGIN", None) request_method = environ['REQUEST_METHOD'] policyname, ret_origin = self.selectPolicy(orig, request_method) if orig and policyname != "deny": def custom_start_response(status, headers, exc_info=None): policyname, ret_origin = self.selectPolicy(orig, request_method) policy = self.policies[policyname] if policy.credentials == 'true' and policy.origin == "*": # for credentialed access '*' are ignored in origin ret_origin = orig if ret_origin: headers.append(('Access-Control-Allow-Origin', ret_origin)) if policy.credentials == 'true': headers.append(('Access-Control-Allow-Credentials', 'true')) if policy.expose_headers: headers.append(('Access-Control-Expose-Headers', policy.expose_headers)) if policy.origin != "*": headers.append(('Vary', 'Origin')) return start_response(status, headers, exc_info) else: custom_start_response = start_response return self.application(environ, custom_start_response) def make_middleware(app, cfg=None, **kw): cfg = (cfg or {}).copy() cfg.update(kw) app = CORS(app, cfg) return app wsgicors-0.7.0/PKG-INFO0000664000175000017500000001712313054644036015274 0ustar normannorman00000000000000Metadata-Version: 1.1 Name: wsgicors Version: 0.7.0 Summary: WSGI for Cross Origin Resource Sharing (CORS) Home-page: https://github.com/may-day/wsgicors Author: Norman Krämer Author-email: kraemer.norman@googlemail.com License: Apache Software License 2.0 Description: wsgicors |buildstatus| ======== .. |buildstatus| image:: https://travis-ci.org/may-day/wsgicors.svg?branch=master This is a WSGI middleware that answers CORS preflight requests and adds the needed header to the response. For CORS see: http://www.w3.org/TR/cors/ Usage ----- Either plug it in programmatically as in this pyramid example: .. code:: python def app(global_config, **settings): """ This function returns a WSGI application. It is usually called by the PasteDeploy framework during ``paster serve``. """ def get_root(request): return {} config = Configurator(root_factory=get_root, settings=settings) config.begin() # whatever it takes to config your app goes here config.end() from wsgicors import CORS return CORS(config.make_wsgi_app(), headers="*", methods="*", maxage="180", origin="*") or plug it into your wsgi pipeline via paste ini to let it serve by waitress for instance: :: [app:myapp] use = egg:mysuperapp#app ### # wsgi server configuration ### [server:main] use = egg:waitress#main host = 0.0.0.0 port = 6543 [pipeline:main] pipeline = cors myapp [filter:cors] use = egg:wsgicors#middleware # define a "free" policy free_origin=copy free_headers=* free_expose_headers=* free_methods=HEAD, OPTIONS, GET free_maxage=180 # define a "subdom" policy subdom_origin=http://example.com http://example2.com https://*.example.com subdom_headers=* subdom_methods=HEAD, OPTIONS, GET, POST, PUT, DELETE subdom_expose_headers=Foo, Doom subdom_maxage=180 # define a combination of policies, they are evaluated in the order given by the policy keyword # the first that matches the request's origin will be used policy=subdom,free # policy matching strategy # matchstrategy=firstmatch Keywords are: - ``origin`` - ``headers`` - ``methods`` - ``credentials`` - ``maxage`` for ``origin``: - use ``copy`` which will copy whatever origin the request comes from - a space separated list of hostnames - they can also contain wildcards like ``*`` or ``?`` (fnmatch lib is used for matching). If a match is found the original host is returned. - any other literal will be be copied verbatim (like ``*`` for instance to allow any source) for ``headers``: - use ``*`` which will allow whatever header is asked for - any other literal will be be copied verbatim for ``expose_headers``: - use ``*`` to allow access to any header the client might wish to access - any other literal will be be copied verbatim for ``methods``: - use ``*`` which will allow whatever method is asked for - any other literal will be be copied verbatim (like ``POST, PATCH, PUT, DELETE`` for instance) for ``credentials``: - use ``true`` - anything else will be ignored (that is no response header for ``Access-Control-Allow-Credentials`` is sent) for ``maxage``: - give the number of seconds the answer can be used by a client, anything nonempty will be copied verbatim As can be seen in the example above, a policy needs to be created with the ``policy`` keyword. The options need then be prefixed with the policy name and a ``_``. The ``policy`` keyword itself can be a comma separated list. If so the origin of the request is matched against the origins defined in the policies and the first matching is the policy used. An alternative matching strategy would be ``verbmatch``, that selects the first of the listed that also matches the request method. To switch between the strategies use the ``matchstrategy`` keyword: - use ``firstmatch`` (the default) to select the first of the policies that matches on the ``origin`` keyword - use ``verbmatch`` to select the first of the policies that matches on the ``methods`` and ``origin`` keyword Changes ======= Version 0.7.0 ------------- - ``verbmulti`` matching strategy, that matches the first listed policy that also matches the requested METHOD - relaxed dependency on lru_cache version Version 0.6.0 ------------- - support for multiple policies - caching of matching results Version 0.5.1 ------------- - check for request being preflight - reworked tests Version 0.5.0 ------------- - support for Access-Control-Expose-Headers - Header ``Vary`` is set to ``Origin`` if origin policy differs from ``*`` Version 0.4.1 ------------- - py3 utf-8 related setup fixes Version 0.4 ----------- - python3 compatibility Version 0.3 ----------- - ``origin`` now takes space separated list of hostnames. They can be filename patterns like \*.domain.tld Version 0.2 ----------- - Access-Control-Allow-Credentials is now returned in the actual reponse if specified by policy Credits ======= “wsgicors” is written and maintained by Norman Krämer. Contributors ------------ The following people contributed directly or indirectly to this project: - `Julien De Vos `_ - `Ryan Shaw `_ - `David Douard `_ - `MattSANU `_ - `Sami Salonen `_ - `Sami Salonen `_ - `Wouter Claeys `_ Please add yourself here when you submit your first pull request. Keywords: wsgi,cors Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Internet :: WWW/HTTP :: WSGI wsgicors-0.7.0/setup.cfg0000664000175000017500000000011313054644036016007 0ustar normannorman00000000000000[easy_install] [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 wsgicors-0.7.0/LICENSE0000664000175000017500000002613612503520414015177 0ustar normannorman00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. wsgicors-0.7.0/wsgicors.egg-info/0000775000175000017500000000000013054644036017525 5ustar normannorman00000000000000wsgicors-0.7.0/wsgicors.egg-info/PKG-INFO0000664000175000017500000001712313054644036020626 0ustar normannorman00000000000000Metadata-Version: 1.1 Name: wsgicors Version: 0.7.0 Summary: WSGI for Cross Origin Resource Sharing (CORS) Home-page: https://github.com/may-day/wsgicors Author: Norman Krämer Author-email: kraemer.norman@googlemail.com License: Apache Software License 2.0 Description: wsgicors |buildstatus| ======== .. |buildstatus| image:: https://travis-ci.org/may-day/wsgicors.svg?branch=master This is a WSGI middleware that answers CORS preflight requests and adds the needed header to the response. For CORS see: http://www.w3.org/TR/cors/ Usage ----- Either plug it in programmatically as in this pyramid example: .. code:: python def app(global_config, **settings): """ This function returns a WSGI application. It is usually called by the PasteDeploy framework during ``paster serve``. """ def get_root(request): return {} config = Configurator(root_factory=get_root, settings=settings) config.begin() # whatever it takes to config your app goes here config.end() from wsgicors import CORS return CORS(config.make_wsgi_app(), headers="*", methods="*", maxage="180", origin="*") or plug it into your wsgi pipeline via paste ini to let it serve by waitress for instance: :: [app:myapp] use = egg:mysuperapp#app ### # wsgi server configuration ### [server:main] use = egg:waitress#main host = 0.0.0.0 port = 6543 [pipeline:main] pipeline = cors myapp [filter:cors] use = egg:wsgicors#middleware # define a "free" policy free_origin=copy free_headers=* free_expose_headers=* free_methods=HEAD, OPTIONS, GET free_maxage=180 # define a "subdom" policy subdom_origin=http://example.com http://example2.com https://*.example.com subdom_headers=* subdom_methods=HEAD, OPTIONS, GET, POST, PUT, DELETE subdom_expose_headers=Foo, Doom subdom_maxage=180 # define a combination of policies, they are evaluated in the order given by the policy keyword # the first that matches the request's origin will be used policy=subdom,free # policy matching strategy # matchstrategy=firstmatch Keywords are: - ``origin`` - ``headers`` - ``methods`` - ``credentials`` - ``maxage`` for ``origin``: - use ``copy`` which will copy whatever origin the request comes from - a space separated list of hostnames - they can also contain wildcards like ``*`` or ``?`` (fnmatch lib is used for matching). If a match is found the original host is returned. - any other literal will be be copied verbatim (like ``*`` for instance to allow any source) for ``headers``: - use ``*`` which will allow whatever header is asked for - any other literal will be be copied verbatim for ``expose_headers``: - use ``*`` to allow access to any header the client might wish to access - any other literal will be be copied verbatim for ``methods``: - use ``*`` which will allow whatever method is asked for - any other literal will be be copied verbatim (like ``POST, PATCH, PUT, DELETE`` for instance) for ``credentials``: - use ``true`` - anything else will be ignored (that is no response header for ``Access-Control-Allow-Credentials`` is sent) for ``maxage``: - give the number of seconds the answer can be used by a client, anything nonempty will be copied verbatim As can be seen in the example above, a policy needs to be created with the ``policy`` keyword. The options need then be prefixed with the policy name and a ``_``. The ``policy`` keyword itself can be a comma separated list. If so the origin of the request is matched against the origins defined in the policies and the first matching is the policy used. An alternative matching strategy would be ``verbmatch``, that selects the first of the listed that also matches the request method. To switch between the strategies use the ``matchstrategy`` keyword: - use ``firstmatch`` (the default) to select the first of the policies that matches on the ``origin`` keyword - use ``verbmatch`` to select the first of the policies that matches on the ``methods`` and ``origin`` keyword Changes ======= Version 0.7.0 ------------- - ``verbmulti`` matching strategy, that matches the first listed policy that also matches the requested METHOD - relaxed dependency on lru_cache version Version 0.6.0 ------------- - support for multiple policies - caching of matching results Version 0.5.1 ------------- - check for request being preflight - reworked tests Version 0.5.0 ------------- - support for Access-Control-Expose-Headers - Header ``Vary`` is set to ``Origin`` if origin policy differs from ``*`` Version 0.4.1 ------------- - py3 utf-8 related setup fixes Version 0.4 ----------- - python3 compatibility Version 0.3 ----------- - ``origin`` now takes space separated list of hostnames. They can be filename patterns like \*.domain.tld Version 0.2 ----------- - Access-Control-Allow-Credentials is now returned in the actual reponse if specified by policy Credits ======= “wsgicors” is written and maintained by Norman Krämer. Contributors ------------ The following people contributed directly or indirectly to this project: - `Julien De Vos `_ - `Ryan Shaw `_ - `David Douard `_ - `MattSANU `_ - `Sami Salonen `_ - `Sami Salonen `_ - `Wouter Claeys `_ Please add yourself here when you submit your first pull request. Keywords: wsgi,cors Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Internet :: WWW/HTTP :: WSGI wsgicors-0.7.0/wsgicors.egg-info/SOURCES.txt0000664000175000017500000000045013054644036021410 0ustar normannorman00000000000000AUTHORS.rst CHANGES.rst LICENSE MANIFEST.in README.rst setup.cfg setup.py test-wsgicors.py wsgicors.py wsgicors.egg-info/PKG-INFO wsgicors.egg-info/SOURCES.txt wsgicors.egg-info/dependency_links.txt wsgicors.egg-info/entry_points.txt wsgicors.egg-info/requires.txt wsgicors.egg-info/top_level.txtwsgicors-0.7.0/wsgicors.egg-info/requires.txt0000664000175000017500000000004513054644036022124 0ustar normannorman00000000000000backports.functools_lru_cache >= 1.0 wsgicors-0.7.0/wsgicors.egg-info/top_level.txt0000664000175000017500000000001113054644036022247 0ustar normannorman00000000000000wsgicors wsgicors-0.7.0/wsgicors.egg-info/entry_points.txt0000664000175000017500000000012413054644036023020 0ustar normannorman00000000000000 [paste.filter_app_factory] middleware = wsgicors:make_middleware wsgicors-0.7.0/wsgicors.egg-info/dependency_links.txt0000664000175000017500000000000113054644036023573 0ustar normannorman00000000000000 wsgicors-0.7.0/CHANGES.rst0000664000175000017500000000160413054642025015772 0ustar normannorman00000000000000Changes ======= Version 0.7.0 ------------- - ``verbmulti`` matching strategy, that matches the first listed policy that also matches the requested METHOD - relaxed dependency on lru_cache version Version 0.6.0 ------------- - support for multiple policies - caching of matching results Version 0.5.1 ------------- - check for request being preflight - reworked tests Version 0.5.0 ------------- - support for Access-Control-Expose-Headers - Header ``Vary`` is set to ``Origin`` if origin policy differs from ``*`` Version 0.4.1 ------------- - py3 utf-8 related setup fixes Version 0.4 ----------- - python3 compatibility Version 0.3 ----------- - ``origin`` now takes space separated list of hostnames. They can be filename patterns like \*.domain.tld Version 0.2 ----------- - Access-Control-Allow-Credentials is now returned in the actual reponse if specified by policy wsgicors-0.7.0/AUTHORS.rst0000664000175000017500000000110013054642025016036 0ustar normannorman00000000000000Credits ======= “wsgicors” is written and maintained by Norman Krämer. Contributors ------------ The following people contributed directly or indirectly to this project: - `Julien De Vos `_ - `Ryan Shaw `_ - `David Douard `_ - `MattSANU `_ - `Sami Salonen `_ - `Sami Salonen `_ - `Wouter Claeys `_ Please add yourself here when you submit your first pull request. wsgicors-0.7.0/test-wsgicors.py0000664000175000017500000004152713054642025017367 0ustar normannorman00000000000000# -*- encoding: utf-8 -*- # # This file is part of wsgicors # # wsgicors is a WSGI middleware that answers CORS preflight requests # # copyright 2014-2015 Norman Krämer # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from webob import Request, Response from wsgicors import make_middleware as mw from nose import with_setup deny = {"policy":"deny"} free = {"policy":"pol", "pol_origin":"*", "pol_methods":"*", "pol_headers":"*", "pol_expose_headers":"*", "pol_credentials":"true", "pol_maxage":"100" } multi = {"policy":"pol2,pol1", "pol1_origin":"*", "pol1_methods":"*", "pol1_headers":"*", "pol1_expose_headers":"*", "pol1_credentials":"true", "pol1_maxage":"100", "pol2_origin":"*.woopy.com", "pol2_methods":"*", "pol2_headers":"*", "pol2_expose_headers":"*", "pol2_credentials":"true", "pol2_maxage":"100", } # example from https://github.com/may-day/wsgicors/pull/16 # note that pol1 does not allow PUT, but pol2 does verbmulti = {"policy":"pol2,pol1", "pol1_origin":"*.ourdomain.com", "pol1_headers":"*", "pol1_methods":"HEAD, OPTIONS, GET, POST, PUT, DELETE", "pol1_maxage":"180", "pol2_origin":"*", "pol2_headers":"*", "pol2_methods":"HEAD, OPTIONS, GET", "pol2_maxage":"180", } preflight_headers = {'REQUEST_METHOD':'OPTIONS', 'Access-Control-Request-Method':'*', 'Origin':'localhost'} request_headers = {'REQUEST_METHOD':'GET', 'Access-Control-Request-Method':'*', 'Origin':'localhost'} def setup(): pass @with_setup(setup) def test_selectPolicy_firstmatch(): "check whether correct policy is returned" multi2 = multi.copy() multi2["policy"] = "pol2,pol1" multi2["matchstrategy"] = "firstmatch" corsed = mw(Response("this is not a preflight response"), multi2) policyname, ret_origin = corsed.selectPolicy("palim.woopy.com") assert policyname == "pol2", "'pol2' should have been returned since it matches first (but result was: '%s')" % policyname assert ret_origin == "palim.woopy.com", "'palim.woopy.com' expected since its matched by pol2 (but result was: '%s')" % ret_origin policyname, ret_origin = corsed.selectPolicy("palim.com") assert policyname == "pol1", "'pol1' should have been returned since it matches first (but result was: '%s')" % policyname assert ret_origin == "*", "'*' expected since its matched by pol1 (but result was: '%s')" % ret_origin multi2 = multi.copy() multi2["policy"] = "pol1,pol2" corsed = mw(Response("this is not a preflight response"), multi2) policyname, ret_origin = corsed.selectPolicy("palim.woopy.com") assert policyname == "pol1", "'pol1' should have been returned since it matches first (but result was: '%s')" % policyname assert ret_origin == "*", "'*' expectedsince its matched by pol1 (but result was: '%s')" % ret_origin @with_setup(setup) def test_selectPolicy_verbmatch(): "check whether correct policy is returned" multi2 = verbmulti.copy() multi2["policy"] = "pol2,pol1" multi2["matchstrategy"] = "verbmatch" corsed = mw(Response("this is not a preflight response"), multi2) policyname, ret_origin = corsed.selectPolicy("ourdomain", "PUT") assert policyname == "pol1", "'pol1' should have been returned since it matches both origin and verb first (but result was: '%s')" % policyname multi2 = verbmulti.copy() multi2["policy"] = "pol2,pol1" multi2["matchstrategy"] = "verbmatch" multi2["pol1_methods"] = "*" corsed = mw(Response("this is not a preflight response"), multi2) policyname, ret_origin = corsed.selectPolicy("ourdomain", "PUT") assert policyname == "pol1", "'pol1' should have been returned since it matches both origin and verb first (but result was: '%s')" % policyname @with_setup(setup) def test_non_preflight_are_not_answered(): "requests that don't match preflight criteria are ignored" corsed = mw(Response("this is not a preflight response"), free) for drop_header in preflight_headers.keys(): hdr=preflight_headers.copy() del hdr[drop_header] yield non_preflight_are_not_answered, corsed, hdr def non_preflight_are_not_answered(corsed, hdr): "requests that don't match preflight criteria are ignored" req = prepRequest(hdr) res = req.get_response(corsed) assert res.body.decode("utf-8") == "this is not a preflight response", "No preflight should have been detected (body was: '%s')" % res.body def prepRequest(hdr, **kw): req = Request.blank("/") req.method= "GET" if "REQUEST_METHOD" not in hdr else hdr["REQUEST_METHOD"] for k, v in hdr.items(): if k != "REQUEST_METHOD": req.headers[k] = v for k,v in kw.items(): k=getRequestHeaderName(k) req.headers[k] = v return req @with_setup(setup) def testdeny(): "Denied policy" corsed = mw(Response("non preflight"), deny) preflight = prepRequest(preflight_headers) res = preflight.get_response(corsed) assert res.body.decode("utf-8") == "", "Body must be empty but was:%s" % res.body assert "Access-Control-Allow-Origin" not in res.headers, "Header should not be in repsonse" assert "Access-Control-Allow-Credentials" not in res.headers, "Header should not be in repsonse" assert "Access-Control-Allow-Methods" not in res.headers, "Header should not be in repsonse" assert "Access-Control-Allow-Headers" not in res.headers, "Header should not be in repsonse" assert "Access-Control-Max-Age" not in res.headers, "Header should not be in repsonse" assert "Access-Control-Expose-Headers" not in res.headers, "Header should not be in repsonse" assert "Vary" not in res.headers, "Header should not be in repsonse" @with_setup(setup) def test_origin_policy_match(): policy = free.copy() policy["pol_origin"] = "http://example.com example?.com https://*.example.com" corsed = mw(Response("non preflight response"), policy) ### preflight request for origin, expected in [("localhost", None), ("http://example.com", "http://example.com"), ("example2.com", "example2.com"), ("https://www.example.com", "https://www.example.com")]: yield preflight_check_result, corsed, "Origin", origin, expected ### actual request for origin, origin_expected, vary_expected in [("localhost", None, None), ("http://example.com", "http://example.com", "Origin"), ("example2.com", "example2.com", "Origin"), ("https://www.example.com", "https://www.example.com", "Origin")]: yield request_check_result, corsed, "Origin", origin, origin_expected, ("Vary", vary_expected) @with_setup(setup) def test_origin_policy_copy(): policy = free.copy() policy["pol_origin"] = "copy" corsed = mw(Response("non preflight response"), policy) ### preflight request for origin, expected in [("localhost", "localhost"), ("example.com", "example.com")]: yield preflight_check_result, corsed, "Origin", origin, expected ### actual request for origin, origin_expected, vary_expected in [("localhost", "localhost", "Origin"), ("example.com", "example.com", "Origin")]: yield request_check_result, corsed, "Origin", origin, origin_expected, ("Vary", vary_expected) @with_setup(setup) def test_origin_policy_all(): policy = free.copy() policy["pol_origin"] = "*" corsed = mw(Response("non preflight response"), policy) ### preflight request for origin, expected in [("localhost", "*")]: yield preflight_check_result, corsed, "Origin", origin, expected ### actual request for origin, origin_expected, vary_expected in [("localhost", "localhost", None)]: yield request_check_result, corsed, "Origin", origin, origin_expected, ("Vary", vary_expected) @with_setup(setup) def test_method_policy_all(): policy = free.copy() policy["pol_methods"] = "*" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Method", requested, expected ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Method", requested, expected @with_setup(setup) def test_method_policy_fixed(): policy = free.copy() policy["pol_methods"] = "PUT, GET" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "PUT, GET")]: yield preflight_check_result, corsed, "Method", requested, expected ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Method", requested, expected @with_setup(setup) def test_header_policy_all(): policy = free.copy() policy["pol_headers"] = "*" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected @with_setup(setup) def test_headers_policy_fixed(): policy = free.copy() policy["pol_headers"] = "Wooble" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "Wooble")]: yield preflight_check_result, corsed, "Headers", requested, expected ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected @with_setup(setup) def test_credentials_policy_true(): "Allow-Credentials should be added to the response" policy = free.copy() policy["pol_credentials"] = "true" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected, ("Access-Control-Allow-Credentials", "true") ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected, ("Access-Control-Allow-Credentials", "true") @with_setup(setup) def test_credentials_policy_no(): "Allow-Credentials should not be present, if policy is different from 'yes'" policy = free.copy() policy["pol_credentials"] = "no" # something different from "yes" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected, ("Access-Control-Allow-Credentials", None) ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected, ("Access-Control-Allow-Credentials", None) @with_setup(setup) def test_credentials_policy_none(): "Allow-Credentials should not be present" policy = free.copy() del policy["pol_credentials"] corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected, ("Access-Control-Allow-Credentials", None) ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected, ("Access-Control-Allow-Credentials", None) @with_setup(setup) def test_age_policy_set(): "Add Max-Age added to preflight response" policy = free.copy() policy["pol_maxage"]="100" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected, ("Access-Control-Max-Age", "100") ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected, ("Access-Control-Max-Age", None) @with_setup(setup) def test_age_policy_unset(): "Add Max-Age not in preflight response" policy = free.copy() del policy["pol_maxage"] corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected, ("Access-Control-Max-Age", None) ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected, ("Access-Control-Max-Age", None) @with_setup(setup) def test_expose_header_policy_set(): "Add Expose-Headers in actual request if policy says so" policy = free.copy() policy["pol_expose_headers"] = "exposed" corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected, ("Access-Control-Expose-Headers", None) ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected, ("Access-Control-Expose-Headers", "exposed") @with_setup(setup) def test_expose_header_policy_unset(): "No Expose-Headers in actual request if not given" policy = free.copy() del policy["pol_expose_headers"] corsed = mw(Response("non preflight response"), policy) ### preflight request for requested, expected in [("woopy", "woopy")]: yield preflight_check_result, corsed, "Headers", requested, expected, ("Access-Control-Expose-Headers", None) ### actual request for requested, expected in [("woopy", None)]: yield request_check_result, corsed, "Headers", requested, expected, ("Access-Control-Expose-Headers", None) def preflight_check_result(corsed, check_header, requested, result_expected, *more_header_expectpairs): casename=getRequestHeaderName(check_header) preflight = prepRequest(preflight_headers, **{check_header:requested}) res = preflight.get_response(corsed) res_header = getResponseHeaderName(check_header) result=res.headers.get(res_header) assert result == result_expected, "Preflight %s - %s: expected '%s' but got '%s'" % (casename, res_header, result_expected, result) for header, expected in more_header_expectpairs: result=res.headers.get(header) assert result == expected, "Preflight %s - %s: expected '%s' but got '%s'" % (casename, header, expected, result) def request_check_result(corsed, check_header, requested, result_expected, *more_header_expectpairs): casename=getRequestHeaderName(check_header) request = prepRequest(request_headers, **{check_header:requested}) res = request.get_response(corsed) result=res.body.decode("utf-8") expected = "non preflight response" assert result == expected, "ActualRequest %s - Body: expected '%s' but got '%s'" % (casename, expected, result) res_header = getResponseHeaderName(check_header) result=res.headers.get(res_header) assert result == result_expected, "ActualRequest %s - %s: expected '%s' but got '%s'" % (casename, res_header, result_expected, result) for header, expected in more_header_expectpairs: result=res.headers.get(header) assert result == expected, "ActualRequest %s - %s: expected '%s' but got '%s'" % (casename, header, expected, result) def getResponseHeaderName(name): rename={ "Method":"Access-Control-Allow-Methods" ,"Origin":"Access-Control-Allow-Origin" ,"Headers":"Access-Control-Allow-Headers" ,"Credentials":"Access-Control-Allow-Credentials" ,"Age":"Access-Control-Max-Age" } return rename.get(name) def getRequestHeaderName(name): if name not in ("Origin", ): name="Access-Control-Request-" + name.capitalize() return name wsgicors-0.7.0/setup.py0000664000175000017500000000327613054642025015711 0ustar normannorman00000000000000#-*- coding:utf-8 -*- from setuptools import setup import sys, os import codecs here = os.path.abspath(os.path.dirname(__file__)) def readfile(fname): return codecs.open(os.path.join(here, fname), encoding='utf-8').read() version = '0.7.0' README = readfile('README.rst') CHANGES = readfile('CHANGES.rst') AUTHORS = readfile('AUTHORS.rst') install_requires=[] if sys.version_info < (3, 2): install_requires=["backports.functools_lru_cache >= 1.0"] # hack, or test wont run on py2.7 try: import multiprocessing import logging except: pass setup(name='wsgicors', version=version, description="WSGI for Cross Origin Resource Sharing (CORS)", long_description=README + '\n\n' + CHANGES + '\n\n' + AUTHORS, classifiers = [ "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Internet :: WWW/HTTP :: WSGI" ], keywords=["wsgi", "cors"], author='Norman Krämer', author_email='kraemer.norman@googlemail.com', url="https://github.com/may-day/wsgicors", license='Apache Software License 2.0', py_modules=["wsgicors"], install_requires = install_requires, tests_require = [ 'nose', 'nose-testconfig', 'webob' ], test_suite = 'nose.collector', entry_points = """ [paste.filter_app_factory] middleware = wsgicors:make_middleware """ ) wsgicors-0.7.0/README.rst0000664000175000017500000000755013054642025015665 0ustar normannorman00000000000000wsgicors |buildstatus| ======== .. |buildstatus| image:: https://travis-ci.org/may-day/wsgicors.svg?branch=master This is a WSGI middleware that answers CORS preflight requests and adds the needed header to the response. For CORS see: http://www.w3.org/TR/cors/ Usage ----- Either plug it in programmatically as in this pyramid example: .. code:: python def app(global_config, **settings): """ This function returns a WSGI application. It is usually called by the PasteDeploy framework during ``paster serve``. """ def get_root(request): return {} config = Configurator(root_factory=get_root, settings=settings) config.begin() # whatever it takes to config your app goes here config.end() from wsgicors import CORS return CORS(config.make_wsgi_app(), headers="*", methods="*", maxage="180", origin="*") or plug it into your wsgi pipeline via paste ini to let it serve by waitress for instance: :: [app:myapp] use = egg:mysuperapp#app ### # wsgi server configuration ### [server:main] use = egg:waitress#main host = 0.0.0.0 port = 6543 [pipeline:main] pipeline = cors myapp [filter:cors] use = egg:wsgicors#middleware # define a "free" policy free_origin=copy free_headers=* free_expose_headers=* free_methods=HEAD, OPTIONS, GET free_maxage=180 # define a "subdom" policy subdom_origin=http://example.com http://example2.com https://*.example.com subdom_headers=* subdom_methods=HEAD, OPTIONS, GET, POST, PUT, DELETE subdom_expose_headers=Foo, Doom subdom_maxage=180 # define a combination of policies, they are evaluated in the order given by the policy keyword # the first that matches the request's origin will be used policy=subdom,free # policy matching strategy # matchstrategy=firstmatch Keywords are: - ``origin`` - ``headers`` - ``methods`` - ``credentials`` - ``maxage`` for ``origin``: - use ``copy`` which will copy whatever origin the request comes from - a space separated list of hostnames - they can also contain wildcards like ``*`` or ``?`` (fnmatch lib is used for matching). If a match is found the original host is returned. - any other literal will be be copied verbatim (like ``*`` for instance to allow any source) for ``headers``: - use ``*`` which will allow whatever header is asked for - any other literal will be be copied verbatim for ``expose_headers``: - use ``*`` to allow access to any header the client might wish to access - any other literal will be be copied verbatim for ``methods``: - use ``*`` which will allow whatever method is asked for - any other literal will be be copied verbatim (like ``POST, PATCH, PUT, DELETE`` for instance) for ``credentials``: - use ``true`` - anything else will be ignored (that is no response header for ``Access-Control-Allow-Credentials`` is sent) for ``maxage``: - give the number of seconds the answer can be used by a client, anything nonempty will be copied verbatim As can be seen in the example above, a policy needs to be created with the ``policy`` keyword. The options need then be prefixed with the policy name and a ``_``. The ``policy`` keyword itself can be a comma separated list. If so the origin of the request is matched against the origins defined in the policies and the first matching is the policy used. An alternative matching strategy would be ``verbmatch``, that selects the first of the listed that also matches the request method. To switch between the strategies use the ``matchstrategy`` keyword: - use ``firstmatch`` (the default) to select the first of the policies that matches on the ``origin`` keyword - use ``verbmatch`` to select the first of the policies that matches on the ``methods`` and ``origin`` keyword