Debian Codegraph @

README.rst

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