aiopytedapi 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.
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.0'
22
+ __version_tuple__ = version_tuple = (0, 1, 0)
23
+
24
+ __commit_id__ = commit_id = None
aiopytedapi/client.py ADDED
@@ -0,0 +1,364 @@
1
+ """The gateway client.
2
+
3
+ :class:`TedapiClient` sends TEDAPI requests over one :class:`Transport`:
4
+
5
+ async with aiohttp.ClientSession() as session:
6
+ key = RsaKey.from_pem(pem_bytes)
7
+ client = TedapiClient.signed(session, "192.168.1.50", key, password="ABCDE")
8
+ await client.connect()
9
+ status = await client.get_network_status()
10
+
11
+ Every method raises a :class:`~aiopytedapi.exceptions.TedapiError` subclass on
12
+ failure; none returns None to mean "it failed". Commands that change settings
13
+ need the signed connection and log a WARNING when they're sent.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import logging
20
+ import re
21
+ from typing import Any, Dict, Optional, Tuple
22
+
23
+ import aiohttp
24
+
25
+ from ._proto import tedapi_pb2 as pb
26
+ from .exceptions import (
27
+ GatewayRejectedError,
28
+ NotSupportedError,
29
+ SignedConnectionRequired,
30
+ UnexpectedResponseError,
31
+ )
32
+ from .keys import KeyInput, RsaKey, fingerprint, public_key_bytes, rsa_public_key_der
33
+ from .models import (
34
+ EXPORT_LIMIT_KEY,
35
+ IMPORT_LIMIT_KEY,
36
+ AuthorizedClient,
37
+ AuthorizedClients,
38
+ CalibrationDelayStatus,
39
+ NetworkStatus,
40
+ Number,
41
+ SiteLimits,
42
+ export_limit_value,
43
+ import_limit_value,
44
+ validate_calibration_delay,
45
+ )
46
+ from .transport import DEFAULT_TIMEOUT, WIFI_HOST, SignedTransport, Transport, WifiTransport
47
+
48
+ _LOGGER = logging.getLogger(__name__)
49
+
50
+ #: The error code a gateway answers for a request its firmware doesn't implement.
51
+ NOT_IMPLEMENTED = 12
52
+ _FINGERPRINT_PREFIX = re.compile(r"[0-9a-fA-F]{8,64}")
53
+
54
+
55
+ class TedapiClient:
56
+ """A TEDAPI client for one gateway, over one transport."""
57
+
58
+ def __init__(self, transport: Transport, *, din: Optional[str] = None) -> None:
59
+ self.transport = transport
60
+ self._din = din
61
+
62
+ @classmethod
63
+ def signed(
64
+ cls,
65
+ session: aiohttp.ClientSession,
66
+ host: str,
67
+ key: RsaKey,
68
+ *,
69
+ password: Optional[str] = None,
70
+ din: Optional[str] = None,
71
+ timeout: float = DEFAULT_TIMEOUT,
72
+ ) -> TedapiClient:
73
+ """A client on the signed connection (``/tedapi/v1r``), on the
74
+ gateway's home-network address or its Wi-Fi address. ``password`` is
75
+ the customer login password, needed for the DIN unless ``din`` is
76
+ given."""
77
+ return cls(SignedTransport(session, host, key, password=password, timeout=timeout), din=din)
78
+
79
+ @classmethod
80
+ def wifi(
81
+ cls,
82
+ session: aiohttp.ClientSession,
83
+ password: str,
84
+ *,
85
+ host: str = WIFI_HOST,
86
+ din: Optional[str] = None,
87
+ timeout: float = DEFAULT_TIMEOUT,
88
+ ) -> TedapiClient:
89
+ """A read-only client on the Gateway Wi-Fi connection (``/tedapi/v1``)
90
+ with the gateway's Wi-Fi password."""
91
+ return cls(WifiTransport(session, password, host=host, timeout=timeout), din=din)
92
+
93
+ # ── Connection ───────────────────────────────────────────────────
94
+
95
+ @property
96
+ def din(self) -> Optional[str]:
97
+ """The gateway's DIN, once known."""
98
+ return self._din
99
+
100
+ @property
101
+ def signed_connection(self) -> bool:
102
+ """True when this client can send commands that change settings."""
103
+ return self.transport.signed
104
+
105
+ async def connect(self) -> str:
106
+ """Fetch the gateway's DIN (needed by every request) and return it."""
107
+ self._din = await self.transport.get_din()
108
+ return self._din
109
+
110
+ async def _send(self, envelope: pb.MessageEnvelope) -> pb.MessageEnvelope:
111
+ din = self._din if self._din is not None else await self.connect()
112
+ envelope.recipient.din = din
113
+ return await self.transport.send(envelope, din)
114
+
115
+ @staticmethod
116
+ def _read_envelope() -> pb.MessageEnvelope:
117
+ """A read request: delivered over local HTTPS from the installer. The
118
+ gateway answers it on both transports."""
119
+ envelope = pb.MessageEnvelope()
120
+ envelope.deliveryChannel = pb.DELIVERY_CHANNEL_LOCAL_HTTPS
121
+ envelope.sender.local = pb.LOCAL_PARTICIPANT_INSTALLER
122
+ return envelope
123
+
124
+ @staticmethod
125
+ def _command_envelope() -> pb.MessageEnvelope:
126
+ """A signed command: delivered as a Hermes command from the customer
127
+ app client the signing key is registered as."""
128
+ envelope = pb.MessageEnvelope()
129
+ envelope.deliveryChannel = pb.DELIVERY_CHANNEL_HERMES_COMMAND
130
+ envelope.sender.authorizedClient = pb.AUTHORIZED_CLIENT_TYPE_CUSTOMER_MOBILE_APP
131
+ return envelope
132
+
133
+ def _require_signed(self, what: str) -> None:
134
+ if not self.transport.signed:
135
+ raise SignedConnectionRequired(f"{what} needs the signed connection")
136
+
137
+ @staticmethod
138
+ def _check_error(envelope: pb.MessageEnvelope, what: str) -> None:
139
+ """Raise for a ``common.error_response`` answer."""
140
+ if envelope.WhichOneof("payload") == "common" and envelope.common.WhichOneof("message") == "error_response":
141
+ status = envelope.common.error_response.status
142
+ if status.code == NOT_IMPLEMENTED:
143
+ raise NotSupportedError(status.code, f"{what} is not supported by this gateway's firmware")
144
+ raise GatewayRejectedError(status.code, status.message)
145
+
146
+ @classmethod
147
+ def _reply(cls, envelope: pb.MessageEnvelope, payload: str, field: str, what: str) -> Any:
148
+ """The ``<payload>.<field>`` answer message, or raise."""
149
+ cls._check_error(envelope, what)
150
+ if envelope.WhichOneof("payload") == payload:
151
+ group = getattr(envelope, payload)
152
+ if group.WhichOneof("message") == field:
153
+ return getattr(group, field)
154
+ raise UnexpectedResponseError(f"{what}: the gateway's answer was not {field}")
155
+
156
+ # ── Configuration (config.json) ──────────────────────────────────
157
+
158
+ async def _read_config(self) -> Tuple[Dict[str, Any], bytes]:
159
+ """config.json and its hash (the write's optimistic lock)."""
160
+ envelope = self._command_envelope() if self.transport.signed else self._read_envelope()
161
+ request = envelope.filestore.readFileRequest
162
+ request.domain = pb.FILE_STORE_API_DOMAIN_CONFIG_JSON
163
+ request.name = "config.json"
164
+ reply = self._reply(await self._send(envelope), "filestore", "readFileResponse", "config read")
165
+ try:
166
+ config = json.loads(reply.file.blob.decode("utf-8"))
167
+ except (UnicodeDecodeError, ValueError) as err:
168
+ raise UnexpectedResponseError("config.json could not be decoded") from err
169
+ if not isinstance(config, dict):
170
+ raise UnexpectedResponseError("config.json is not an object")
171
+ return config, bytes(reply.hash)
172
+
173
+ async def get_config(self) -> Dict[str, Any]:
174
+ """The gateway's configuration (config.json). Read-only. It holds the
175
+ site's settings and identifiers: don't log or publish it."""
176
+ config, _ = await self._read_config()
177
+ return config
178
+
179
+ async def _update_config(self, updates: Dict[str, Any], what: str) -> Dict[str, Any]:
180
+ """Read-modify-write config.json over the signed connection. The
181
+ write carries the hash of the config that was read, so the gateway
182
+ refuses it if the config changed in between. ``updates`` maps dotted
183
+ paths (``site_info.max_site_meter_power_ac``) to values."""
184
+ self._require_signed(what)
185
+ config, config_hash = await self._read_config()
186
+ for path, value in updates.items():
187
+ *parents, leaf = path.split(".")
188
+ node = config
189
+ for key in parents:
190
+ child = node.get(key)
191
+ if not isinstance(child, dict):
192
+ child = node[key] = {}
193
+ node = child
194
+ node[leaf] = value
195
+ envelope = self._command_envelope()
196
+ request = envelope.filestore.updateFileRequest
197
+ request.domain = pb.FILE_STORE_API_DOMAIN_CONFIG_JSON
198
+ request.file.name = "config.json"
199
+ request.file.blob = json.dumps(config).encode("utf-8")
200
+ request.hash = config_hash
201
+ answer = await self._send(envelope)
202
+ self._check_error(answer, what)
203
+ if answer.WhichOneof("payload") != "filestore" or answer.filestore.WhichOneof("message") not in (
204
+ None,
205
+ "updateFileResponse",
206
+ ):
207
+ raise UnexpectedResponseError(f"{what}: the gateway did not acknowledge the config write")
208
+ return config
209
+
210
+ # ── Network status ───────────────────────────────────────────────
211
+
212
+ async def get_network_status(self) -> NetworkStatus:
213
+ """Each network interface's state (Wi-Fi, Ethernet, cellular):
214
+ enabled, active route, link / internet / Tesla connectivity and
215
+ signal strength. Read-only.
216
+
217
+ A Powerwall 3 answers on both connections. A Powerwall 2 answers only
218
+ on the Gateway Wi-Fi connection: over the signed connection it raises
219
+ MessageFaultError (``MESSAGEFAULT_ERROR_TIMEOUT``)."""
220
+ envelope = self._read_envelope()
221
+ envelope.common.get_networking_status_request.SetInParent()
222
+ reply = self._reply(await self._send(envelope), "common", "get_networking_status_response", "network status")
223
+ return NetworkStatus.from_proto(reply)
224
+
225
+ # ── Site import / export limits ──────────────────────────────────
226
+
227
+ async def get_site_limits(self) -> SiteLimits:
228
+ """The site's import and export limits (kW). Read-only."""
229
+ return SiteLimits.from_config(await self.get_config())
230
+
231
+ async def set_import_limit(self, kilowatts: Optional[Number]) -> SiteLimits:
232
+ """Set the most power the site may import from the grid (kW); None
233
+ removes the limit. Signed connection only.
234
+
235
+ An installer may have set this limit to meet the grid connection
236
+ agreement: don't raise or remove it unless you're allowed to."""
237
+ value = import_limit_value(kilowatts)
238
+ self._require_signed("setting the import limit")
239
+ _LOGGER.warning("Setting the site import limit to %s kW", "none" if kilowatts is None else kilowatts)
240
+ config = await self._update_config({f"site_info.{IMPORT_LIMIT_KEY}": value}, "setting the import limit")
241
+ return SiteLimits.from_config(config)
242
+
243
+ async def set_export_limit(self, kilowatts: Optional[Number]) -> SiteLimits:
244
+ """Set the most power the site may export to the grid (kW); None
245
+ removes the limit. Signed connection only.
246
+
247
+ An installer may have set this limit to meet the grid connection
248
+ agreement (a network export limit): don't raise or remove it unless
249
+ you're allowed to."""
250
+ value = export_limit_value(kilowatts)
251
+ self._require_signed("setting the export limit")
252
+ _LOGGER.warning("Setting the site export limit to %s kW", "none" if kilowatts is None else kilowatts)
253
+ config = await self._update_config({f"site_info.{EXPORT_LIMIT_KEY}": value}, "setting the export limit")
254
+ return SiteLimits.from_config(config)
255
+
256
+ # ── Battery calibration delay ────────────────────────────────────
257
+
258
+ async def get_battery_calibration_delay_status(self) -> CalibrationDelayStatus:
259
+ """How many calibration delays are left, and the time left on the
260
+ current one. Read-only; signed connection only.
261
+
262
+ A Powerwall 3 on firmware 26.34.3 raises NotSupportedError."""
263
+ self._require_signed("the calibration delay status")
264
+ envelope = self._command_envelope()
265
+ envelope.teg.get_delay_battery_calibration_status_request.SetInParent()
266
+ reply = self._reply(
267
+ await self._send(envelope),
268
+ "teg",
269
+ "get_delay_battery_calibration_status_response",
270
+ "the calibration delay status",
271
+ )
272
+ return CalibrationDelayStatus.from_proto(reply)
273
+
274
+ async def delay_battery_calibration(self, delay_hours: int) -> None:
275
+ """Postpone the gateway's next battery calibration by ``delay_hours``.
276
+ The gateway allows a limited number of delays, and each accepted
277
+ request may use one. Signed connection only.
278
+
279
+ A calibration can't be started locally: this only postpones one. An
280
+ acknowledgement is not proof the calibration moved."""
281
+ validate_calibration_delay(delay_hours)
282
+ self._require_signed("delaying the battery calibration")
283
+ envelope = self._command_envelope()
284
+ envelope.teg.delay_battery_calibration_request.delay_hours = delay_hours
285
+ _LOGGER.warning("Delaying the battery calibration by %d h", delay_hours)
286
+ self._reply(
287
+ await self._send(envelope), "teg", "delay_battery_calibration_response", "delaying the battery calibration"
288
+ )
289
+
290
+ # ── Authorized clients (registered keys) ─────────────────────────
291
+
292
+ async def get_authorized_clients(self) -> AuthorizedClients:
293
+ """The keys that may send the gateway signed commands (the Tesla app,
294
+ vehicles, clients like this one) and each key's state. Read-only;
295
+ both connections."""
296
+ envelope = self._read_envelope()
297
+ envelope.authorization.list_authorized_clients_request.SetInParent()
298
+ reply = self._reply(
299
+ await self._send(envelope),
300
+ "authorization",
301
+ "list_authorized_clients_response",
302
+ "the authorized clients list",
303
+ )
304
+ return AuthorizedClients.from_proto(reply)
305
+
306
+ @property
307
+ def current_key(self) -> Optional[bytes]:
308
+ """PKCS#1 DER of the key this client signs with (signed connection)."""
309
+ return self.transport.public_key_der
310
+
311
+ async def add_authorized_client(
312
+ self, public_key: KeyInput | RsaKey, description: str = "aiopytedapi"
313
+ ) -> AuthorizedClient:
314
+ """Add an RSA public key as a customer app client. Signed connection
315
+ only (the signing key must be VERIFIED).
316
+
317
+ The new key starts in PENDING_VERIFICATION and times out unless it's
318
+ verified within about 10 minutes. A key added this way is not vouched
319
+ for by the signing key, and keys added locally have not been seen to
320
+ verify: registering a key that verifies still needs Tesla's cloud."""
321
+ key_der = rsa_public_key_der(public_key)
322
+ self._require_signed("adding a key")
323
+ envelope = self._command_envelope()
324
+ request = envelope.authorization.add_authorized_client_request
325
+ request.type = pb.AUTHORIZED_CLIENT_TYPE_CUSTOMER_MOBILE_APP
326
+ request.key_type = pb.AUTHORIZED_KEY_TYPE_RSA
327
+ request.public_key = key_der
328
+ request.description = description
329
+ reply = self._reply(
330
+ await self._send(envelope), "authorization", "add_authorized_client_response", "adding a key"
331
+ )
332
+ client = AuthorizedClient.from_proto(reply.client)
333
+ _LOGGER.warning("Added key %s (%s)", client.fingerprint[:16], client.state)
334
+ return client
335
+
336
+ async def remove_authorized_client(self, public_key: KeyInput | RsaKey, *, allow_current_key: bool = False) -> None:
337
+ """Remove a client's key. It can no longer send signed commands, and
338
+ re-adding it needs registration and verification again. Signed
339
+ connection only.
340
+
341
+ ``public_key`` is the key as listed (DER bytes or the base64
342
+ string), a PEM key, an RsaKey, or a fingerprint prefix of 8 or more
343
+ hex characters that matches exactly one client. Removing the key this
344
+ client signs with would lock it out, so it's refused unless
345
+ ``allow_current_key``."""
346
+ self._require_signed("removing a key")
347
+ key = await self._resolve_key(public_key)
348
+ if key == self.current_key and not allow_current_key:
349
+ raise ValueError("refusing to remove the key this client signs with (pass allow_current_key=True)")
350
+ envelope = self._command_envelope()
351
+ envelope.authorization.remove_authorized_client_request.public_key = key
352
+ self._reply(await self._send(envelope), "authorization", "remove_authorized_client_response", "removing a key")
353
+ _LOGGER.warning("Removed key %s", fingerprint(key)[:16])
354
+
355
+ async def _resolve_key(self, public_key: KeyInput | RsaKey) -> bytes:
356
+ if isinstance(public_key, str) and _FINGERPRINT_PREFIX.fullmatch(public_key.strip()):
357
+ matches = (await self.get_authorized_clients()).find(public_key)
358
+ if len(matches) != 1:
359
+ raise ValueError(f"the fingerprint prefix matches {len(matches)} clients (need exactly 1)")
360
+ return matches[0].public_key
361
+ return public_key_bytes(public_key)
362
+
363
+
364
+ __all__ = ["NOT_IMPLEMENTED", "TedapiClient"]
@@ -0,0 +1,76 @@
1
+ """Exceptions raised by aiopytedapi.
2
+
3
+ Every error the library raises derives from :class:`TedapiError`, so a caller
4
+ can catch that one class. The subclasses say what went wrong closely enough
5
+ for an application to react: retry later, ask the user for a password, or ask
6
+ them to register the key again.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+
12
+ class TedapiError(Exception):
13
+ """Base class for every aiopytedapi error."""
14
+
15
+
16
+ class GatewayConnectionError(TedapiError):
17
+ """The gateway could not be reached, or did not answer in time."""
18
+
19
+
20
+ class GatewayBusyError(TedapiError):
21
+ """The gateway is rate limiting requests (HTTP 429 or 503). Wait before
22
+ sending more: retrying at once makes it worse."""
23
+
24
+
25
+ class GatewayAuthError(TedapiError):
26
+ """The gateway refused the password (HTTP 401 or 403 after a login)."""
27
+
28
+
29
+ class KeyNotAuthorizedError(TedapiError):
30
+ """The gateway does not accept the signing key: it is not registered, was
31
+ removed, or does not match the registered key.
32
+
33
+ ``fingerprint`` is the SHA-256 fingerprint of the key that was used, to
34
+ compare against the gateway's list of authorized clients."""
35
+
36
+ def __init__(self, message: str, fingerprint: str) -> None:
37
+ super().__init__(message)
38
+ self.fingerprint = fingerprint
39
+
40
+
41
+ class KeyPendingVerificationError(KeyNotAuthorizedError):
42
+ """The signing key is registered but not verified yet. Toggle the
43
+ Powerwall's On/Off switch within about 10 minutes of registering it."""
44
+
45
+
46
+ class MessageFaultError(TedapiError):
47
+ """The gateway answered a signed request with a message fault, for
48
+ example ``MESSAGEFAULT_ERROR_TIMEOUT`` (a Powerwall 2 answers some
49
+ requests only over the Gateway Wi-Fi)."""
50
+
51
+ def __init__(self, fault: str) -> None:
52
+ super().__init__(f"gateway message fault: {fault}")
53
+ self.fault = fault
54
+
55
+
56
+ class GatewayRejectedError(TedapiError):
57
+ """The gateway answered with an error status instead of a result."""
58
+
59
+ def __init__(self, code: int, message: str) -> None:
60
+ super().__init__(f"gateway returned error {code}: {message}" if message else f"gateway returned error {code}")
61
+ self.code = code
62
+ self.message = message
63
+
64
+
65
+ class NotSupportedError(GatewayRejectedError):
66
+ """The gateway firmware does not implement the request (error code 12)."""
67
+
68
+
69
+ class SignedConnectionRequired(TedapiError):
70
+ """The command needs the signed (RSA key) connection; the Wi-Fi password
71
+ connection can't send it."""
72
+
73
+
74
+ class UnexpectedResponseError(TedapiError):
75
+ """The gateway's answer could not be decoded, or was not the answer to the
76
+ request that was sent."""
aiopytedapi/keys.py ADDED
@@ -0,0 +1,142 @@
1
+ """RSA keys: the signing key a client uses, and public keys as the gateway
2
+ lists them.
3
+
4
+ Keys are DER encoded on the wire; RSA public keys are PKCS#1, the encoding the
5
+ gateway registers and lists back. A key's fingerprint is the SHA-256 of that
6
+ DER, the same fingerprint pypowerwall prints for a key.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import binascii
13
+ import hashlib
14
+ from typing import Union
15
+
16
+ from cryptography.hazmat.primitives import hashes, serialization
17
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
18
+ from cryptography.hazmat.primitives.asymmetric.types import PublicKeyTypes
19
+
20
+ KeyInput = Union[bytes, bytearray, str]
21
+
22
+
23
+ def fingerprint(public_key_der: bytes) -> str:
24
+ """SHA-256 hex fingerprint of DER public key bytes."""
25
+ return hashlib.sha256(bytes(public_key_der)).hexdigest()
26
+
27
+
28
+ class RsaKey:
29
+ """The RSA private key a signed connection signs its requests with.
30
+
31
+ Load it with :meth:`from_pem` (reading the file is the caller's job, so
32
+ no blocking I/O happens inside the event loop). The key itself is never
33
+ logged or returned; ``repr`` shows only its fingerprint.
34
+ """
35
+
36
+ def __init__(self, private_key: rsa.RSAPrivateKey) -> None:
37
+ self._private_key = private_key
38
+ self.public_key_der: bytes = private_key.public_key().public_bytes(
39
+ serialization.Encoding.DER, serialization.PublicFormat.PKCS1
40
+ )
41
+ self.fingerprint: str = fingerprint(self.public_key_der)
42
+
43
+ @classmethod
44
+ def from_pem(cls, pem: bytes, password: bytes | None = None) -> RsaKey:
45
+ """Load a PEM private key. Raises ValueError if it is not an RSA key."""
46
+ try:
47
+ key = serialization.load_pem_private_key(pem, password=password)
48
+ except (TypeError, ValueError) as err:
49
+ raise ValueError("the key could not be read as a PEM private key") from err
50
+ if not isinstance(key, rsa.RSAPrivateKey):
51
+ raise ValueError("the signed connection needs an RSA key")
52
+ return cls(key)
53
+
54
+ @classmethod
55
+ def generate(cls, key_size: int = 4096) -> RsaKey:
56
+ """A new key pair (RSA-4096, as the gateway expects). CPU heavy: run it
57
+ in an executor from async code."""
58
+ return cls(rsa.generate_private_key(public_exponent=65537, key_size=key_size))
59
+
60
+ def private_pem(self) -> bytes:
61
+ """The private key as unencrypted PKCS#8 PEM, to store it. Write it
62
+ with owner-only permissions."""
63
+ return self._private_key.private_bytes(
64
+ serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()
65
+ )
66
+
67
+ def sign(self, data: bytes) -> bytes:
68
+ """RSA PKCS#1 v1.5 signature with SHA-512, as the gateway verifies."""
69
+ return self._private_key.sign(data, padding.PKCS1v15(), hashes.SHA512())
70
+
71
+ def __repr__(self) -> str:
72
+ return f"RsaKey(fingerprint={self.fingerprint[:16]}...)"
73
+
74
+
75
+ def _as_bytes(key: KeyInput) -> bytes:
76
+ if isinstance(key, (bytes, bytearray)):
77
+ return bytes(key)
78
+ if isinstance(key, str):
79
+ try:
80
+ return key.strip().encode("ascii")
81
+ except UnicodeEncodeError as err:
82
+ raise ValueError("public key is not PEM, DER or base64") from err
83
+ raise ValueError("public key must be bytes or str")
84
+
85
+
86
+ def _is_pem(data: bytes) -> bool:
87
+ return data.lstrip().startswith(b"-----BEGIN ")
88
+
89
+
90
+ def _b64decode(data: bytes) -> bytes:
91
+ try:
92
+ return base64.b64decode(data, validate=True)
93
+ except (binascii.Error, ValueError) as err:
94
+ raise ValueError("public key is not PEM, DER or base64") from err
95
+
96
+
97
+ def _load_public_key(data: bytes) -> PublicKeyTypes:
98
+ if _is_pem(data):
99
+ if b"PRIVATE KEY-----" in data:
100
+ return serialization.load_pem_private_key(data, password=None).public_key()
101
+ return serialization.load_pem_public_key(data)
102
+ return serialization.load_der_public_key(data)
103
+
104
+
105
+ def rsa_public_key_der(key: KeyInput | RsaKey) -> bytes:
106
+ """PKCS#1 DER of an RSA public key, the encoding the gateway registers.
107
+
108
+ ``key`` may be an :class:`RsaKey`, a PEM public key, a PEM private key
109
+ (only its public half is used; nothing is kept), DER bytes (PKCS#1 or
110
+ SubjectPublicKeyInfo), or a base64 string of the DER. Raises ValueError for
111
+ anything else, including keys that are not RSA."""
112
+ if isinstance(key, RsaKey):
113
+ return key.public_key_der
114
+ data = _as_bytes(key)
115
+ if not data:
116
+ raise ValueError("public key is empty")
117
+ if not _is_pem(data) and isinstance(key, str):
118
+ data = _b64decode(data)
119
+ try:
120
+ public_key = _load_public_key(data)
121
+ except (TypeError, ValueError) as err:
122
+ raise ValueError("public key could not be read (expected an RSA key as PEM, DER or base64)") from err
123
+ if not isinstance(public_key, rsa.RSAPublicKey):
124
+ raise ValueError("only RSA keys can be added")
125
+ return public_key.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1)
126
+
127
+
128
+ def public_key_bytes(key: KeyInput | RsaKey) -> bytes:
129
+ """The key bytes that identify an existing client: DER bytes as given, a
130
+ base64 string exactly as listed, a PEM key (an RSA key is converted to the
131
+ PKCS#1 DER the gateway lists) or an :class:`RsaKey`. Raises ValueError for
132
+ empty or undecodable input."""
133
+ if isinstance(key, RsaKey):
134
+ return key.public_key_der
135
+ data = _as_bytes(key)
136
+ if not data:
137
+ raise ValueError("public key is empty")
138
+ if _is_pem(data):
139
+ return rsa_public_key_der(data)
140
+ if isinstance(key, str):
141
+ return _b64decode(data)
142
+ return data