pax_global_header00006660000000000000000000000064130763703420014517gustar00rootroot0000000000000052 comment=866125cb9d6b0f767fb94430015a3e6a5e63ab08 aiohttp-cors-0.5.3/000077500000000000000000000000001307637034200141405ustar00rootroot00000000000000aiohttp-cors-0.5.3/.gitignore000066400000000000000000000012221307637034200161250ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python /env/ /build/ develop-eggs/ /dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg /*.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ /.tox/ .coverage .coverage.* /.cache nosetests.xml coverage.xml *,cover # Sphinx documentation docs/_build/ # PyBuilder target/ aiohttp-cors-0.5.3/.jscs.json000066400000000000000000000032521307637034200160550ustar00rootroot00000000000000{ "requireCurlyBraces": [ "if", "else", "for", "while", "do", "try", "catch" ], "requireOperatorBeforeLineBreak": true, "requireCamelCaseOrUpperCaseIdentifiers": true, "maximumLineLength": { "value": 80, "allowComments": true, "allowRegex": true }, "validateIndentation": 2, "validateQuoteMarks": "'", "disallowMultipleLineStrings": true, "disallowMixedSpacesAndTabs": true, "disallowTrailingWhitespace": true, "disallowSpaceAfterPrefixUnaryOperators": true, "disallowMultipleVarDecl": true, "requireSpaceAfterKeywords": [ "if", "else", "for", "while", "do", "switch", "return", "try", "catch" ], "requireSpaceBeforeBinaryOperators": [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", "+=", "+", "-", "*", "/", "%", "<<", ">>", ">>>", "&", "|", "^", "&&", "||", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ], "requireSpaceAfterBinaryOperators": true, "requireSpacesInConditionalExpression": true, "requireSpaceBeforeBlockStatements": true, "requireSpacesInForStatement": true, "requireLineFeedAtFileEnd": true, "requireSpacesInFunctionExpression": { "beforeOpeningCurlyBrace": true }, "disallowSpacesInsideObjectBrackets": "all", "disallowSpacesInsideArrayBrackets": "all", "disallowSpacesInsideParentheses": true, "disallowMultipleLineBreaks": true, "disallowNewlineBeforeBlockStatements": [ "if", "else", "try", "catch", "finally", "do", "while", "for", "function" ] } aiohttp-cors-0.5.3/.jshintrc000066400000000000000000000022701307637034200157660ustar00rootroot00000000000000{ "asi": false, "bitwise": false, "boss": false, "browser": true, "camelcase": true, "couch": false, "curly": true, "debug": false, "devel": true, "dojo": false, "eqeqeq": true, "eqnull": true, "es3": true, "esnext": false, "evil": false, "expr": true, "forin": false, "funcscope": true, "globalstrict": false, "immed": true, "iterator": false, "jquery": false, "lastsemic": false, "latedef": false, "laxbreak": true, "laxcomma": false, "loopfunc": true, "mootools": false, "multistr": false, "newcap": true, "noarg": true, "node": false, "noempty": false, "nonew": true, "nonstandard": false, "nomen": false, "onecase": false, "onevar": false, "passfail": false, "plusplus": false, "proto": false, "prototypejs": false, "regexdash": true, "regexp": false, "rhino": false, "undef": true, "unused": "strict", "scripturl": true, "shadow": false, "smarttabs": true, "strict": false, "sub": false, "supernew": false, "trailing": true, "validthis": true, "withstmt": false, "white": true, "worker": false, "wsh": false, "yui": false, "indent": 4, "predef": ["require", "define", "JSON"], "quotmark": "single", "maxcomplexity": 10, "esnext": true } aiohttp-cors-0.5.3/.pep8rc000066400000000000000000000003331307637034200153410ustar00rootroot00000000000000; TODO: This configuration currently not used in pytest-pep8, see ; [pep8] show-source = yes statistics = yes count = yes aiohttp-cors-0.5.3/.pylintrc000066400000000000000000000304321307637034200160070ustar00rootroot00000000000000[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore= # Pickle collected data for later comparisons. persistent=yes # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= # Deprecated. It was used to include message's id in output. Use --msg-template # instead. #include-ids=no # Deprecated. It was used to include symbolic ids of messages in output. Use # --msg-template instead. #symbols=no # Use multiple processes to speed up Pylint. jobs=1 # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code extension-pkg-whitelist= # Allow optimization of some AST trees. This will activate a peephole AST # optimizer, which will apply various small optimizations. For instance, it can # be used to obtain the result of joining multiple strings with the addition # operator. Joining a lot of strings can lead to a maximum recursion error in # Pylint and this flag can prevent that. It has one side effect, the resulting # AST will be different than the one from reality. optimize-ast=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED confidence= # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. #enable= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" disable=E1604,W1629,W1605,I0020,W1609,W1615,W1610,W1618,W1608,W1622,W1640,E1603,W1635,W1636,W1634,W1628,W1614,E1601,W1601,I0021,E1605,W1611,W1612,W1619,W1616,W1638,W1626,W1630,W1607,E1602,W1623,W1613,W1606,W1625,W0704,W1639,W1603,W1632,E1606,W1602,W1637,W1624,W1620,E1608,W1627,E1607,W1633,W1604,W1617,W1621 [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=yes # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. # Path/line on separate added to allow IDE to parse error messages and # provide interactive link on the place of the error. msg-template={path}:{line}: {C}:{msg_id}:{line:3d},{column:2d}: {msg} ({symbol}) [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format logging-modules=logging [FORMAT] # Maximum number of characters on a single line. max-line-length=100 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no # List of optional constructs for which whitespace checking is disabled no-space-check=trailing-comma,dict-separator # Maximum number of lines in a module max-module-lines=1000 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME,XXX,TODO [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the name of dummy variables (i.e. expectedly # not used). dummy-variables-rgx=_$|dummy # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_,_cb [BASIC] # Required attributes for module, separated by a comma required-attributes= # List of builtins function names that should not be used, separated by a comma bad-functions=map,filter # Good variable names which should always be accepted, separated by a comma good-names=i,j,k,ex,Run,_ # Bad variable names which should always be refused, separated by a comma bad-names=foo,bar,baz,toto,tutu,tata # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Include a hint for the correct naming format with invalid-name include-naming-hint=no # Regular expression matching correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Naming hint for module names module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression matching correct method names method-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for method names method-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct class attribute names class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Naming hint for class attribute names class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ # Regular expression matching correct class names class-rgx=[A-Z_][a-zA-Z0-9]+$ # Naming hint for class names class-name-hint=[A-Z_][a-zA-Z0-9]+$ # Regular expression matching correct function names function-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for function names function-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct inline iteration names inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ # Naming hint for inline iteration names inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ # Regular expression matching correct constant names const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Naming hint for constant names const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ # Regular expression matching correct argument names argument-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for argument names argument-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct attribute names attr-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for attribute names attr-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression matching correct variable names variable-rgx=[a-z_][a-z0-9_]{2,30}$ # Naming hint for variable names variable-name-hint=[a-z_][a-z0-9_]{2,30}$ # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=__.*__ # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis ignored-modules= # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members=REQUEST,acl_users,aq_parent [SPELLING] # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=stringprep,optparse # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict,_fields,_replace,_source,_make [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branches=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception aiohttp-cors-0.5.3/.travis.yml000066400000000000000000000044371307637034200162610ustar00rootroot00000000000000language: python dist: trusty python: - 3.4 - 3.5 - 3.6 # TODO: Use Travis apt addon, when chromium-chromedriver will be supported # three: https://github.com/travis-ci/apt-package-whitelist/issues/574 before_install: - sudo apt-get -qq update - sudo apt-get install -y chromium-browser chromium-chromedriver install: - pip install --upgrade pip setuptools wheel # aiohttp git repo has only *.pyx files, so install cython too. - '[ -z "$MASTER_AIOHTTP" ] || pip install -U cython git+https://github.com/KeepSafe/aiohttp.git' - pip install -Ur requirements-dev.txt before_script: # Start X-server for Selenium tests. - "export DISPLAY=:99.0" - "sh -e /etc/init.d/xvfb start" - sleep 3 # give xvfb some time to start script: - '[ "$TYPE" != "test" ] || python setup.py test --addopts -v --addopts -s' - '[ "$TYPE" != "lint" ] || python setup.py check' env: global: - WEBDRIVER_CHROMEDRIVER_PATH=/usr/lib/chromium-browser/chromedriver matrix: # PYTHONASYNCIODEBUG environment variable is considered as enabled if it # is any non empty string. - TYPE=test PYTHONASYNCIODEBUG= MASTER_AIOHTTP= - TYPE=test PYTHONASYNCIODEBUG=x MASTER_AIOHTTP= - TYPE=test PYTHONASYNCIODEBUG= MASTER_AIOHTTP=x - TYPE=test PYTHONASYNCIODEBUG=x MASTER_AIOHTTP=x matrix: include: # Environment to deploy project on PyPI. - python: "3.5" env: DEPLOY_ENV=1 - python: "3.5" env: TYPE=lint # Deploy on PyPI all tagged build on master branch. deploy: provider: pypi user: aiohttp-cors-deploy password: secure: KViGT/W2vWRWZkV5bZYLiI3v/qXVRGEFAs8G1OMx/OhLvHTj8vO6pZ+hlzLi9zTnBTVHG2xEOrwtjiuHxpJMcDPAul3rn0fwSXy9BRDAeR7B7RIlvLxegMRTnWtsj5x8/VkqQDrPW5YWmuXFb4tDJ+LEkadUrkF9YhJvtUnSQcEOOHVvJa4DekMhZEVM8AKA+7AT9FibWZbJ5s8bTjLke77/eyX7+1DdgC7G++ZesK2HKS1vlM7fN+cWPyUFofXwcEc42rwQwJ5FY2saqTvPN5GBOMpXdaBUmSyYT64447TVFoINbAFuCa3tUeY7ZQpC6B8bHVqEGq+UAujUGU7uhid29CHV03PTFeupTZRscVDkL+IEUjK6Ft+x/B9eStVpKh9d5Yh8INZkdoHVmybJo62k/YHwxAu7ftG+q1bUAHwgKkukXa+ZpmSD2v6BggVUBS6qFwv6tnKpuI0jRsneEUXPmJVUHpv6lPzVRPW/lQDZqxUvESz9w9mitwBiMA7q8jyL9w4zJVKAETjo6llWGQ2wOLjaz3LwuQ8vDOKfWOdvk78W8Usw5amkp2invyidU/2+Y1hlekRuhaMEaUdd4GPmP8beOh7CEXJr5bD3QjbqOpOMi+d+3rYVR0NZMWxawgtUGMBb/8DUNq4sD4Na5G3sGSy+rHMtDAuMOOUlLoU= distributions: sdist bdist_wheel on: tags: true branch: master condition: $DEPLOY_ENV = 1 aiohttp-cors-0.5.3/CHANGES.rst000066400000000000000000000040741307637034200157470ustar00rootroot00000000000000CHANGES ======= 0.5.3 (2017-04-21) ------------------ - Fix `typing` being installed on Python 3.6. 0.5.2 (2017-03-28) ------------------ - Fix tests compatibility with ``aiohttp`` 2.0. This release and release v0.5.0 should work on ``aiohttp`` 2.0. 0.5.1 (2017-03-23) ------------------ - Enforce ``aiohttp`` version to be less than 2.0. Newer ``aiohttp`` releases will be supported in the next release. 0.5.0 (2016-11-18) ------------------ - Fix compatibility with ``aiohttp`` 1.1 0.4.0 (2016-04-04) ------------------ - Fixed support with new Resources objects introduced in ``aiohttp`` 0.21.0. Minimum supported version of ``aiohttp`` is 0.21.4 now. - New Resources objects are supported. You can specify default configuration for a Resource and use ``allow_methods`` to explicitly list allowed methods (or ``*`` for all HTTP methods): .. code-block:: python # Allow POST and PUT requests from "http://client.example.org" origin. hello_resource = cors.add(app.router.add_resource("/hello"), { "http://client.example.org": aiohttp_cors.ResourceOptions( allow_methods=["POST", "PUT"]), }) # No need to add POST and PUT routes into CORS configuration object. hello_resource.add_route("POST", handler_post) hello_resource.add_route("PUT", handler_put) # Still you can add additional methods to CORS configuration object: cors.add(hello_resource.add_route("DELETE", handler_delete)) - ``AbstractRouterAdapter`` was completely rewritten to be more Router agnostic. 0.3.0 (2016-02-06) ------------------ - Rename ``UrlDistatcherRouterAdapter`` to ``UrlDispatcherRouterAdapter``. - Set maximum supported ``aiohttp`` version to ``0.20.2``, see bug #30 for details. 0.2.0 (2015-11-30) ------------------ - Move ABCs from ``aiohttp_cors.router_adapter`` to ``aiohttp_cors.abc``. - Rename ``RouterAdapter`` to ``AbstractRouterAdapter``. - Fix bug with configuring CORS for named routes. 0.1.0 (2015-11-05) ------------------ * Initial release. aiohttp-cors-0.5.3/LICENSE000066400000000000000000000261361307637034200151550ustar00rootroot00000000000000 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. aiohttp-cors-0.5.3/MANIFEST.in000066400000000000000000000001751307637034200157010ustar00rootroot00000000000000include LICENSE include CHANGES.rst include README.rst recursive-include tests *.py include tests/integration/test_page.html aiohttp-cors-0.5.3/README.rst000066400000000000000000000365741307637034200156460ustar00rootroot00000000000000CORS support for aiohttp ======================== ``aiohttp_cors`` library implements `Cross Origin Resource Sharing (CORS) `__ support for `aiohttp `__ asyncio-powered asynchronous HTTP server. Jump directly to `Usage`_ part to see how to use ``aiohttp_cors``. Same-origin policy ================== Web security model is tightly connected to `Same-origin policy (SOP) `__. In short: web pages cannot *Read* resources which origin doesn't match origin of requested page, but can *Embed* (or *Execute*) resources and have limited ability to *Write* resources. Origin of a page is defined in the `Standard `__ as tuple ``(schema, host, port)`` (there is a notable exception with Internet Explorer: it doesn't use port to define origin, but uses it's own `Security Zones `__). Can *Embed* means that resource from other origin can be embedded into the page, e.g. by using `` aiohttp-cors-0.5.3/tests/integration/test_real_browser.py000066400000000000000000000264201307637034200237300ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """System test using real browser. """ import os import json import asyncio import socket import unittest import pathlib import logging import webbrowser from aiohttp import web, hdrs import selenium.common.exceptions from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from aiohttp_cors import setup, ResourceOptions from ..aio_test_base import create_server, AioTestBase, asynctest class _ServerDescr: """Auxiliary class for storing server info""" def __init__(self): self.app = None self.cors = None self.handler = None self.server = None self.url = None class IntegrationServers: """Integration servers starting/stopping manager""" def __init__(self, use_resources, *, loop=None): self.servers = {} self.loop = loop if self.loop is None: self.loop = asyncio.get_event_loop() self.use_resources = use_resources self._logger = logging.getLogger("IntegrationServers") @property def origin_server_url(self): return self.servers["origin"].url @asyncio.coroutine def start_servers(self): test_page_path = pathlib.Path(__file__).with_name("test_page.html") @asyncio.coroutine def handle_test_page(request: web.Request) -> web.StreamResponse: with test_page_path.open("r", encoding="utf-8") as f: return web.Response( text=f.read(), headers={hdrs.CONTENT_TYPE: "text/html"}) @asyncio.coroutine def handle_no_cors(request: web.Request) -> web.StreamResponse: return web.Response( text="""{"type": "no_cors.json"}""", headers={hdrs.CONTENT_TYPE: "application/json"}) @asyncio.coroutine def handle_resource(request: web.Request) -> web.StreamResponse: return web.Response( text="""{"type": "resource"}""", headers={hdrs.CONTENT_TYPE: "application/json"}) @asyncio.coroutine def handle_servers_addresses( request: web.Request) -> web.StreamResponse: servers_addresses = \ {name: descr.url for name, descr in self.servers.items()} return web.Response( text=json.dumps(servers_addresses)) # For most resources: # "origin" server has no CORS configuration. # "allowing" server explicitly allows CORS requests to "origin" server. # "denying" server explicitly disallows CORS requests to "origin" # server. # "free_for_all" server allows CORS requests for all origins server. # "no_cors" server has no CORS configuration. cors_server_names = ["allowing", "denying", "free_for_all"] server_names = cors_server_names + ["origin", "no_cors"] for server_name in server_names: assert server_name not in self.servers self.servers[server_name] = _ServerDescr() server_sockets = {} # Create applications and sockets. for server_name, server_descr in self.servers.items(): server_descr.app = web.Application() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 0)) sock.listen(10) server_sockets[server_name] = sock hostaddr, port = sock.getsockname() server_descr.url = "http://{host}:{port}".format( host=hostaddr, port=port) # Server test page from origin server. self.servers["origin"].app.router.add_route( "GET", "/", handle_test_page) self.servers["origin"].app.router.add_route( "GET", "/servers_addresses", handle_servers_addresses) # Add routes to all servers. for server_name in server_names: app = self.servers[server_name].app app.router.add_route("GET", "/no_cors.json", handle_no_cors) app.router.add_route("GET", "/cors_resource", handle_resource, name="cors_resource") cors_default_configs = { "allowing": { self.servers["origin"].url: ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*") }, "denying": { # Allow requests to other than "origin" server. self.servers["allowing"].url: ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*") }, "free_for_all": { "*": ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*") }, } # Configure CORS. for server_name, server_descr in self.servers.items(): default_config = cors_default_configs.get(server_name) if default_config is None: continue server_descr.cors = setup( server_descr.app, defaults=default_config) # Add CORS routes. for server_name in cors_server_names: server_descr = self.servers[server_name] # TODO: Starting from aiohttp 0.21.0 name-based access returns # Resource, not Route. Manually get route while aiohttp_cors # doesn't support configuring for Resources. resource = server_descr.app.router["cors_resource"] route = next(iter(resource)) if self.use_resources: server_descr.cors.add(resource) server_descr.cors.add(route) else: server_descr.cors.add(route) # Start servers. for server_name, server_descr in self.servers.items(): handler = server_descr.app.make_handler() server = yield from create_server(handler, self.loop, sock=server_sockets[server_name]) server_descr.handler = handler server_descr.server = server self._logger.info("Started server '%s' at '%s'", server_name, server_descr.url) @asyncio.coroutine def stop_servers(self): for server_descr in self.servers.values(): server_descr.server.close() yield from server_descr.handler.finish_connections() yield from server_descr.server.wait_closed() yield from server_descr.app.cleanup() self.servers = {} def _get_chrome_driver(): driver_path_env = "WEBDRIVER_CHROMEDRIVER_PATH" if driver_path_env in os.environ: driver = webdriver.Chrome(executable_path=os.environ[driver_path_env]) else: driver = webdriver.Chrome() return driver class TestInBrowser(AioTestBase): @asyncio.coroutine def _test_in_webdriver(self, driver, use_resources): # TODO: Use pytest's fixtures to test use resources/not use resources. servers = IntegrationServers(use_resources) yield from servers.start_servers() def selenium_thread(): driver.get(servers.origin_server_url) assert "aiohttp_cors" in driver.title wait = WebDriverWait(driver, 10) run_button = wait.until(EC.element_to_be_clickable( (By.ID, "runTestsButton"))) # Start tests. run_button.send_keys(Keys.RETURN) # Wait while test will finish (until clear button is not # activated). wait.until(EC.element_to_be_clickable( (By.ID, "clearResultsButton"))) # Get results json results_area = driver.find_element_by_id("results") return json.loads(results_area.get_attribute("value")) try: results = yield from self.loop.run_in_executor( self.thread_pool_executor, selenium_thread) self.assertEqual(results["status"], "success") for test_name, test_data in results["data"].items(): with self.subTest(group_name=test_name): self.assertEqual(test_data["status"], "success", msg=(test_name, test_data)) finally: yield from servers.stop_servers() @asynctest @asyncio.coroutine def test_firefox(self): try: driver = webdriver.Firefox() except selenium.common.exceptions.WebDriverException: raise unittest.SkipTest try: yield from self._test_in_webdriver(driver, False) finally: driver.close() @asynctest @asyncio.coroutine def test_chromium(self): try: driver = _get_chrome_driver() except selenium.common.exceptions.WebDriverException: raise unittest.SkipTest try: yield from self._test_in_webdriver(driver, False) finally: driver.close() @asynctest @asyncio.coroutine def test_firefox_resource(self): try: driver = webdriver.Firefox() except selenium.common.exceptions.WebDriverException: raise unittest.SkipTest try: yield from self._test_in_webdriver(driver, True) finally: driver.close() @asynctest @asyncio.coroutine def test_chromium_resource(self): try: driver = _get_chrome_driver() except selenium.common.exceptions.WebDriverException: raise unittest.SkipTest try: yield from self._test_in_webdriver(driver, True) finally: driver.close() def _run_integration_server(): """Runs integration server for interactive debugging.""" logging.basicConfig(level=logging.INFO) logger = logging.getLogger("run_integration_server") loop = asyncio.get_event_loop() servers = IntegrationServers() logger.info("Starting integration servers...") loop.run_until_complete(servers.start_servers()) try: webbrowser.open(servers.origin_server_url) except webbrowser.Error: pass try: loop.run_forever() except KeyboardInterrupt: pass finally: logger.info("Stopping integration servers...") loop.run_until_complete(servers.stop_servers()) if __name__ == "__main__": # This module can be run in the following way: # $ python -m tests.integration.test_real_browser # from aiohttp_cors root directory. _run_integration_server() aiohttp-cors-0.5.3/tests/unit/000077500000000000000000000000001307637034200162615ustar00rootroot00000000000000aiohttp-cors-0.5.3/tests/unit/__init__.py000066400000000000000000000000001307637034200203600ustar00rootroot00000000000000aiohttp-cors-0.5.3/tests/unit/test___about__.py000066400000000000000000000017111307637034200216000ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """Test aiohttp_cors package metainformation. """ import unittest from pkg_resources import parse_version import aiohttp_cors class TestMetaInformation(unittest.TestCase): """Test package metainformation""" # pylint: disable=no-self-use def test_version(self): """Test package version string""" parse_version(aiohttp_cors.__version__) aiohttp-cors-0.5.3/tests/unit/test_cors_config.py000066400000000000000000000063371307637034200221760ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """aiohttp_cors.cors_config unit tests. """ import asyncio import unittest from aiohttp import web from aiohttp_cors import CorsConfig, ResourceOptions def _handler(request): return web.Response(text="Done") class TestCorsConfig(unittest.TestCase): """Unit tests for CorsConfig""" def setUp(self): self.loop = asyncio.new_event_loop() self.app = web.Application(loop=self.loop) self.cors = CorsConfig(self.app, defaults={ "*": ResourceOptions() }) self.get_route = self.app.router.add_route( "GET", "/get_path", _handler) self.options_route = self.app.router.add_route( "OPTIONS", "/options_path", _handler) def tearDown(self): self.loop.close() def test_add_options_route(self): """Test configuring OPTIONS route""" with self.assertRaises(RuntimeError): self.cors.add(self.options_route.resource) def test_plain_named_route(self): """Test adding plain named route.""" # Adding CORS routes should not introduce new named routes. self.assertEqual(len(self.app.router.keys()), 0) route = self.app.router.add_route( "GET", "/{name}", _handler, name="dynamic_named_route") self.assertEqual(len(self.app.router.keys()), 1) self.cors.add(route) self.assertEqual(len(self.app.router.keys()), 1) def test_dynamic_named_route(self): """Test adding dynamic named route.""" self.assertEqual(len(self.app.router.keys()), 0) route = self.app.router.add_route( "GET", "/{name}", _handler, name="dynamic_named_route") self.assertEqual(len(self.app.router.keys()), 1) self.cors.add(route) self.assertEqual(len(self.app.router.keys()), 1) def test_static_named_route(self): """Test adding dynamic named route.""" self.assertEqual(len(self.app.router.keys()), 0) route = self.app.router.add_static( "/file", "/", name="dynamic_named_route") self.assertEqual(len(self.app.router.keys()), 1) self.cors.add(route) self.assertEqual(len(self.app.router.keys()), 1) def test_static_resource(self): """Test adding static resource.""" self.assertEqual(len(self.app.router.keys()), 0) self.app.router.add_static( "/file", "/", name="dynamic_named_route") self.assertEqual(len(self.app.router.keys()), 1) for resource in list(self.app.router.resources()): if issubclass(resource, web.StaticResource): self.cors.add(resource) self.assertEqual(len(self.app.router.keys()), 1) aiohttp-cors-0.5.3/tests/unit/test_resource_options.py000066400000000000000000000041711307637034200232770ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """aiohttp_cors.resource_options unit tests. """ import unittest from aiohttp_cors.resource_options import ResourceOptions class TestResourceOptions(unittest.TestCase): """Unit tests for ResourceOptions class""" def test_init_no_args(self): """Test construction without arguments""" opts = ResourceOptions() self.assertFalse(opts.allow_credentials) self.assertFalse(opts.expose_headers) self.assertFalse(opts.allow_headers) self.assertIsNone(opts.max_age) def test_comparison(self): self.assertTrue(ResourceOptions() == ResourceOptions()) self.assertFalse(ResourceOptions() != ResourceOptions()) self.assertFalse( ResourceOptions(allow_credentials=True) == ResourceOptions()) self.assertTrue( ResourceOptions(allow_credentials=True) != ResourceOptions()) def test_allow_methods(self): self.assertIsNone(ResourceOptions().allow_methods) self.assertEqual( ResourceOptions(allow_methods='*').allow_methods, '*') self.assertEqual( ResourceOptions(allow_methods=[]).allow_methods, frozenset()) self.assertEqual( ResourceOptions(allow_methods=['get']).allow_methods, frozenset(['GET'])) self.assertEqual( ResourceOptions(allow_methods=['get', 'Post']).allow_methods, {'GET', 'POST'}) with self.assertRaises(ValueError): ResourceOptions(allow_methods='GET') # TODO: test arguments parsing aiohttp-cors-0.5.3/tests/unit/test_urldispatcher_router_adapter.py000066400000000000000000000101521307637034200256420ustar00rootroot00000000000000# Copyright 2015 Vladimir Rutsky # # 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. """aiohttp_cors.urldispatcher_router_adapter unit tests. """ import asyncio import unittest from unittest import mock from aiohttp import web from aiohttp_cors.urldispatcher_router_adapter import \ ResourcesUrlDispatcherRouterAdapter from aiohttp_cors import ResourceOptions def _handler(request): return web.Response(text="Done") class TestResourcesUrlDispatcherRouterAdapter(unittest.TestCase): """Unit tests for CorsConfig""" def setUp(self): self.loop = asyncio.new_event_loop() self.app = web.Application(loop=self.loop) self.adapter = ResourcesUrlDispatcherRouterAdapter( self.app.router, defaults={ "*": ResourceOptions() }) self.get_route = self.app.router.add_route( "GET", "/get_path", _handler) self.options_route = self.app.router.add_route( "OPTIONS", "/options_path", _handler) def tearDown(self): self.loop.close() def test_add_get_route(self): """Test configuring GET route""" result = self.adapter.add_preflight_handler( self.get_route.resource, _handler) self.assertIsNone(result) self.assertEqual(len(self.adapter._resource_config), 0) self.assertEqual( len(self.adapter._resources_with_preflight_handlers), 1) self.assertEqual(len(self.adapter._preflight_routes), 1) def test_add_options_route(self): """Test configuring OPTIONS route""" with self.assertRaisesRegex( ValueError, "CORS must be enabled for route's resource first"): self.adapter.add_preflight_handler(self.options_route, _handler) self.assertFalse(self.adapter._resources_with_preflight_handlers) self.assertFalse(self.adapter._preflight_routes) def test_get_non_preflight_request_config(self): self.adapter.add_preflight_handler( self.get_route.resource, _handler) self.adapter.set_config_for_routing_entity( self.get_route.resource, { 'http://example.org': ResourceOptions(), }) self.adapter.add_preflight_handler( self.get_route, _handler) self.adapter.set_config_for_routing_entity( self.get_route, { 'http://test.example.org': ResourceOptions(), }) request = mock.Mock() with mock.patch('aiohttp_cors.urldispatcher_router_adapter.' 'ResourcesUrlDispatcherRouterAdapter.' 'is_cors_enabled_on_request' ) as is_cors_enabled_on_request, \ mock.patch('aiohttp_cors.urldispatcher_router_adapter.' 'ResourcesUrlDispatcherRouterAdapter.' '_request_resource' ) as _request_resource: is_cors_enabled_on_request.return_value = True _request_resource.return_value = self.get_route.resource self.assertEqual( self.adapter.get_non_preflight_request_config(request), { '*': ResourceOptions(), 'http://example.org': ResourceOptions(), }) request.method = 'GET' self.assertEqual( self.adapter.get_non_preflight_request_config(request), { '*': ResourceOptions(), 'http://example.org': ResourceOptions(), 'http://test.example.org': ResourceOptions(), }) aiohttp-cors-0.5.3/tox.ini000066400000000000000000000005361307637034200154570ustar00rootroot00000000000000[tox] envlist = py34, py35, check [testenv] commands = {envpython} setup.py test deps = pytest [testenv:check] deps = docutils pygments flake8 commands = {envpython} setup.py check -rms flake8 aiohttp_cors tests [pytest] testpaths = aiohttp_cors tests ;addopts = --cov aiohttp_cors ; --pylint-rcfile=.pylintrc --pylint