| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
"""CORS configuration container class definition.""" |
| 16 |
|
| 17 |
import collections |
| 18 |
import warnings |
| 19 |
from collections.abc import Mapping |
| 20 |
from typing import Any, Union |
| 21 |
|
| 22 |
from aiohttp import hdrs, web |
| 23 |
|
| 24 |
from .abc import AbstractRouterAdapter |
| 25 |
from .preflight_handler import _PreflightHandler |
| 26 |
from .resource_options import ResourceOptions |
| 27 |
from .urldispatcher_router_adapter import ResourcesUrlDispatcherRouterAdapter |
| 28 |
|
| 29 |
__all__ = ("CorsConfig",) |
| 30 |
|
| 31 |
|
| 32 |
_TRUE = "true" |
| 33 |
|
| 34 |
|
| 35 |
_SIMPLE_RESPONSE_HEADERS = frozenset( |
| 36 |
[ |
| 37 |
hdrs.CACHE_CONTROL, |
| 38 |
hdrs.CONTENT_LANGUAGE, |
| 39 |
hdrs.CONTENT_TYPE, |
| 40 |
hdrs.EXPIRES, |
| 41 |
hdrs.LAST_MODIFIED, |
| 42 |
hdrs.PRAGMA, |
| 43 |
] |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
def _parse_config_options( |
| 48 |
config: Mapping[str, Union[ResourceOptions, Mapping[str, Any]]] = None, |
| 49 |
): |
| 50 |
"""Parse CORS configuration (default or per-route) |
| 51 |
|
| 52 |
:param config: |
| 53 |
Mapping from Origin to Resource configuration (allowed headers etc) |
| 54 |
defined either as mapping or `ResourceOptions` instance. |
| 55 |
|
| 56 |
Raises `ValueError` if configuration is not correct. |
| 57 |
""" |
| 58 |
|
| 59 |
if config is None: |
| 60 |
return {} |
| 61 |
|
| 62 |
if not isinstance(config, collections.abc.Mapping): |
| 63 |
raise ValueError(f"Config must be mapping, got '{config}'") |
| 64 |
|
| 65 |
parsed = {} |
| 66 |
|
| 67 |
options_keys = {"allow_credentials", "expose_headers", "allow_headers", "max_age"} |
| 68 |
|
| 69 |
for origin, options in config.items(): |
| 70 |
|
| 71 |
|
| 72 |
if not isinstance(origin, str): |
| 73 |
raise ValueError(f"Origin must be string, got '{origin}'") |
| 74 |
|
| 75 |
if isinstance(options, ResourceOptions): |
| 76 |
resource_options = options |
| 77 |
|
| 78 |
else: |
| 79 |
if not isinstance(options, collections.abc.Mapping): |
| 80 |
raise ValueError( |
| 81 |
"Origin options must be either " |
| 82 |
"aiohttp_cors.ResourceOptions instance or mapping, " |
| 83 |
"got '{}'".format(options) |
| 84 |
) |
| 85 |
|
| 86 |
unexpected_args = frozenset(options.keys()) - options_keys |
| 87 |
if unexpected_args: |
| 88 |
raise ValueError( |
| 89 |
"Unexpected keywords in resource options: {}".format( |
| 90 |
|
| 91 |
",".join(map(str, unexpected_args)) |
| 92 |
) |
| 93 |
) |
| 94 |
|
| 95 |
resource_options = ResourceOptions(**options) |
| 96 |
|
| 97 |
parsed[origin] = resource_options |
| 98 |
|
| 99 |
return parsed |
| 100 |
|
| 101 |
|
| 102 |
_ConfigType = Mapping[str, Union[ResourceOptions, Mapping[str, Any]]] |
| 103 |
|
| 104 |
|
| 105 |
class _CorsConfigImpl(_PreflightHandler): |
| 106 |
|
| 107 |
def __init__(self, app: web.Application, router_adapter: AbstractRouterAdapter): |
| 108 |
self._app = app |
| 109 |
|
| 110 |
self._router_adapter = router_adapter |
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
self._app.on_response_prepare.append(self._on_response_prepare) |
| 115 |
|
| 116 |
def add(self, routing_entity, config: _ConfigType = None): |
| 117 |
"""Enable CORS for specific route or resource. |
| 118 |
|
| 119 |
If route is passed CORS is enabled for route's resource. |
| 120 |
|
| 121 |
:param routing_entity: |
| 122 |
Route or Resource for which CORS should be enabled. |
| 123 |
:param config: |
| 124 |
CORS options for the route. |
| 125 |
:return: `routing_entity`. |
| 126 |
""" |
| 127 |
|
| 128 |
parsed_config = _parse_config_options(config) |
| 129 |
|
| 130 |
self._router_adapter.add_preflight_handler( |
| 131 |
routing_entity, self._preflight_handler |
| 132 |
) |
| 133 |
self._router_adapter.set_config_for_routing_entity( |
| 134 |
routing_entity, parsed_config |
| 135 |
) |
| 136 |
|
| 137 |
return routing_entity |
| 138 |
|
| 139 |
async def _on_response_prepare( |
| 140 |
self, request: web.Request, response: web.StreamResponse |
| 141 |
): |
| 142 |
"""Non-preflight CORS request response processor. |
| 143 |
|
| 144 |
If request is done on CORS-enabled route, process request parameters |
| 145 |
and set appropriate CORS response headers. |
| 146 |
""" |
| 147 |
if not self._router_adapter.is_cors_enabled_on_request( |
| 148 |
request |
| 149 |
) or self._router_adapter.is_preflight_request(request): |
| 150 |
|
| 151 |
|
| 152 |
return |
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
config = self._router_adapter.get_non_preflight_request_config(request) |
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
origin = request.headers.get(hdrs.ORIGIN) |
| 161 |
if origin is None: |
| 162 |
|
| 163 |
return |
| 164 |
|
| 165 |
options = config.get(origin, config.get("*")) |
| 166 |
if options is None: |
| 167 |
|
| 168 |
return |
| 169 |
|
| 170 |
assert hdrs.ACCESS_CONTROL_ALLOW_ORIGIN not in response.headers |
| 171 |
assert hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS not in response.headers |
| 172 |
assert hdrs.ACCESS_CONTROL_EXPOSE_HEADERS not in response.headers |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
if options.expose_headers == "*": |
| 178 |
|
| 179 |
exposed_headers = ( |
| 180 |
frozenset(response.headers.keys()) - _SIMPLE_RESPONSE_HEADERS |
| 181 |
) |
| 182 |
response.headers[hdrs.ACCESS_CONTROL_EXPOSE_HEADERS] = ",".join( |
| 183 |
exposed_headers |
| 184 |
) |
| 185 |
|
| 186 |
elif options.expose_headers: |
| 187 |
|
| 188 |
response.headers[hdrs.ACCESS_CONTROL_EXPOSE_HEADERS] = ",".join( |
| 189 |
options.expose_headers |
| 190 |
) |
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
response.headers[hdrs.ACCESS_CONTROL_ALLOW_ORIGIN] = origin |
| 195 |
if options.allow_credentials: |
| 196 |
|
| 197 |
response.headers[hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS] = _TRUE |
| 198 |
|
| 199 |
async def _get_config(self, request, origin, request_method): |
| 200 |
config = await self._router_adapter.get_preflight_request_config( |
| 201 |
request, origin, request_method |
| 202 |
) |
| 203 |
return config |
| 204 |
|
| 205 |
|
| 206 |
class CorsConfig: |
| 207 |
"""CORS configuration instance. |
| 208 |
|
| 209 |
The instance holds default CORS parameters and per-route options specified |
| 210 |
in `add()` method. |
| 211 |
|
| 212 |
Each `aiohttp.web.Application` can have exactly one instance of this class. |
| 213 |
""" |
| 214 |
|
| 215 |
def __init__( |
| 216 |
self, |
| 217 |
app: web.Application, |
| 218 |
*, |
| 219 |
defaults: _ConfigType = None, |
| 220 |
router_adapter: AbstractRouterAdapter = None, |
| 221 |
): |
| 222 |
"""Construct CORS configuration. |
| 223 |
|
| 224 |
:param app: |
| 225 |
Application for which CORS configuration is built. |
| 226 |
:param defaults: |
| 227 |
Default CORS settings for origins. |
| 228 |
:param router_adapter: |
| 229 |
Router adapter. Required if application uses non-default router. |
| 230 |
""" |
| 231 |
|
| 232 |
self.defaults = _parse_config_options(defaults) |
| 233 |
|
| 234 |
self._cors_impl = None |
| 235 |
|
| 236 |
self._resources_router_adapter = None |
| 237 |
self._resources_cors_impl = None |
| 238 |
|
| 239 |
self._old_routes_cors_impl = None |
| 240 |
|
| 241 |
if router_adapter is None: |
| 242 |
router_adapter = ResourcesUrlDispatcherRouterAdapter( |
| 243 |
app.router, self.defaults |
| 244 |
) |
| 245 |
|
| 246 |
self._cors_impl = _CorsConfigImpl(app, router_adapter) |
| 247 |
|
| 248 |
def add(self, routing_entity, config: _ConfigType = None, webview: bool = False): |
| 249 |
"""Enable CORS for specific route or resource. |
| 250 |
|
| 251 |
If route is passed CORS is enabled for route's resource. |
| 252 |
|
| 253 |
:param routing_entity: |
| 254 |
Route or Resource for which CORS should be enabled. |
| 255 |
:param config: |
| 256 |
CORS options for the route. |
| 257 |
:return: `routing_entity`. |
| 258 |
""" |
| 259 |
|
| 260 |
if webview: |
| 261 |
warnings.warn( |
| 262 |
"webview argument is deprecated, " |
| 263 |
"views are handled authomatically without " |
| 264 |
"extra settings", |
| 265 |
DeprecationWarning, |
| 266 |
stacklevel=2, |
| 267 |
) |
| 268 |
|
| 269 |
return self._cors_impl.add(routing_entity, config) |