You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

191 lines
6.4 KiB

  1. from __future__ import annotations
  2. import functools
  3. import hmac
  4. import http
  5. from collections.abc import Awaitable, Iterable
  6. from typing import Any, Callable, cast
  7. from ..datastructures import Headers
  8. from ..exceptions import InvalidHeader
  9. from ..headers import build_www_authenticate_basic, parse_authorization_basic
  10. from .server import HTTPResponse, WebSocketServerProtocol
  11. __all__ = ["BasicAuthWebSocketServerProtocol", "basic_auth_protocol_factory"]
  12. Credentials = tuple[str, str]
  13. def is_credentials(value: Any) -> bool:
  14. try:
  15. username, password = value
  16. except (TypeError, ValueError):
  17. return False
  18. else:
  19. return isinstance(username, str) and isinstance(password, str)
  20. class BasicAuthWebSocketServerProtocol(WebSocketServerProtocol):
  21. """
  22. WebSocket server protocol that enforces HTTP Basic Auth.
  23. """
  24. realm: str = ""
  25. """
  26. Scope of protection.
  27. If provided, it should contain only ASCII characters because the
  28. encoding of non-ASCII characters is undefined.
  29. """
  30. username: str | None = None
  31. """Username of the authenticated user."""
  32. def __init__(
  33. self,
  34. *args: Any,
  35. realm: str | None = None,
  36. check_credentials: Callable[[str, str], Awaitable[bool]] | None = None,
  37. **kwargs: Any,
  38. ) -> None:
  39. if realm is not None:
  40. self.realm = realm # shadow class attribute
  41. self._check_credentials = check_credentials
  42. super().__init__(*args, **kwargs)
  43. async def check_credentials(self, username: str, password: str) -> bool:
  44. """
  45. Check whether credentials are authorized.
  46. This coroutine may be overridden in a subclass, for example to
  47. authenticate against a database or an external service.
  48. Args:
  49. username: HTTP Basic Auth username.
  50. password: HTTP Basic Auth password.
  51. Returns:
  52. :obj:`True` if the handshake should continue;
  53. :obj:`False` if it should fail with an HTTP 401 error.
  54. """
  55. if self._check_credentials is not None:
  56. return await self._check_credentials(username, password)
  57. return False
  58. async def process_request(
  59. self,
  60. path: str,
  61. request_headers: Headers,
  62. ) -> HTTPResponse | None:
  63. """
  64. Check HTTP Basic Auth and return an HTTP 401 response if needed.
  65. """
  66. try:
  67. authorization = request_headers["Authorization"]
  68. except KeyError:
  69. return (
  70. http.HTTPStatus.UNAUTHORIZED,
  71. [("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
  72. b"Missing credentials\n",
  73. )
  74. try:
  75. username, password = parse_authorization_basic(authorization)
  76. except InvalidHeader:
  77. return (
  78. http.HTTPStatus.UNAUTHORIZED,
  79. [("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
  80. b"Unsupported credentials\n",
  81. )
  82. if not await self.check_credentials(username, password):
  83. return (
  84. http.HTTPStatus.UNAUTHORIZED,
  85. [("WWW-Authenticate", build_www_authenticate_basic(self.realm))],
  86. b"Invalid credentials\n",
  87. )
  88. self.username = username
  89. return await super().process_request(path, request_headers)
  90. def basic_auth_protocol_factory(
  91. realm: str | None = None,
  92. credentials: Credentials | Iterable[Credentials] | None = None,
  93. check_credentials: Callable[[str, str], Awaitable[bool]] | None = None,
  94. create_protocol: Callable[..., BasicAuthWebSocketServerProtocol] | None = None,
  95. ) -> Callable[..., BasicAuthWebSocketServerProtocol]:
  96. """
  97. Protocol factory that enforces HTTP Basic Auth.
  98. :func:`basic_auth_protocol_factory` is designed to integrate with
  99. :func:`~websockets.legacy.server.serve` like this::
  100. serve(
  101. ...,
  102. create_protocol=basic_auth_protocol_factory(
  103. realm="my dev server",
  104. credentials=("hello", "iloveyou"),
  105. )
  106. )
  107. Args:
  108. realm: Scope of protection. It should contain only ASCII characters
  109. because the encoding of non-ASCII characters is undefined.
  110. Refer to section 2.2 of :rfc:`7235` for details.
  111. credentials: Hard coded authorized credentials. It can be a
  112. ``(username, password)`` pair or a list of such pairs.
  113. check_credentials: Coroutine that verifies credentials.
  114. It receives ``username`` and ``password`` arguments
  115. and returns a :class:`bool`. One of ``credentials`` or
  116. ``check_credentials`` must be provided but not both.
  117. create_protocol: Factory that creates the protocol. By default, this
  118. is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced
  119. by a subclass.
  120. Raises:
  121. TypeError: If the ``credentials`` or ``check_credentials`` argument is
  122. wrong.
  123. """
  124. if (credentials is None) == (check_credentials is None):
  125. raise TypeError("provide either credentials or check_credentials")
  126. if credentials is not None:
  127. if is_credentials(credentials):
  128. credentials_list = [cast(Credentials, credentials)]
  129. elif isinstance(credentials, Iterable):
  130. credentials_list = list(cast(Iterable[Credentials], credentials))
  131. if not all(is_credentials(item) for item in credentials_list):
  132. raise TypeError(f"invalid credentials argument: {credentials}")
  133. else:
  134. raise TypeError(f"invalid credentials argument: {credentials}")
  135. credentials_dict = dict(credentials_list)
  136. async def check_credentials(username: str, password: str) -> bool:
  137. try:
  138. expected_password = credentials_dict[username]
  139. except KeyError:
  140. return False
  141. return hmac.compare_digest(expected_password, password)
  142. if create_protocol is None:
  143. create_protocol = BasicAuthWebSocketServerProtocol
  144. # Help mypy and avoid this error: "type[BasicAuthWebSocketServerProtocol] |
  145. # Callable[..., BasicAuthWebSocketServerProtocol]" not callable [misc]
  146. create_protocol = cast(
  147. Callable[..., BasicAuthWebSocketServerProtocol], create_protocol
  148. )
  149. return functools.partial(
  150. create_protocol,
  151. realm=realm,
  152. check_credentials=check_credentials,
  153. )