Debian Codegraph @

PKG-INFO

raw
1 Metadata-Version: 2.4
2 Name: aiohttp-cors
3 Version: 0.8.1
4 Summary: CORS support for aiohttp
5 Home-page: https://github.com/aio-libs/aiohttp-cors
6 Author: Vladimir Rutsky and aio-libs team
7 Author-email: [email protected]
8 License: Apache License, Version 2.0
9 Classifier: License :: OSI Approved :: Apache Software License
10 Classifier: Intended Audience :: Developers
11 Classifier: Programming Language :: Python
12 Classifier: Programming Language :: Python :: 3
13 Classifier: Topic :: Software Development :: Libraries
14 Classifier: Topic :: Internet :: WWW/HTTP
15 Classifier: Framework :: AsyncIO
16 Classifier: Operating System :: MacOS :: MacOS X
17 Classifier: Operating System :: Microsoft :: Windows
18 Classifier: Operating System :: POSIX
19 Classifier: Development Status :: 3 - Alpha
20 Classifier: Framework :: aiohttp
21 Requires-Python: >=3.9
22 Description-Content-Type: text/x-rst
23 License-File: LICENSE
24 Requires-Dist: aiohttp>=3.9
25 Dynamic: author
26 Dynamic: author-email
27 Dynamic: classifier
28 Dynamic: description
29 Dynamic: description-content-type
30 Dynamic: home-page
31 Dynamic: license
32 Dynamic: license-file
33 Dynamic: requires-dist
34 Dynamic: requires-python
35 Dynamic: summary
36
37 ========================
38 CORS support for aiohttp
39 ========================
40
41 ``aiohttp_cors`` library implements
42 `Cross Origin Resource Sharing (CORS) <cors_>`__
43 support for `aiohttp <aiohttp_>`__
44 asyncio-powered asynchronous HTTP server.
45
46 Jump directly to `Usage`_ part to see how to use ``aiohttp_cors``.
47
48 Same-origin policy
49 ==================
50
51 Web security model is tightly connected to
52 `Same-origin policy (SOP) <sop_>`__.
53 In short: web pages cannot *Read* resources which origin
54 doesn't match origin of requested page, but can *Embed* (or *Execute*)
55 resources and have limited ability to *Write* resources.
56
57 Origin of a page is defined in the `Standard <cors_>`__ as tuple
58 ``(schema, host, port)``
59 (there is a notable exception with Internet Explorer: it doesn't use port to
60 define origin, but uses it's own
61 `Security Zones <https://msdn.microsoft.com/en-us/library/ms537183.aspx>`__).
62
63 Can *Embed* means that resource from other origin can be embedded into
64 the page,
65 e.g. by using ``<script src="...">``, ``<img src="...">``,
66 ``<iframe src="...">``.
67
68 Cannot *Read* means that resource from other origin *source* cannot be
69 obtained by page
70 (*source* — any information that would allow to reconstruct resource).
71 E.g. the page can *Embed* image with ``<img src="...">``,
72 but it can't get information about specific pixels, so page can't reconstruct
73 original image
74 (though some information from the other resource may still be leaked:
75 e.g. the page can read embedded image dimensions).
76
77 Limited ability to *Write* means, that the page can send POST requests to
78 other origin with limited set of ``Content-Type`` values and headers.
79
80 Restriction to *Read* resource from other origin is related to authentication
81 mechanism that is used by browsers:
82 when browser reads (downloads) resource he automatically sends all security
83 credentials that user previously authorized for that resource
84 (e.g. cookies, HTTP Basic Authentication).
85
86 For example, if *Read* would be allowed and user is authenticated
87 in some internet banking,
88 malicious page would be able to embed internet banking page with ``iframe``
89 (since authentication is done by the browser it may be embedded as if
90 user is directly navigated to internet banking page),
91 then read user private information by reading *source* of the embedded page
92 (which may be not only source code, but, for example,
93 screenshot of the embedded internet banking page).
94
95 Cross-origin resource sharing
96 =============================
97
98 `Cross-origin Resource Sharing (CORS) <cors_>`__ allows to override
99 SOP for specific resources.
100
101 In short, CORS works in the following way.
102
103 When page ``https://client.example.com`` request (*Read*) resource
104 ``https://server.example.com/resource`` that have other origin,
105 browser implicitly appends ``Origin: https://client.example.com`` header
106 to the HTTP request,
107 effectively requesting server to give read permission for
108 the resource to the ``https://client.example.com`` page::
109
110 GET /resource HTTP/1.1
111 Origin: https://client.example.com
112 Host: server.example.com
113
114 If server allows access from the page to the resource, it responds with
115 resource with ``Access-Control-Allow-Origin: https://client.example.com``
116 HTTP header
117 (optionally allowing exposing custom server headers to the page and
118 enabling use of the user credentials on the server resource)::
119
120 Access-Control-Allow-Origin: https://client.example.com
121 Access-Control-Allow-Credentials: true
122 Access-Control-Expose-Headers: X-Server-Header
123
124 Browser checks, if server responded with proper
125 ``Access-Control-Allow-Origin`` header and accordingly allows or denies
126 access for the obtained resource to the page.
127
128 CORS specification designed in a way that servers that are not aware
129 of CORS will not expose any additional information, except allowed by the
130 SOP.
131
132 To request resources with custom headers or using custom HTTP methods
133 (e.g. ``PUT``, ``DELETE``) that are not allowed by SOP,
134 CORS-enabled browser first send *preflight request* to the
135 resource using ``OPTIONS`` method, in which he queries access to the resource
136 with specific method and headers::
137
138 OPTIONS / HTTP/1.1
139 Origin: https://client.example.com
140 Access-Control-Request-Method: PUT
141 Access-Control-Request-Headers: X-Client-Header
142
143 CORS-enabled server responds is requested method is allowed and which of
144 the specified headers are allowed::
145
146 Access-Control-Allow-Origin: https://client.example.com
147 Access-Control-Allow-Credentials: true
148 Access-Control-Allow-Methods: PUT
149 Access-Control-Allow-Headers: X-Client-Header
150 Access-Control-Max-Age: 3600
151
152 Browser checks response to preflight request, and, if actual request allowed,
153 does actual request.
154
155 Installation
156 ============
157
158 You can install ``aiohttp_cors`` as a typical Python library from PyPI or
159 from git:
160
161 .. code-block:: bash
162
163 $ pip install aiohttp_cors
164
165 Usage
166 =====
167
168 To use ``aiohttp_cors`` you need to configure the application and
169 enable CORS on
170 `resources and routes <https://aiohttp.readthedocs.org/en/stable/web.html#resources-and-routes>`__
171 that you want to expose:
172
173 .. code-block:: python
174
175 import asyncio
176 from aiohttp import web
177 import aiohttp_cors
178
179 @asyncio.coroutine
180 def handler(request):
181 return web.Response(
182 text="Hello!",
183 headers={
184 "X-Custom-Server-Header": "Custom data",
185 })
186
187 app = web.Application()
188
189 # `aiohttp_cors.setup` returns `aiohttp_cors.CorsConfig` instance.
190 # The `cors` instance will store CORS configuration for the
191 # application.
192 cors = aiohttp_cors.setup(app)
193
194 # To enable CORS processing for specific route you need to add
195 # that route to the CORS configuration object and specify its
196 # CORS options.
197 resource = cors.add(app.router.add_resource("/hello"))
198 route = cors.add(
199 resource.add_route("GET", handler), {
200 "http://client.example.org": aiohttp_cors.ResourceOptions(
201 allow_credentials=True,
202 expose_headers=("X-Custom-Server-Header",),
203 allow_headers=("X-Requested-With", "Content-Type"),
204 max_age=3600,
205 )
206 })
207
208 Each route has it's own CORS configuration passed in ``CorsConfig.add()``
209 method.
210
211 CORS configuration is a mapping from origins to options for that origins.
212
213 In the example above CORS is configured for the resource under path ``/hello``
214 and HTTP method ``GET``, and in the context of CORS:
215
216 * This resource will be available using CORS only to
217 ``http://client.example.org`` origin.
218
219 * Passing of credentials to this resource will be allowed.
220
221 * The resource will expose to the client ``X-Custom-Server-Header``
222 server header.
223
224 * The client will be allowed to pass ``X-Requested-With`` and
225 ``Content-Type`` headers to the server.
226
227 * Preflight requests will be allowed to be cached by client for ``3600``
228 seconds.
229
230 Resource will be available only to the explicitly specified origins.
231 You can specify "all other origins" using special ``*`` origin:
232
233 .. code-block:: python
234
235 cors.add(route, {
236 "*":
237 aiohttp_cors.ResourceOptions(allow_credentials=False),
238 "http://client.example.org":
239 aiohttp_cors.ResourceOptions(allow_credentials=True),
240 })
241
242 Here the resource specified by ``route`` will be available to all origins with
243 disallowed credentials passing, and with allowed credentials passing only to
244 ``http://client.example.org``.
245
246 By default ``ResourceOptions`` will be constructed without any allowed CORS
247 options.
248 This means, that resource will be available using CORS to specified origin,
249 but client will not be allowed to send either credentials,
250 or send non-simple headers, or read from server non-simple headers.
251
252 To enable sending or receiving all headers you can specify special value
253 ``*`` instead of sequence of headers:
254
255 .. code-block:: python
256
257 cors.add(route, {
258 "http://client.example.org":
259 aiohttp_cors.ResourceOptions(
260 expose_headers="*",
261 allow_headers="*"),
262 })
263
264 You can specify default CORS-enabled resource options using
265 ``aiohttp_cors.setup()``'s ``defaults`` argument:
266
267 .. code-block:: python
268
269 cors = aiohttp_cors.setup(app, defaults={
270 # Allow all to read all CORS-enabled resources from
271 # http://client.example.org.
272 "http://client.example.org": aiohttp_cors.ResourceOptions(),
273 })
274
275 # Enable CORS on routes.
276
277 # According to defaults POST and PUT will be available only to
278 # "http://client.example.org".
279 hello_resource = cors.add(app.router.add_resource("/hello"))
280 cors.add(hello_resource.add_route("POST", handler_post))
281 cors.add(hello_resource.add_route("PUT", handler_put))
282
283 # In addition to "http://client.example.org", GET request will be
284 # allowed from "http://other-client.example.org" origin.
285 cors.add(hello_resource.add_route("GET", handler), {
286 "http://other-client.example.org":
287 aiohttp_cors.ResourceOptions(),
288 })
289
290 # CORS will be enabled only on the resources added to `CorsConfig`,
291 # so following resource will be NOT CORS-enabled.
292 app.router.add_route("GET", "/private", handler)
293
294 Also you can specify default options for resources:
295
296 .. code-block:: python
297
298 # Allow POST and PUT requests from "http://client.example.org" origin.
299 hello_resource = cors.add(app.router.add_resource("/hello"), {
300 "http://client.example.org": aiohttp_cors.ResourceOptions(),
301 })
302 cors.add(hello_resource.add_route("POST", handler_post))
303 cors.add(hello_resource.add_route("PUT", handler_put))
304
305 Resource CORS configuration allows to use ``allow_methods`` option that
306 explicitly specifies list of allowed HTTP methods for origin
307 (or ``*`` for all HTTP methods).
308 By using this option it is not required to add all resource routes to
309 CORS configuration object:
310
311 .. code-block:: python
312
313 # Allow POST and PUT requests from "http://client.example.org" origin.
314 hello_resource = cors.add(app.router.add_resource("/hello"), {
315 "http://client.example.org":
316 aiohttp_cors.ResourceOptions(allow_methods=["POST", "PUT"]),
317 })
318 # No need to add POST and PUT routes into CORS configuration object.
319 hello_resource.add_route("POST", handler_post)
320 hello_resource.add_route("PUT", handler_put)
321 # Still you can add additional methods to CORS configuration object:
322 cors.add(hello_resource.add_route("DELETE", handler_delete))
323
324 Here is an example of how to enable CORS for all origins with all CORS
325 features:
326
327 .. code-block:: python
328
329 cors = aiohttp_cors.setup(app, defaults={
330 "*": aiohttp_cors.ResourceOptions(
331 allow_credentials=True,
332 expose_headers="*",
333 allow_headers="*",
334 )
335 })
336
337 # Add all resources to `CorsConfig`.
338 resource = cors.add(app.router.add_resource("/hello"))
339 cors.add(resource.add_route("GET", handler_get))
340 cors.add(resource.add_route("PUT", handler_put))
341 cors.add(resource.add_route("POST", handler_put))
342 cors.add(resource.add_route("DELETE", handler_delete))
343
344 Old routes API is supported — you can use ``router.add_router`` and
345 ``router.register_route`` as before, though this usage is discouraged:
346
347 .. code-block:: python
348
349 cors.add(
350 app.router.add_route("GET", "/hello", handler), {
351 "http://client.example.org": aiohttp_cors.ResourceOptions(
352 allow_credentials=True,
353 expose_headers=("X-Custom-Server-Header",),
354 allow_headers=("X-Requested-With", "Content-Type"),
355 max_age=3600,
356 )
357 })
358
359 You can enable CORS for all added routes by accessing routes list
360 in the router:
361
362 .. code-block:: python
363
364 # Setup application routes.
365 app.router.add_route("GET", "/hello", handler_get)
366 app.router.add_route("PUT", "/hello", handler_put)
367 app.router.add_route("POST", "/hello", handler_put)
368 app.router.add_route("DELETE", "/hello", handler_delete)
369
370 # Configure default CORS settings.
371 cors = aiohttp_cors.setup(app, defaults={
372 "*": aiohttp_cors.ResourceOptions(
373 allow_credentials=True,
374 expose_headers="*",
375 allow_headers="*",
376 )
377 })
378
379 # Configure CORS on all routes.
380 for route in list(app.router.routes()):
381 cors.add(route)
382
383 You can also use ``CorsViewMixin`` on ``web.View``:
384
385 .. code-block:: python
386
387 class CorsView(web.View, CorsViewMixin):
388
389 cors_config = {
390 "*": ResourceOption(
391 allow_credentials=True,
392 allow_headers="X-Request-ID",
393 )
394 }
395
396 @asyncio.coroutine
397 def get(self):
398 return web.Response(text="Done")
399
400 @custom_cors({
401 "*": ResourceOption(
402 allow_credentials=True,
403 allow_headers="*",
404 )
405 })
406 @asyncio.coroutine
407 def post(self):
408 return web.Response(text="Done")
409
410 cors = aiohttp_cors.setup(app, defaults={
411 "*": aiohttp_cors.ResourceOptions(
412 allow_credentials=True,
413 expose_headers="*",
414 allow_headers="*",
415 )
416 })
417
418 cors.add(
419 app.router.add_route("*", "/resource", CorsView),
420 webview=True)
421
422
423 Security
424 ========
425
426 TODO: fill this
427
428 Development
429 ===========
430
431 To setup development environment:
432
433 .. code-block:: bash
434
435 # Clone sources repository:
436 git clone https://github.com/aio-libs/aiohttp_cors.git .
437 # Create and activate virtual Python environment:
438 python3 -m venv env
439 source env/bin/activate
440 # Install requirements and aiohttp_cors into virtual environment
441 pip install -r requirements-dev.txt
442
443 To run tests:
444
445 .. code-block:: bash
446
447 tox
448
449 To run only runtime tests in current environment:
450
451 .. code-block:: bash
452
453 py.test
454
455 To run only static code analysis checks:
456
457 .. code-block:: bash
458
459 tox -e check
460
461 Running Selenium tests
462 ----------------------
463
464 To run Selenium tests with Firefox web driver you need to install Firefox.
465
466 To run Selenium tests with Chromium web driver you need to:
467
468 1. Install Chrome driver. On Ubuntu 14.04 it's in ``chromium-chromedriver``
469 package.
470
471 2. Either add ``chromedriver`` to PATH or set ``WEBDRIVER_CHROMEDRIVER_PATH``
472 environment variable to ``chromedriver``, e.g. on Ubuntu 14.04
473 ``WEBDRIVER_CHROMEDRIVER_PATH=/usr/lib/chromium-browser/chromedriver``.
474
475 Release process
476 ---------------
477
478 To release version ``vA.B.C`` from the current version of ``master`` branch
479 you need to:
480
481 1. Create local branch ``vA.B.C``.
482 2. In ``CHANGES.rst`` set release date to today.
483 3. In ``aiohttp_cors/__about__.py`` change version from ``A.B.Ca0`` to
484 ``A.B.C``.
485 4. Create pull request with ``vA.B.C`` branch, wait for all checks to
486 successfully finish (Travis and Appveyor).
487 5. Merge pull request to master.
488 6. Update and checkout ``master`` branch.
489
490 7. Create and push tag for release version to GitHub:
491
492 .. code-block:: bash
493
494 git tag vA.B.C
495 git push --tags
496
497 Now Travis should ran tests again, and build and deploy wheel on PyPI.
498
499 If Travis release doesn't work for some reason, use following steps
500 for manual release upload.
501
502 1. Install fresh versions of setuptools and pip.
503 Install ``wheel`` for building wheels.
504 Install ``twine`` for uploading to PyPI.
505
506 .. code-block:: bash
507
508 pip install -U pip setuptools twine wheel
509
510 2. Configure PyPI credentials in ``~/.pypirc``.
511
512 3. Build distribution:
513
514 .. code-block:: bash
515
516 rm -rf build dist; python setup.py sdist bdist_wheel
517
518 4. Upload new release to PyPI:
519
520 .. code-block:: bash
521
522 twine upload dist/*
523
524 8. Edit release description on GitHub if needed.
525 9. Announce new release on the *aio-libs* mailing list:
526 https://groups.google.com/forum/#!forum/aio-libs.
527
528 Post release steps:
529
530 1. In ``CHANGES.rst`` add template for the next release.
531 2. In ``aiohttp_cors/__about__.py`` change version from ``A.B.C`` to
532 ``A.(B + 1).0a0``.
533
534 Bugs
535 ====
536
537 Please report bugs, issues, feature requests, etc. on
538 `GitHub <https://github.com/aio-libs/aiohttp_cors/issues>`__.
539
540
541 License
542 =======
543
544 Copyright 2015 Vladimir Rutsky <[email protected]>.
545
546 Licensed under the
547 `Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>`__,
548 see ``LICENSE`` file for details.
549
550 .. _cors: http://www.w3.org/TR/cors/
551 .. _aiohttp: https://github.com/KeepSafe/aiohttp/
552 .. _sop: https://en.wikipedia.org/wiki/Same-origin_policy
553
554
555 =========
556 CHANGES
557 =========
558
559 0.8.1 (2025-03-31)
560 ==================
561
562 - Fix packaging to not install on Python 3.8.
563
564 0.8.0 (2025-03-11)
565 ==================
566
567 - Make the library compatible with aiohttp 3.9+ and Python 3.9+
568
569 0.7.0 (2018-03-05)
570 ==================
571
572 - Make web view check implicit and type based (#159)
573
574 - Disable Python 3.4 support (#156)
575
576 - Support aiohttp 3.0+ (#155)
577
578 0.6.0 (2017-12-21)
579 ==================
580
581 - Support aiohttp views by ``CorsViewMixin`` (#145)
582
583 0.5.3 (2017-04-21)
584 ==================
585
586 - Fix ``typing`` being installed on Python 3.6.
587
588 0.5.2 (2017-03-28)
589 ==================
590
591 - Fix tests compatibility with ``aiohttp`` 2.0.
592 This release and release v0.5.0 should work on ``aiohttp`` 2.0.
593
594
595 0.5.1 (2017-03-23)
596 ==================
597
598 - Enforce ``aiohttp`` version to be less than 2.0.
599 Newer ``aiohttp`` releases will be supported in the next release.
600
601 0.5.0 (2016-11-18)
602 ==================
603
604 - Fix compatibility with ``aiohttp`` 1.1
605
606
607 0.4.0 (2016-04-04)
608 ==================
609
610 - Fixed support with new Resources objects introduced in ``aiohttp`` 0.21.0.
611 Minimum supported version of ``aiohttp`` is 0.21.4 now.
612
613 - New Resources objects are supported.
614 You can specify default configuration for a Resource and use
615 ``allow_methods`` to explicitly list allowed methods (or ``*`` for all
616 HTTP methods):
617
618 .. code-block:: python
619
620 # Allow POST and PUT requests from "http://client.example.org" origin.
621 hello_resource = cors.add(app.router.add_resource("/hello"), {
622 "http://client.example.org":
623 aiohttp_cors.ResourceOptions(
624 allow_methods=["POST", "PUT"]),
625 })
626 # No need to add POST and PUT routes into CORS configuration object.
627 hello_resource.add_route("POST", handler_post)
628 hello_resource.add_route("PUT", handler_put)
629 # Still you can add additional methods to CORS configuration object:
630 cors.add(hello_resource.add_route("DELETE", handler_delete))
631
632 - ``AbstractRouterAdapter`` was completely rewritten to be more Router
633 agnostic.
634
635 0.3.0 (2016-02-06)
636 ==================
637
638 - Rename ``UrlDistatcherRouterAdapter`` to ``UrlDispatcherRouterAdapter``.
639
640 - Set maximum supported ``aiohttp`` version to ``0.20.2``, see bug #30 for
641 details.
642
643 0.2.0 (2015-11-30)
644 ==================
645
646 - Move ABCs from ``aiohttp_cors.router_adapter`` to ``aiohttp_cors.abc``.
647
648 - Rename ``RouterAdapter`` to ``AbstractRouterAdapter``.
649
650 - Fix bug with configuring CORS for named routes.
651
652 0.1.0 (2015-11-05)
653 ==================
654
655 * Initial release.