Debian Codegraph @

src/websockets/legacy/auth.py

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