libvirtpy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. libvirtpy/__init__.py +5 -0
  2. libvirtpy/client/__init__.py +54 -0
  3. libvirtpy/client/_bases.py +326 -0
  4. libvirtpy/client/_runner.py +57 -0
  5. libvirtpy/client/aio.py +5922 -0
  6. libvirtpy/client/client.py +5695 -0
  7. libvirtpy/client/operations/__init__.py +631 -0
  8. libvirtpy/client/operations/_common.py +495 -0
  9. libvirtpy/client/operations/checkpoint.py +196 -0
  10. libvirtpy/client/operations/connection.py +93 -0
  11. libvirtpy/client/operations/connection_extra.py +256 -0
  12. libvirtpy/client/operations/domain.py +306 -0
  13. libvirtpy/client/operations/domain_agent.py +115 -0
  14. libvirtpy/client/operations/domain_block.py +368 -0
  15. libvirtpy/client/operations/domain_info.py +400 -0
  16. libvirtpy/client/operations/domain_lifecycle.py +338 -0
  17. libvirtpy/client/operations/domain_migration.py +164 -0
  18. libvirtpy/client/operations/domain_network.py +113 -0
  19. libvirtpy/client/operations/domain_tuning.py +494 -0
  20. libvirtpy/client/operations/host.py +246 -0
  21. libvirtpy/client/operations/host_interface.py +100 -0
  22. libvirtpy/client/operations/interface_extra.py +45 -0
  23. libvirtpy/client/operations/network.py +135 -0
  24. libvirtpy/client/operations/network_info.py +155 -0
  25. libvirtpy/client/operations/network_port.py +142 -0
  26. libvirtpy/client/operations/node_device.py +76 -0
  27. libvirtpy/client/operations/node_device_info.py +189 -0
  28. libvirtpy/client/operations/nwfilter.py +67 -0
  29. libvirtpy/client/operations/nwfilter_binding.py +74 -0
  30. libvirtpy/client/operations/secret.py +93 -0
  31. libvirtpy/client/operations/secret_extra.py +24 -0
  32. libvirtpy/client/operations/snapshot.py +100 -0
  33. libvirtpy/client/operations/snapshot_tree.py +114 -0
  34. libvirtpy/client/operations/storage.py +267 -0
  35. libvirtpy/client/operations/storage_info.py +188 -0
  36. libvirtpy/client/operations/streams.py +201 -0
  37. libvirtpy/client/references.py +249 -0
  38. libvirtpy/client/subscribing.py +88 -0
  39. libvirtpy/client/testing/__init__.py +24 -0
  40. libvirtpy/client/testing/_common.py +167 -0
  41. libvirtpy/client/testing/_domains.py +294 -0
  42. libvirtpy/client/testing/_objects.py +205 -0
  43. libvirtpy/client/testing/_state.py +246 -0
  44. libvirtpy/client/testing/_storage.py +171 -0
  45. libvirtpy/client/testing/async_transport.py +30 -0
  46. libvirtpy/client/testing/fake.py +81 -0
  47. libvirtpy/client/transport.py +87 -0
  48. libvirtpy/client/types.py +59 -0
  49. libvirtpy/client/wire.py +436 -0
  50. libvirtpy/client/wire_aio.py +348 -0
  51. libvirtpy/errors.py +7 -0
  52. libvirtpy/py.typed +0 -0
  53. libvirtpy/rpc/__init__.py +1 -0
  54. libvirtpy/rpc/aio.py +387 -0
  55. libvirtpy/rpc/cpumap.py +48 -0
  56. libvirtpy/rpc/errors.py +186 -0
  57. libvirtpy/rpc/events.py +259 -0
  58. libvirtpy/rpc/options.py +66 -0
  59. libvirtpy/rpc/procedure.py +27 -0
  60. libvirtpy/rpc/protocol/__init__.py +0 -0
  61. libvirtpy/rpc/protocol/procedures.py +5163 -0
  62. libvirtpy/rpc/protocol/typed_hints.py +210 -0
  63. libvirtpy/rpc/protocol/types.py +9299 -0
  64. libvirtpy/rpc/remote.py +295 -0
  65. libvirtpy/rpc/remote_aio.py +106 -0
  66. libvirtpy/rpc/sasl.py +467 -0
  67. libvirtpy/rpc/session.py +424 -0
  68. libvirtpy/rpc/sockets.py +251 -0
  69. libvirtpy/rpc/stream.py +323 -0
  70. libvirtpy/rpc/subscription.py +451 -0
  71. libvirtpy/rpc/sync.py +460 -0
  72. libvirtpy/rpc/typed_params.py +97 -0
  73. libvirtpy/rpc/uri.py +85 -0
  74. libvirtpy/rpc/xdr.py +552 -0
  75. libvirtpy/xml/__init__.py +49 -0
  76. libvirtpy/xml/_base.py +145 -0
  77. libvirtpy/xml/_shared/__init__.py +1 -0
  78. libvirtpy/xml/_shared/metadata.py +67 -0
  79. libvirtpy/xml/_shared/network.py +108 -0
  80. libvirtpy/xml/_shared/storage.py +131 -0
  81. libvirtpy/xml/_shared/sysinfo.py +83 -0
  82. libvirtpy/xml/_types.py +197 -0
  83. libvirtpy/xml/_xml_element.py +134 -0
  84. libvirtpy/xml/backup/__init__.py +25 -0
  85. libvirtpy/xml/backup/backup.py +89 -0
  86. libvirtpy/xml/backup/checkpoint.py +48 -0
  87. libvirtpy/xml/capabilities/__init__.py +43 -0
  88. libvirtpy/xml/capabilities/domain.py +436 -0
  89. libvirtpy/xml/capabilities/host.py +413 -0
  90. libvirtpy/xml/capabilities/storagepool.py +59 -0
  91. libvirtpy/xml/domain/__init__.py +493 -0
  92. libvirtpy/xml/domain/blkiotune.py +81 -0
  93. libvirtpy/xml/domain/clock.py +79 -0
  94. libvirtpy/xml/domain/cpu.py +265 -0
  95. libvirtpy/xml/domain/devices/__init__.py +495 -0
  96. libvirtpy/xml/domain/devices/address.py +152 -0
  97. libvirtpy/xml/domain/devices/audio.py +204 -0
  98. libvirtpy/xml/domain/devices/chardev.py +197 -0
  99. libvirtpy/xml/domain/devices/common.py +75 -0
  100. libvirtpy/xml/domain/devices/controller.py +262 -0
  101. libvirtpy/xml/domain/devices/devices.py +79 -0
  102. libvirtpy/xml/domain/devices/disk.py +471 -0
  103. libvirtpy/xml/domain/devices/filesystem.py +206 -0
  104. libvirtpy/xml/domain/devices/graphics.py +245 -0
  105. libvirtpy/xml/domain/devices/hostdev.py +221 -0
  106. libvirtpy/xml/domain/devices/input.py +89 -0
  107. libvirtpy/xml/domain/devices/interface.py +459 -0
  108. libvirtpy/xml/domain/devices/iommu.py +54 -0
  109. libvirtpy/xml/domain/devices/memballoon.py +42 -0
  110. libvirtpy/xml/domain/devices/memory_device.py +101 -0
  111. libvirtpy/xml/domain/devices/misc.py +169 -0
  112. libvirtpy/xml/domain/devices/nvram.py +20 -0
  113. libvirtpy/xml/domain/devices/shmem.py +46 -0
  114. libvirtpy/xml/domain/devices/sound.py +42 -0
  115. libvirtpy/xml/domain/devices/tpm.py +103 -0
  116. libvirtpy/xml/domain/devices/usb.py +86 -0
  117. libvirtpy/xml/domain/devices/video.py +101 -0
  118. libvirtpy/xml/domain/domain.py +157 -0
  119. libvirtpy/xml/domain/features.py +312 -0
  120. libvirtpy/xml/domain/iothread.py +41 -0
  121. libvirtpy/xml/domain/launch_security.py +82 -0
  122. libvirtpy/xml/domain/memory.py +149 -0
  123. libvirtpy/xml/domain/misc.py +113 -0
  124. libvirtpy/xml/domain/namespaces.py +96 -0
  125. libvirtpy/xml/domain/numa.py +140 -0
  126. libvirtpy/xml/domain/os.py +267 -0
  127. libvirtpy/xml/domain/qemu.py +102 -0
  128. libvirtpy/xml/domain/seclabel.py +29 -0
  129. libvirtpy/xml/domain/storage_source.py +466 -0
  130. libvirtpy/xml/domain/sysinfo.py +34 -0
  131. libvirtpy/xml/interface/__init__.py +17 -0
  132. libvirtpy/xml/interface/interface.py +153 -0
  133. libvirtpy/xml/network/__init__.py +101 -0
  134. libvirtpy/xml/network/network.py +311 -0
  135. libvirtpy/xml/network/port.py +84 -0
  136. libvirtpy/xml/nodedev/__init__.py +13 -0
  137. libvirtpy/xml/nodedev/nodedev.py +490 -0
  138. libvirtpy/xml/nwfilter/__init__.py +81 -0
  139. libvirtpy/xml/nwfilter/binding.py +51 -0
  140. libvirtpy/xml/nwfilter/filter.py +92 -0
  141. libvirtpy/xml/nwfilter/rules.py +534 -0
  142. libvirtpy/xml/secret/__init__.py +11 -0
  143. libvirtpy/xml/secret/secret.py +36 -0
  144. libvirtpy/xml/snapshot/__init__.py +29 -0
  145. libvirtpy/xml/snapshot/snapshot.py +136 -0
  146. libvirtpy/xml/storage/__init__.py +75 -0
  147. libvirtpy/xml/storage/pool.py +219 -0
  148. libvirtpy/xml/storage/volume.py +102 -0
  149. libvirtpy/xml/sysinfo.py +40 -0
  150. libvirtpy-0.1.0.dist-info/METADATA +109 -0
  151. libvirtpy-0.1.0.dist-info/RECORD +154 -0
  152. libvirtpy-0.1.0.dist-info/WHEEL +4 -0
  153. libvirtpy-0.1.0.dist-info/licenses/LICENSE +501 -0
  154. libvirtpy-0.1.0.dist-info/licenses/NOTICE +23 -0
libvirtpy/rpc/sasl.py ADDED
@@ -0,0 +1,467 @@
1
+ """SASL authentication for libvirt daemons (pure Python, standard library only).
2
+
3
+ Supported mechanisms, best first: SCRAM-SHA-256, SCRAM-SHA-1, DIGEST-MD5 (what
4
+ libvirt's default configuration uses) and PLAIN. None of them needs a SASL
5
+ *security layer*, so SASL is allowed only on a channel that is already
6
+ protected: a UNIX socket, TLS or SSH. GSSAPI (Kerberos) is not supported.
7
+
8
+ ``sasl_exchange`` is a generator that yields the calls to make and receives
9
+ their replies, so the sync and the async client drive the same code.
10
+ """
11
+
12
+ import base64
13
+ import hashlib
14
+ import hmac
15
+ import re
16
+ import secrets
17
+ import unicodedata
18
+ from collections.abc import Generator
19
+ from dataclasses import dataclass
20
+ from typing import Any, Protocol
21
+
22
+ from libvirtpy.rpc.errors import AuthFailedError, ErrorNumber
23
+ from libvirtpy.rpc.procedure import Procedure
24
+ from libvirtpy.rpc.protocol import procedures, types
25
+
26
+ __all__ = [
27
+ "DigestMd5",
28
+ "PlainMechanism",
29
+ "SaslCredentials",
30
+ "SaslMechanism",
31
+ "Scram",
32
+ "choose_mechanism",
33
+ "parse_mechanisms",
34
+ "sasl_exchange",
35
+ ]
36
+
37
+ SERVICE = "libvirt"
38
+ CHAR_LIMIT = 128
39
+ MAX_ITERATIONS = 1_000_000
40
+ SaslCall = tuple[Procedure[Any, Any], Any]
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class SaslCredentials:
45
+ """The user name and password to authenticate with."""
46
+
47
+ username: str
48
+ password: str
49
+ realm: str | None = None
50
+ """The realm to use if the server does not name one (DIGEST-MD5)."""
51
+
52
+
53
+ class SaslMechanism(Protocol):
54
+ """One authentication mechanism, as a client."""
55
+
56
+ name: str
57
+
58
+ @property
59
+ def finished(self) -> bool:
60
+ """Whether the server has proved itself and nothing more is expected."""
61
+
62
+ def start(self) -> bytes | None:
63
+ """Make the first message.
64
+
65
+ :returns: the initial response, or ``None`` if the server speaks first.
66
+ """
67
+
68
+ def step(self, challenge: bytes) -> bytes | None:
69
+ """Answer a message of the server.
70
+
71
+ :param challenge: the server's data.
72
+ :returns: the response, or ``None`` for no data.
73
+ :raises AuthFailedError: if the server's data is wrong.
74
+ """
75
+
76
+
77
+ class PlainMechanism:
78
+ """PLAIN (RFC 4616): user name and password in the clear."""
79
+
80
+ name = "PLAIN"
81
+
82
+ def __init__(self, credentials: SaslCredentials) -> None:
83
+ """Create the mechanism.
84
+
85
+ :param credentials: who to authenticate as.
86
+ """
87
+ self._credentials = credentials
88
+
89
+ @property
90
+ def finished(self) -> bool:
91
+ """PLAIN has nothing to verify, so it is always finished."""
92
+ return True
93
+
94
+ def start(self) -> bytes | None:
95
+ """Make the initial response.
96
+
97
+ :returns: ``authzid NUL user NUL password`` with an empty authzid.
98
+ """
99
+ user = self._credentials.username.encode()
100
+ password = self._credentials.password.encode()
101
+ return b"\0" + user + b"\0" + password
102
+
103
+ def step(self, challenge: bytes) -> bytes | None:
104
+ """Refuse any server message: PLAIN has none.
105
+
106
+ :param challenge: the server's data.
107
+ :returns: nothing.
108
+ :raises AuthFailedError: always.
109
+ """
110
+ raise _failure("the server sent data during PLAIN")
111
+
112
+
113
+ class Scram:
114
+ """SCRAM-SHA-1 and SCRAM-SHA-256 (RFC 5802, RFC 7677), without channel binding."""
115
+
116
+ def __init__(
117
+ self, credentials: SaslCredentials, algorithm: str, nonce: str | None = None
118
+ ) -> None:
119
+ """Create the mechanism.
120
+
121
+ :param credentials: who to authenticate as.
122
+ :param algorithm: ``sha1`` or ``sha256``.
123
+ :param nonce: our random string; made up if left out (tests fix it).
124
+ """
125
+ self.name = f"SCRAM-{algorithm.upper().replace('SHA', 'SHA-')}"
126
+ self._credentials = credentials
127
+ self._algorithm = algorithm
128
+ self._nonce = nonce or secrets.token_urlsafe(18)
129
+
130
+ self._bare = ""
131
+ self._server_first = ""
132
+ self._expected_signature = b""
133
+ self._stage = 0
134
+
135
+ @property
136
+ def finished(self) -> bool:
137
+ """Whether the server's signature was checked."""
138
+ return self._stage == 2
139
+
140
+ def start(self) -> bytes | None:
141
+ """Make the client-first message.
142
+
143
+ :returns: the message with the gs2 header ``n,,``.
144
+ """
145
+ user = _prepare(self._credentials.username)
146
+ user = user.replace("=", "=3D").replace(",", "=2C")
147
+ self._bare = f"n={user},r={self._nonce}"
148
+ return f"n,,{self._bare}".encode()
149
+
150
+ def step(self, challenge: bytes) -> bytes | None:
151
+ """Answer the server-first message, or check the server-final one.
152
+
153
+ :param challenge: the server's data.
154
+ :returns: the client-final message, or nothing after the last check.
155
+ :raises AuthFailedError: if the server's data is wrong.
156
+ """
157
+ if self._stage == 0:
158
+ self._stage = 1
159
+ return self._client_final(_text(challenge))
160
+
161
+ self._verify(_text(challenge))
162
+ self._stage = 2
163
+ return None
164
+
165
+ def _client_final(self, server_first: str) -> bytes:
166
+ """Compute the client-final message with its proof.
167
+
168
+ :param server_first: the server's first message.
169
+ :returns: the client-final message.
170
+ :raises AuthFailedError: if the server's nonce or parameters are wrong.
171
+ """
172
+ fields = {
173
+ key: value
174
+ for key, _, value in (
175
+ part.partition("=") for part in server_first.split(",")
176
+ )
177
+ }
178
+ nonce = fields.get("r", "")
179
+ if not nonce.startswith(self._nonce) or "s" not in fields or "i" not in fields:
180
+ raise _failure("the SCRAM server-first message is not valid")
181
+
182
+ salt = _base64(fields["s"])
183
+ iterations = _iterations(fields["i"])
184
+
185
+ password = _prepare(self._credentials.password).encode()
186
+ salted = hashlib.pbkdf2_hmac(self._algorithm, password, salt, iterations)
187
+ client_key = self._hmac(salted, b"Client Key")
188
+ without_proof = f"c=biws,r={nonce}"
189
+
190
+ message = f"{self._bare},{server_first},{without_proof}".encode()
191
+
192
+ stored_key = hashlib.new(self._algorithm, client_key).digest()
193
+ signature = self._hmac(stored_key, message)
194
+ proof = bytes(a ^ b for a, b in zip(client_key, signature, strict=True))
195
+ self._expected_signature = self._hmac(
196
+ self._hmac(salted, b"Server Key"), message
197
+ )
198
+ return f"{without_proof},p={base64.b64encode(proof).decode()}".encode()
199
+
200
+ def _verify(self, server_final: str) -> None:
201
+ """Check the server's signature.
202
+
203
+ :param server_final: the server's last message (``v=...``).
204
+ :raises AuthFailedError: if the server reports an error or its proof is wrong.
205
+ """
206
+ if server_final.startswith("e="):
207
+ raise _failure(f"the server refused the credentials: {server_final[2:]}")
208
+
209
+ proof = _base64(server_final.removeprefix("v="))
210
+ if not hmac.compare_digest(proof, self._expected_signature):
211
+ raise _failure("the server could not prove it knows the password")
212
+
213
+ def _hmac(self, key: bytes, message: bytes) -> bytes:
214
+ """Compute an HMAC with the mechanism's hash.
215
+
216
+ :param key: the key.
217
+ :param message: the data.
218
+ :returns: the digest.
219
+ """
220
+ return hmac.new(key, message, self._algorithm).digest()
221
+
222
+
223
+ class DigestMd5:
224
+ """DIGEST-MD5 (RFC 2831), authentication only (``qop=auth``)."""
225
+
226
+ name = "DIGEST-MD5"
227
+
228
+ def __init__(
229
+ self,
230
+ credentials: SaslCredentials,
231
+ host: str,
232
+ cnonce: str | None = None,
233
+ service: str = SERVICE,
234
+ ) -> None:
235
+ """Create the mechanism.
236
+
237
+ :param credentials: who to authenticate as.
238
+ :param host: the server's host name, for the ``digest-uri``.
239
+ :param cnonce: our random string; made up if left out (tests fix it).
240
+ :param service: the service name in the ``digest-uri``; libvirt's is
241
+ ``libvirt``.
242
+ """
243
+ self._credentials = credentials
244
+ self._digest_uri = f"{service}/{host}"
245
+ self._cnonce = cnonce or secrets.token_hex(16)
246
+ self._expected_rspauth = ""
247
+ self._stage = 0
248
+
249
+ @property
250
+ def finished(self) -> bool:
251
+ """Whether the server's ``rspauth`` was checked."""
252
+ return self._stage == 2
253
+
254
+ def start(self) -> bytes | None:
255
+ """DIGEST-MD5 has no initial response: the server speaks first.
256
+
257
+ :returns: nothing.
258
+ """
259
+ return None
260
+
261
+ def step(self, challenge: bytes) -> bytes | None:
262
+ """Answer the server's challenge, or check its ``rspauth``.
263
+
264
+ :param challenge: the server's data.
265
+ :returns: the response; empty after the last check.
266
+ :raises AuthFailedError: if the server's data is wrong.
267
+ """
268
+ if self._stage == 0:
269
+ self._stage = 1
270
+ return self._respond(_directives(_text(challenge)))
271
+
272
+ rspauth = _directives(_text(challenge)).get("rspauth")
273
+ if rspauth != self._expected_rspauth:
274
+ raise _failure("the server could not prove it knows the password")
275
+ self._stage = 2
276
+ return b""
277
+
278
+ def _respond(self, challenge: dict[str, str]) -> bytes:
279
+ """Compute the response to the server's challenge.
280
+
281
+ :param challenge: its directives (``realm``, ``nonce``, ``qop``, ...).
282
+ :returns: the response directives.
283
+ :raises AuthFailedError: if the server offers no ``auth`` quality of protection.
284
+ """
285
+ if "auth" not in challenge.get("qop", "auth").split(","):
286
+ raise _failure("the server demands a SASL security layer, not supported")
287
+
288
+ realm = challenge.get("realm", self._credentials.realm or "")
289
+ nonce = challenge.get("nonce")
290
+ if nonce is None:
291
+ raise _failure("the DIGEST-MD5 challenge has no nonce")
292
+ user = self._credentials.username
293
+
294
+ secret = hashlib.md5(
295
+ f"{user}:{realm}:{self._credentials.password}".encode()
296
+ ).digest()
297
+ key = hashlib.md5(secret + f":{nonce}:{self._cnonce}".encode()).hexdigest()
298
+
299
+ response = self._digest(key, nonce, "AUTHENTICATE")
300
+ self._expected_rspauth = self._digest(key, nonce, "")
301
+
302
+ return (
303
+ f'username="{user}",realm="{realm}",nonce="{nonce}",'
304
+ f'cnonce="{self._cnonce}",nc=00000001,qop=auth,'
305
+ f'digest-uri="{self._digest_uri}",response={response},charset=utf-8'
306
+ ).encode()
307
+
308
+ def _digest(self, key: str, nonce: str, method: str) -> str:
309
+ """Compute the ``response`` (or ``rspauth``, with an empty method) value.
310
+
311
+ :param key: the hex MD5 of ``A1``.
312
+ :param nonce: the server's nonce.
313
+ :param method: ``AUTHENTICATE`` for the response, empty for ``rspauth``.
314
+ :returns: the 32 hex digits.
315
+ """
316
+ a2 = hashlib.md5(f"{method}:{self._digest_uri}".encode()).hexdigest()
317
+ data = f"{key}:{nonce}:00000001:{self._cnonce}:auth:{a2}"
318
+ return hashlib.md5(data.encode()).hexdigest()
319
+
320
+
321
+ def choose_mechanism(
322
+ offered: list[str], credentials: SaslCredentials, host: str
323
+ ) -> SaslMechanism:
324
+ """Pick the best mechanism both sides support.
325
+
326
+ :param offered: the mechanisms the server lists.
327
+ :param credentials: who to authenticate as.
328
+ :param host: the server's host name.
329
+ :returns: the mechanism.
330
+ :raises AuthFailedError: if the server offers none of ours.
331
+ """
332
+ candidates: list[tuple[str, SaslMechanism]] = [
333
+ ("SCRAM-SHA-256", Scram(credentials, "sha256")),
334
+ ("SCRAM-SHA-1", Scram(credentials, "sha1")),
335
+ ("DIGEST-MD5", DigestMd5(credentials, host)),
336
+ ("PLAIN", PlainMechanism(credentials)),
337
+ ]
338
+ for name, mechanism in candidates:
339
+ if name in offered:
340
+ return mechanism
341
+ raise _failure(f"no common SASL mechanism: the server offers {offered}")
342
+
343
+
344
+ def parse_mechanisms(offered: str) -> list[str]:
345
+ """Split the mechanism list that a daemon sends.
346
+
347
+ libvirt separates the names with commas (``SCRAM-SHA-256,DIGEST-MD5``); SASL
348
+ itself uses spaces, so both are accepted.
349
+
350
+ :param offered: the daemon's ``mechlist`` string.
351
+ :returns: the mechanism names, in the order the daemon gave them.
352
+ """
353
+ return [name for name in re.split(r"[,\s]+", offered) if name]
354
+
355
+
356
+ def sasl_exchange(credentials: SaslCredentials, host: str) -> Generator[SaslCall, Any]:
357
+ """Run the SASL conversation with a daemon.
358
+
359
+ :param credentials: who to authenticate as.
360
+ :param host: the server's host name.
361
+ :returns: a generator that yields ``(procedure, arguments)`` and receives the
362
+ reply of each call.
363
+ :raises AuthFailedError: if the mechanisms do not match or the server's proof fails.
364
+ """
365
+ init = yield procedures.AUTH_SASL_INIT, None
366
+ mechanism = choose_mechanism(parse_mechanisms(init.mechlist), credentials, host)
367
+
368
+ first = mechanism.start()
369
+ start = types.AuthSaslStartArgs(
370
+ mech=mechanism.name, nil=int(first is None), data=_to_chars(first)
371
+ )
372
+ reply = yield procedures.AUTH_SASL_START, start
373
+
374
+ while not reply.complete:
375
+ answer = mechanism.step(_from_chars(reply.data))
376
+ step = types.AuthSaslStepArgs(nil=int(answer is None), data=_to_chars(answer))
377
+ reply = yield procedures.AUTH_SASL_STEP, step
378
+
379
+ final = _from_chars(reply.data)
380
+ if final and not mechanism.finished:
381
+ mechanism.step(final)
382
+
383
+
384
+ def _to_chars(data: bytes | None) -> list[int]:
385
+ """Make the wire form of data: an array of signed ``char``.
386
+
387
+ :param data: bytes, or ``None``.
388
+ :returns: one signed integer per byte.
389
+ """
390
+ return [byte - 256 if byte >= CHAR_LIMIT else byte for byte in data or b""]
391
+
392
+
393
+ def _from_chars(chars: list[int]) -> bytes:
394
+ """Make bytes from the wire form (an array of signed ``char``).
395
+
396
+ :param chars: the integers.
397
+ :returns: the bytes.
398
+ """
399
+ return bytes(char & 0xFF for char in chars)
400
+
401
+
402
+ def _text(data: bytes) -> str:
403
+ """Read a server message as text.
404
+
405
+ :param data: the bytes the server sent.
406
+ :returns: the text.
407
+ :raises AuthFailedError: if it is not UTF-8.
408
+ """
409
+ try:
410
+ return data.decode()
411
+ except UnicodeDecodeError as error:
412
+ raise _failure("the server's SASL message is not text") from error
413
+
414
+
415
+ def _base64(text: str) -> bytes:
416
+ """Decode base64 sent by the server.
417
+
418
+ :param text: the base64 text.
419
+ :returns: the bytes.
420
+ :raises AuthFailedError: if it is not valid base64.
421
+ """
422
+ try:
423
+ return base64.b64decode(text, validate=True)
424
+ except ValueError as error:
425
+ raise _failure("the server's SASL message has invalid base64") from error
426
+
427
+
428
+ def _iterations(text: str) -> int:
429
+ """Read the SCRAM iteration count, refusing values that would freeze us.
430
+
431
+ :param text: the ``i=`` value.
432
+ :returns: the count.
433
+ :raises AuthFailedError: if it is not a number from 1 to ``MAX_ITERATIONS``.
434
+ """
435
+ if not text.isdigit() or not 1 <= int(text) <= MAX_ITERATIONS:
436
+ raise _failure(f"the SCRAM iteration count {text[:12]!r} is not acceptable")
437
+ return int(text)
438
+
439
+
440
+ def _directives(text: str) -> dict[str, str]:
441
+ """Parse ``key=value,key="quoted value"`` directives.
442
+
443
+ :param text: the server's challenge.
444
+ :returns: the directives; the first of a repeated key wins.
445
+ """
446
+ found: dict[str, str] = {}
447
+ for key, quoted, plain in re.findall(r'([\w-]+)=(?:"([^"]*)"|([^,]*))', text):
448
+ found.setdefault(key, quoted or plain)
449
+ return found
450
+
451
+
452
+ def _prepare(text: str) -> str:
453
+ """Normalise a user name or password (an approximation of SASLprep).
454
+
455
+ :param text: the text.
456
+ :returns: the text in Unicode normal form KC.
457
+ """
458
+ return unicodedata.normalize("NFKC", text)
459
+
460
+
461
+ def _failure(message: str) -> AuthFailedError:
462
+ """Make the error for a failed authentication.
463
+
464
+ :param message: what went wrong.
465
+ :returns: the exception.
466
+ """
467
+ return AuthFailedError(message, code=ErrorNumber.AUTH_FAILED)