Debian Codegraph @

aiohttp_cors/preflight_handler.py

raw symbols SCIP
1 from aiohttp import hdrs, web
2
3 # Positive response to Access-Control-Allow-Credentials
4 _TRUE = "true"
5
6
7 class _PreflightHandler:
8
9 @staticmethod
10 def _parse_request_method(request: web.Request):
11 """Parse Access-Control-Request-Method header of the preflight request"""
12 method = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_METHOD)
13 if method is None:
14 raise web.HTTPForbidden(
15 text="CORS preflight request failed: "
16 "'Access-Control-Request-Method' header is not specified"
17 )
18
19 # FIXME: validate method string (ABNF: method = token), if parsing
20 # fails, raise HTTPForbidden.
21
22 return method
23
24 @staticmethod
25 def _parse_request_headers(request: web.Request):
26 """Parse Access-Control-Request-Headers header or the preflight request
27
28 Returns set of headers in upper case.
29 """
30 headers = request.headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
31 if headers is None:
32 return frozenset()
33
34 # FIXME: validate each header string, if parsing fails, raise
35 # HTTPForbidden.
36 # FIXME: check, that headers split and stripped correctly (according
37 # to ABNF).
38 headers = (h.strip(" \t").upper() for h in headers.split(","))
39 # pylint: disable=bad-builtin
40 return frozenset(filter(None, headers))
41
42 async def _get_config(self, request, origin, request_method):
43 raise NotImplementedError()
44
45 async def _preflight_handler(self, request: web.Request):
46 """CORS preflight request handler"""
47
48 # Handle according to part 6.2 of the CORS specification.
49
50 origin = request.headers.get(hdrs.ORIGIN)
51 if origin is None:
52 # Terminate CORS according to CORS 6.2.1.
53 raise web.HTTPForbidden(
54 text="CORS preflight request failed: "
55 "origin header is not specified in the request"
56 )
57
58 # CORS 6.2.3. Doing it out of order is not an error.
59 request_method = self._parse_request_method(request)
60
61 # CORS 6.2.5. Doing it out of order is not an error.
62
63 try:
64 config = await self._get_config(request, origin, request_method)
65 except KeyError:
66 raise web.HTTPForbidden(
67 text="CORS preflight request failed: "
68 "request method {!r} is not allowed "
69 "for {!r} origin".format(request_method, origin)
70 )
71
72 if not config:
73 # No allowed origins for the route.
74 # Terminate CORS according to CORS 6.2.1.
75 raise web.HTTPForbidden(
76 text="CORS preflight request failed: " "no origins are allowed"
77 )
78
79 options = config.get(origin, config.get("*"))
80 if options is None:
81 # No configuration for the origin - deny.
82 # Terminate CORS according to CORS 6.2.2.
83 raise web.HTTPForbidden(
84 text="CORS preflight request failed: "
85 "origin '{}' is not allowed".format(origin)
86 )
87
88 # CORS 6.2.4
89 request_headers = self._parse_request_headers(request)
90
91 # CORS 6.2.6
92 if options.allow_headers == "*":
93 pass
94 else:
95 disallowed_headers = request_headers - options.allow_headers
96 if disallowed_headers:
97 raise web.HTTPForbidden(
98 text="CORS preflight request failed: "
99 "headers are not allowed: {}".format(", ".join(disallowed_headers))
100 )
101
102 # Ok, CORS actual request with specified in the preflight request
103 # parameters is allowed.
104 # Set appropriate headers and return 200 response.
105
106 response = web.Response()
107
108 # CORS 6.2.7
109 response.headers[hdrs.ACCESS_CONTROL_ALLOW_ORIGIN] = origin
110 if options.allow_credentials:
111 # Set allowed credentials.
112 response.headers[hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS] = _TRUE
113
114 # CORS 6.2.8
115 if options.max_age is not None:
116 response.headers[hdrs.ACCESS_CONTROL_MAX_AGE] = str(options.max_age)
117
118 # CORS 6.2.9
119 # TODO: more optimal for client preflight request cache would be to
120 # respond with ALL allowed methods.
121 response.headers[hdrs.ACCESS_CONTROL_ALLOW_METHODS] = request_method
122
123 # CORS 6.2.10
124 if request_headers:
125 # Note: case of the headers in the request is changed, but this
126 # shouldn't be a problem, since the headers should be compared in
127 # the case-insensitive way.
128 response.headers[hdrs.ACCESS_CONTROL_ALLOW_HEADERS] = ",".join(
129 request_headers
130 )
131
132 return response