Debian Codegraph @

aiohttp_cors/urldispatcher_router_adapter.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 """AbstractRouterAdapter for aiohttp.web.UrlDispatcher."""
16 import collections
17 from typing import Union
18
19 from aiohttp import hdrs, web
20
21 from .abc import AbstractRouterAdapter
22 from .mixin import CorsViewMixin
23
24 # There several usage patterns of routes which should be handled
25 # differently.
26 #
27 # 1. Using new Resources:
28 #
29 # resource = app.router.add_resource(path)
30 # cors.add(resource, resource_defaults=...)
31 # cors.add(resource.add_route(method1, handler1), config=...)
32 # cors.add(resource.add_route(method2, handler2), config=...)
33 # cors.add(resource.add_route(method3, handler3), config=...)
34 #
35 # Here all related Routes (i.e. routes with the same path) are in
36 # a single Resource.
37 #
38 # 2. Using `router.add_static()`:
39 #
40 # route1 = app.router.add_static(
41 # "/images", "/usr/share/app/images/")
42 # cors.add(route1, config=...)
43 #
44 # Here old-style `web.StaticRoute` is created and wrapped with
45 # `web.ResourceAdapter`.
46 #
47 # 3. Using old `router.add_route()`:
48 #
49 # cors.add(app.router.add_route(method1, path, hand1), config=...)
50 # cors.add(app.router.add_route(method2, path, hand2), config=...)
51 # cors.add(app.router.add_route(method3, path, hand3), config=...)
52 #
53 # This creates three Resources with single Route in each.
54 #
55 # 4. Using deprecated `register_route` with manually created
56 # `web.Route`:
57 #
58 # route1 = RouteSubclass(...)
59 # app.router.register_route(route1)
60 # cors.add(route1, config=...)
61 #
62 # Here old-style route is wrapped with `web.ResourceAdapter`.
63 #
64 # Preflight requests is roughly an OPTIONS request with query
65 # "is specific HTTP method is allowed".
66 # In order to properly handle preflight request we need to know which
67 # routes have enabled CORS on the request path and CORS configuration
68 # for requested HTTP method.
69 #
70 # In case of new usage pattern it's simple: we need to take a look at
71 # self._resource_config[resource][method] for the processing resource.
72 #
73 # In case of old usage pattern we need to iterate over routes with
74 # enabled CORS and check is requested path and HTTP method is accepted
75 # by a route.
76
77
78 class _ResourceConfig:
79 def __init__(self, default_config):
80 # Resource default config.
81 self.default_config = default_config
82
83 # HTTP method to route configuration.
84 self.method_config = {}
85
86
87 def _is_web_view(entity, strict=True):
88 webview = False
89 if isinstance(entity, web.AbstractRoute):
90 handler = entity.handler
91 if isinstance(handler, type) and issubclass(handler, web.View):
92 webview = True
93 if not issubclass(handler, CorsViewMixin):
94 if strict:
95 raise ValueError(
96 "web view should be derived from "
97 "aiohttp_cors.CorsViewMixin for working "
98 "with the library"
99 )
100 else:
101 return False
102 return webview
103
104
105 class ResourcesUrlDispatcherRouterAdapter(AbstractRouterAdapter):
106 """Adapter for `UrlDispatcher` for Resources-based routing only.
107
108 Should be used with routes added in the following way:
109
110 resource = app.router.add_resource(path)
111 cors.add(resource, resource_defaults=...)
112 cors.add(resource.add_route(method1, handler1), config=...)
113 cors.add(resource.add_route(method2, handler2), config=...)
114 cors.add(resource.add_route(method3, handler3), config=...)
115 """
116
117 def __init__(self, router: web.UrlDispatcher, defaults):
118 """
119 :param defaults:
120 Default CORS configuration.
121 """
122 self._router = router
123
124 # Default configuration for all routes.
125 self._default_config = defaults
126
127 # Mapping from Resource to _ResourceConfig.
128 self._resource_config = {}
129
130 self._resources_with_preflight_handlers = set()
131 self._preflight_routes = set()
132
133 def add_preflight_handler(
134 self,
135 routing_entity: Union[web.Resource, web.StaticResource, web.ResourceRoute],
136 handler,
137 ):
138 """Add OPTIONS handler for all routes defined by `routing_entity`.
139
140 Does nothing if CORS handler already handles routing entity.
141 Should fail if there are conflicting user-defined OPTIONS handlers.
142 """
143
144 if isinstance(routing_entity, web.Resource):
145 resource = routing_entity
146
147 # Add preflight handler for Resource, if not yet added.
148
149 if resource in self._resources_with_preflight_handlers:
150 # Preflight handler already added for this resource.
151 return
152 for route_obj in resource:
153 if route_obj.method == hdrs.METH_OPTIONS:
154 if route_obj.handler is handler:
155 return # already added
156 else:
157 raise ValueError(
158 "{!r} already has OPTIONS handler {!r}".format(
159 resource, route_obj.handler
160 )
161 )
162 elif route_obj.method == hdrs.METH_ANY:
163 if _is_web_view(route_obj):
164 self._preflight_routes.add(route_obj)
165 self._resources_with_preflight_handlers.add(resource)
166 return
167 else:
168 raise ValueError(
169 "{!r} already has a '*' handler "
170 "for all methods".format(resource)
171 )
172
173 preflight_route = resource.add_route(hdrs.METH_OPTIONS, handler)
174 self._preflight_routes.add(preflight_route)
175 self._resources_with_preflight_handlers.add(resource)
176
177 elif isinstance(routing_entity, web.StaticResource):
178 resource = routing_entity
179
180 # Add preflight handler for Resource, if not yet added.
181
182 if resource in self._resources_with_preflight_handlers:
183 # Preflight handler already added for this resource.
184 return
185
186 resource.set_options_route(handler)
187 preflight_route = resource._routes[hdrs.METH_OPTIONS]
188 self._preflight_routes.add(preflight_route)
189 self._resources_with_preflight_handlers.add(resource)
190
191 elif isinstance(routing_entity, web.ResourceRoute):
192 route = routing_entity
193
194 if not self.is_cors_for_resource(route.resource):
195 self.add_preflight_handler(route.resource, handler)
196
197 else:
198 raise ValueError(
199 f"Resource or ResourceRoute expected, got {routing_entity!r}"
200 )
201
202 def is_cors_for_resource(self, resource: web.Resource) -> bool:
203 """Is CORS is configured for the resource"""
204 return resource in self._resources_with_preflight_handlers
205
206 def _request_route(self, request: web.Request) -> web.ResourceRoute:
207 match_info = request.match_info
208 assert isinstance(match_info, web.UrlMappingMatchInfo)
209 return match_info.route
210
211 def _request_resource(self, request: web.Request) -> web.Resource:
212 return self._request_route(request).resource
213
214 def is_preflight_request(self, request: web.Request) -> bool:
215 """Is `request` is a CORS preflight request."""
216 route = self._request_route(request)
217 if _is_web_view(route, strict=False):
218 return request.method == "OPTIONS"
219 return route in self._preflight_routes
220
221 def is_cors_enabled_on_request(self, request: web.Request) -> bool:
222 """Is `request` is a request for CORS-enabled resource."""
223
224 return self._request_resource(request) in self._resource_config
225
226 def set_config_for_routing_entity(
227 self,
228 routing_entity: Union[web.Resource, web.StaticResource, web.ResourceRoute],
229 config,
230 ):
231 """Record configuration for resource or it's route."""
232
233 if isinstance(routing_entity, (web.Resource, web.StaticResource)):
234 resource = routing_entity
235
236 # Add resource configuration or fail if it's already added.
237 if resource in self._resource_config:
238 raise ValueError(
239 f"CORS is already configured for {resource!r} resource."
240 )
241
242 self._resource_config[resource] = _ResourceConfig(default_config=config)
243
244 elif isinstance(routing_entity, web.ResourceRoute):
245 route = routing_entity
246
247 # Add resource's route configuration or fail if it's already added.
248 if route.resource not in self._resource_config:
249 self.set_config_for_routing_entity(route.resource, config)
250
251 if route.resource not in self._resource_config:
252 raise ValueError(
253 "Can't setup CORS for {!r} request, "
254 "CORS must be enabled for route's resource first.".format(route)
255 )
256
257 resource_config = self._resource_config[route.resource]
258
259 if route.method in resource_config.method_config:
260 raise ValueError(
261 "Can't setup CORS for {!r} route: CORS already "
262 "configured on resource {!r} for {} method".format(
263 route, route.resource, route.method
264 )
265 )
266
267 resource_config.method_config[route.method] = config
268
269 else:
270 raise ValueError(
271 f"Resource or ResourceRoute expected, got {routing_entity!r}"
272 )
273
274 async def get_preflight_request_config(
275 self, preflight_request: web.Request, origin: str, requested_method: str
276 ):
277 assert self.is_preflight_request(preflight_request)
278
279 resource = self._request_resource(preflight_request)
280 resource_config = self._resource_config[resource]
281 defaulted_config = collections.ChainMap(
282 resource_config.default_config, self._default_config
283 )
284
285 options = defaulted_config.get(origin, defaulted_config.get("*"))
286 if options is not None and options.is_method_allowed(requested_method):
287 # Requested method enabled for CORS in defaults, override it with
288 # explicit route configuration (if any).
289 route_config = resource_config.method_config.get(requested_method, {})
290
291 else:
292 # Requested method is not enabled in defaults.
293 # Enable CORS for it only if explicit configuration exists.
294 route_config = resource_config.method_config[requested_method]
295
296 defaulted_config = collections.ChainMap(route_config, defaulted_config)
297
298 return defaulted_config
299
300 def get_non_preflight_request_config(self, request: web.Request):
301 """Get stored CORS configuration for routing entity that handles
302 specified request."""
303
304 assert self.is_cors_enabled_on_request(request)
305
306 resource = self._request_resource(request)
307 resource_config = self._resource_config[resource]
308 # Take Route config (if any) with defaults from Resource CORS
309 # configuration and global defaults.
310 route = request.match_info.route
311 if _is_web_view(route, strict=False):
312 method_config = request.match_info.handler.get_request_config(
313 request, request.method
314 )
315 else:
316 method_config = resource_config.method_config.get(request.method, {})
317 defaulted_config = collections.ChainMap(
318 method_config, resource_config.default_config, self._default_config
319 )
320
321 return defaulted_config