Debian Codegraph @

aiohttp_cors/cors_config.py

raw symbols SCIP
1 # Copyright 2015 Vladimir Rutsky <[email protected]>
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
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 # Positive response to Access-Control-Allow-Credentials
32 _TRUE = "true"
33 # CORS simple response headers:
34 # <http://www.w3.org/TR/cors/#simple-response-header>
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 # TODO: check that all origins are properly formatted.
71 # This is not a security issue, since origin is compared as strings.
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 # pylint: disable=bad-builtin
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 # Register hook for all responses. This hook handles CORS-related
113 # headers on non-preflight requests.
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 # Either not CORS enabled route, or preflight request which is
151 # handled in its own handler.
152 return
153
154 # Processing response of non-preflight CORS-enabled request.
155
156 config = self._router_adapter.get_non_preflight_request_config(request)
157
158 # Handle according to part 6.1 of the CORS specification.
159
160 origin = request.headers.get(hdrs.ORIGIN)
161 if origin is None:
162 # Terminate CORS according to CORS 6.1.1.
163 return
164
165 options = config.get(origin, config.get("*"))
166 if options is None:
167 # Terminate CORS according to CORS 6.1.2.
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 # Process according to CORS 6.1.4.
175 # Set exposed headers (server headers exposed to client) before
176 # setting any other headers.
177 if options.expose_headers == "*":
178 # Expose all headers that are set in response.
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 # Expose predefined list of headers.
188 response.headers[hdrs.ACCESS_CONTROL_EXPOSE_HEADERS] = ",".join(
189 options.expose_headers
190 )
191
192 # Process according to CORS 6.1.3.
193 # Set allowed origin.
194 response.headers[hdrs.ACCESS_CONTROL_ALLOW_ORIGIN] = origin
195 if options.allow_credentials:
196 # Set allowed credentials.
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)