/aiohttp_cors/resource_options.py

https://github.com/aio-libs/aiohttp-cors · Python · 153 lines · 89 code · 9 blank · 55 comment · 3 complexity · 716f9d5ae1368817cce3afe25c7c8d16 MD5 · raw file

  1. # Copyright 2015 Vladimir Rutsky <vladimir@rutsky.org>
  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. """Resource CORS options class definition.
  15. """
  16. import numbers
  17. import collections
  18. import collections.abc
  19. __all__ = ("ResourceOptions",)
  20. def _is_proper_sequence(seq):
  21. """Returns is seq is sequence and not string."""
  22. return (isinstance(seq, collections.abc.Sequence) and
  23. not isinstance(seq, str))
  24. class ResourceOptions(collections.namedtuple(
  25. "Base",
  26. ("allow_credentials", "expose_headers", "allow_headers", "max_age",
  27. "allow_methods"))):
  28. """Resource CORS options."""
  29. __slots__ = ()
  30. def __init__(self, *, allow_credentials=False, expose_headers=(),
  31. allow_headers=(), max_age=None, allow_methods=None):
  32. """Construct resource CORS options.
  33. Options will be normalized.
  34. :param allow_credentials:
  35. Is passing client credentials to the resource from other origin
  36. is allowed.
  37. See <http://www.w3.org/TR/cors/#user-credentials> for
  38. the definition.
  39. :type allow_credentials: bool
  40. Is passing client credentials to the resource from other origin
  41. is allowed.
  42. :param expose_headers:
  43. Server headers that are allowed to be exposed to the client.
  44. Simple response headers are excluded from this set, see
  45. <http://www.w3.org/TR/cors/#list-of-exposed-headers>.
  46. :type expose_headers: sequence of strings or ``*`` string.
  47. :param allow_headers:
  48. Client headers that are allowed to be passed to the resource.
  49. See <http://www.w3.org/TR/cors/#list-of-headers>.
  50. :type allow_headers: sequence of strings or ``*`` string.
  51. :param max_age:
  52. How long the results of a preflight request can be cached in a
  53. preflight result cache (in seconds).
  54. See <http://www.w3.org/TR/cors/#http-access-control-max-age>.
  55. :param allow_methods:
  56. List of allowed methods or ``*``string. Can be used in resource or
  57. global defaults, but not in specific route.
  58. It's not required to specify all allowed methods for specific
  59. resource, routes that have explicit CORS configuration will be
  60. treated as if their methods are allowed.
  61. """
  62. super().__init__()
  63. def __new__(cls, *, allow_credentials=False, expose_headers=(),
  64. allow_headers=(), max_age=None, allow_methods=None):
  65. """Normalize source parameters and store them in namedtuple."""
  66. if not isinstance(allow_credentials, bool):
  67. raise ValueError(
  68. "'allow_credentials' must be boolean, "
  69. "got '{!r}'".format(allow_credentials))
  70. _allow_credentials = allow_credentials
  71. # `expose_headers` is either "*", or sequence of strings.
  72. if expose_headers == "*":
  73. _expose_headers = expose_headers
  74. elif not _is_proper_sequence(expose_headers):
  75. raise ValueError(
  76. "'expose_headers' must be either '*', or sequence of strings, "
  77. "got '{!r}'".format(expose_headers))
  78. elif expose_headers:
  79. # "Access-Control-Expose-Headers" ":" #field-name
  80. # TODO: Check that headers are valid.
  81. # TODO: Remove headers that in the _SIMPLE_RESPONSE_HEADERS set
  82. # according to
  83. # <http://www.w3.org/TR/cors/#list-of-exposed-headers>.
  84. _expose_headers = frozenset(expose_headers)
  85. else:
  86. # No headers exposed.
  87. _expose_headers = frozenset()
  88. # `allow_headers` is either "*", or set of headers in upper case.
  89. if allow_headers == "*":
  90. _allow_headers = allow_headers
  91. elif not _is_proper_sequence(allow_headers):
  92. raise ValueError(
  93. "'allow_headers' must be either '*', or sequence of strings, "
  94. "got '{!r}'".format(allow_headers))
  95. else:
  96. # TODO: Check that headers are valid.
  97. _allow_headers = frozenset(h.upper() for h in allow_headers)
  98. if max_age is None:
  99. _max_age = None
  100. else:
  101. if not isinstance(max_age, numbers.Integral) or max_age < 0:
  102. raise ValueError(
  103. "'max_age' must be non-negative integer, "
  104. "got '{!r}'".format(max_age))
  105. _max_age = max_age
  106. if allow_methods is None or allow_methods == "*":
  107. _allow_methods = allow_methods
  108. elif not _is_proper_sequence(allow_methods):
  109. raise ValueError(
  110. "'allow_methods' must be either '*', or sequence of strings, "
  111. "got '{!r}'".format(allow_methods))
  112. else:
  113. # TODO: Check that methods are valid.
  114. _allow_methods = frozenset(m.upper() for m in allow_methods)
  115. return super().__new__(
  116. cls,
  117. allow_credentials=_allow_credentials,
  118. expose_headers=_expose_headers,
  119. allow_headers=_allow_headers,
  120. max_age=_max_age,
  121. allow_methods=_allow_methods)
  122. def is_method_allowed(self, method):
  123. if self.allow_methods is None:
  124. return False
  125. if self.allow_methods == '*':
  126. return True
  127. return method.upper() in self.allow_methods