aioratio 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.
aioratio/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """aioratio — async Python client for the Ratio EV Charging cloud API."""
2
+ from __future__ import annotations
3
+
4
+ from .client import RatioClient
5
+ from .exceptions import (
6
+ RatioApiError,
7
+ RatioAuthError,
8
+ RatioConnectionError,
9
+ RatioError,
10
+ RatioRateLimitError,
11
+ )
12
+ from .token_store import JsonFileTokenStore, MemoryTokenStore, TokenBundle, TokenStore
13
+
14
+ __all__ = [
15
+ "RatioClient",
16
+ "RatioError",
17
+ "RatioAuthError",
18
+ "RatioApiError",
19
+ "RatioRateLimitError",
20
+ "RatioConnectionError",
21
+ "TokenStore",
22
+ "TokenBundle",
23
+ "MemoryTokenStore",
24
+ "JsonFileTokenStore",
25
+ ]
26
+
27
+ __version__ = "0.1.0"
aioratio/_transport.py ADDED
@@ -0,0 +1,132 @@
1
+ """Private HTTP transport for the Ratio cloud API.
2
+
3
+ Wraps an :class:`aiohttp.ClientSession` and a :class:`CognitoSrpAuth`
4
+ instance: every request is signed with a bearer access token and a
5
+ single 401 retry is attempted (forcing the auth driver to refresh or
6
+ re-login on the second call).
7
+
8
+ This module is intentionally private -- public callers go through
9
+ :class:`aioratio.client.RatioClient`.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import json as _json
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ import aiohttp
18
+
19
+ from .const import API_BASE_URL, USER_AGENT
20
+ from .exceptions import (
21
+ RatioApiError,
22
+ RatioAuthError,
23
+ RatioConnectionError,
24
+ RatioRateLimitError,
25
+ )
26
+
27
+ if TYPE_CHECKING:
28
+ from .auth import CognitoSrpAuth
29
+
30
+
31
+ class _CloudTransport:
32
+ """Private async HTTP transport for the Ratio cloud API."""
33
+
34
+ def __init__(
35
+ self,
36
+ *,
37
+ auth: "CognitoSrpAuth",
38
+ session: aiohttp.ClientSession,
39
+ base_url: str = API_BASE_URL,
40
+ timeout: float = 30.0,
41
+ ) -> None:
42
+ self._auth = auth
43
+ self._session = session
44
+ self._base_url = base_url.rstrip("/")
45
+ self._timeout = aiohttp.ClientTimeout(total=timeout)
46
+
47
+ async def request(
48
+ self,
49
+ method: str,
50
+ path: str,
51
+ *,
52
+ params: dict[str, Any] | None = None,
53
+ json: dict[str, Any] | None = None,
54
+ ) -> Any:
55
+ """Send an authenticated request and return parsed JSON or None."""
56
+ if not path.startswith("/"):
57
+ path = "/" + path
58
+ url = self._base_url + path
59
+ method_upper = method.upper()
60
+
61
+ retried = False
62
+ while True:
63
+ access_token = await self._auth.get_access_token()
64
+ headers = {
65
+ "Authorization": f"Bearer {access_token}",
66
+ "User-Agent": USER_AGENT,
67
+ "Accept": "application/json",
68
+ }
69
+ if method_upper != "GET" and json is not None:
70
+ headers["Content-Type"] = "application/json"
71
+
72
+ try:
73
+ async with self._session.request(
74
+ method_upper,
75
+ url,
76
+ params=params,
77
+ json=json,
78
+ headers=headers,
79
+ timeout=self._timeout,
80
+ ) as resp:
81
+ status = resp.status
82
+ body_bytes = await resp.read()
83
+ content_type = resp.headers.get("Content-Type", "")
84
+ retry_after = resp.headers.get("Retry-After")
85
+ except aiohttp.ClientError as err:
86
+ raise RatioConnectionError(str(err)) from err
87
+ except asyncio.TimeoutError as err:
88
+ raise RatioConnectionError("request timed out") from err
89
+
90
+ if status == 401:
91
+ if retried:
92
+ raise RatioAuthError("authentication rejected after refresh")
93
+ retried = True
94
+ # Best-effort: expire any cached bundle so the next
95
+ # get_access_token() forces a refresh or re-login.
96
+ store = getattr(self._auth, "_token_store", None)
97
+ if store is not None:
98
+ try:
99
+ bundle = await store.load()
100
+ except Exception: # pragma: no cover - defensive
101
+ bundle = None
102
+ if bundle is not None:
103
+ bundle.expires_at = 0.0
104
+ try:
105
+ await store.save(bundle)
106
+ except Exception: # pragma: no cover - defensive
107
+ pass
108
+ continue
109
+
110
+ if status == 429:
111
+ msg = "rate limit exceeded"
112
+ if retry_after:
113
+ msg = f"{msg} (retry-after={retry_after})"
114
+ raise RatioRateLimitError(msg)
115
+
116
+ if status >= 400:
117
+ body_text = body_bytes.decode("utf-8", errors="replace")
118
+ raise RatioApiError(f"HTTP {status}: {body_text}")
119
+
120
+ if not body_bytes:
121
+ return None
122
+ if "json" in content_type.lower() or body_bytes.lstrip().startswith(
123
+ (b"{", b"[")
124
+ ):
125
+ try:
126
+ return _json.loads(body_bytes.decode("utf-8"))
127
+ except ValueError as err:
128
+ raise RatioApiError(f"invalid JSON response: {err}") from err
129
+ return None
130
+
131
+
132
+ __all__ = ["_CloudTransport"]
aioratio/auth.py ADDED
@@ -0,0 +1,396 @@
1
+ """Cognito SRP authentication driver.
2
+
3
+ Implements three flows against the Cognito Identity Provider service:
4
+
5
+ 1. First-time login (``USER_SRP_AUTH`` -> ``ConfirmDevice`` ->
6
+ ``UpdateDeviceStatus``).
7
+ 2. Subsequent login with a remembered device (``USER_SRP_AUTH`` ->
8
+ ``DEVICE_SRP_AUTH`` -> ``DEVICE_PASSWORD_VERIFIER``).
9
+ 3. Refresh-token grant (``REFRESH_TOKEN_AUTH``) with rotation handling.
10
+
11
+ Token persistence is delegated to :class:`TokenStore`.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import time
17
+ from typing import Any
18
+
19
+ import aiohttp
20
+
21
+ from .const import COGNITO_CLIENT_ID, COGNITO_REGION, COGNITO_USER_POOL_ID
22
+ from .exceptions import (
23
+ RatioApiError,
24
+ RatioAuthError,
25
+ RatioConnectionError,
26
+ RatioRateLimitError,
27
+ )
28
+ from . import srp as _srp
29
+
30
+ from .token_store import TokenBundle, TokenStore
31
+
32
+
33
+ _DEVICE_NAME = "Home Assistant via aioratio"
34
+
35
+
36
+ def _cognito_url(region: str) -> str:
37
+ return f"https://cognito-idp.{region}.amazonaws.com/"
38
+
39
+
40
+ def _expires_at(expires_in: int | float) -> float:
41
+ return time.time() + float(expires_in)
42
+
43
+
44
+ def _is_expired(bundle: TokenBundle) -> bool:
45
+ return bundle.is_expired
46
+
47
+
48
+ class CognitoSrpAuth:
49
+ """Cognito SRP authentication driver."""
50
+
51
+ def __init__(
52
+ self,
53
+ *,
54
+ email: str | None,
55
+ password: str | None,
56
+ token_store: TokenStore,
57
+ session: aiohttp.ClientSession,
58
+ client_id: str = COGNITO_CLIENT_ID,
59
+ user_pool_id: str = COGNITO_USER_POOL_ID,
60
+ region: str = COGNITO_REGION,
61
+ ) -> None:
62
+ self._email = email
63
+ self._password = password
64
+ self._token_store = token_store
65
+ self._session = session
66
+ self._client_id = client_id
67
+ self._user_pool_id = user_pool_id
68
+ self._region = region
69
+ self._lock = asyncio.Lock()
70
+
71
+ @property
72
+ def pool_name(self) -> str:
73
+ """The portion of the user-pool id after the underscore."""
74
+ return self._user_pool_id.split("_", 1)[1]
75
+
76
+ # ------------------------------------------------------------------
77
+ # Public API
78
+ # ------------------------------------------------------------------
79
+ async def get_access_token(self) -> str:
80
+ async with self._lock:
81
+ bundle = await self._token_store.load()
82
+ if bundle is None:
83
+ bundle = await self._login_locked()
84
+ elif _is_expired(bundle):
85
+ if bundle.refresh_token:
86
+ try:
87
+ bundle = await self._refresh_locked(bundle)
88
+ except RatioAuthError:
89
+ bundle = await self._login_locked()
90
+ else:
91
+ bundle = await self._login_locked()
92
+ return bundle.access_token
93
+
94
+ async def login(self) -> TokenBundle:
95
+ async with self._lock:
96
+ return await self._login_locked()
97
+
98
+ async def refresh(self, bundle: TokenBundle) -> TokenBundle:
99
+ async with self._lock:
100
+ return await self._refresh_locked(bundle)
101
+
102
+ # ------------------------------------------------------------------
103
+ # Internals (assume lock held)
104
+ # ------------------------------------------------------------------
105
+ async def _login_locked(self) -> TokenBundle:
106
+ if self._email is None or self._password is None:
107
+ raise RatioAuthError("email and password required for login")
108
+
109
+ existing = await self._token_store.load()
110
+ device_key = getattr(existing, "device_key", None) if existing else None
111
+ device_group_key = (
112
+ getattr(existing, "device_group_key", None) if existing else None
113
+ )
114
+ device_password = (
115
+ getattr(existing, "device_password", None) if existing else None
116
+ )
117
+
118
+ user_srp = _srp.UserSrp()
119
+ srp_a = user_srp.start()
120
+
121
+ auth_params: dict[str, str] = {
122
+ "USERNAME": self._email,
123
+ "SRP_A": srp_a,
124
+ }
125
+ if device_key:
126
+ auth_params["DEVICE_KEY"] = device_key
127
+
128
+ init = await self._initiate_auth("USER_SRP_AUTH", auth_params)
129
+ challenge = init.get("ChallengeName")
130
+ if challenge != "PASSWORD_VERIFIER":
131
+ self._raise_unsupported(challenge)
132
+
133
+ cp = init["ChallengeParameters"]
134
+ srp_username = cp["USERNAME"] # echo this verbatim
135
+ user_id_for_srp = cp["USER_ID_FOR_SRP"]
136
+ signature, ts = user_srp.process_challenge(
137
+ cp["SRP_B"],
138
+ cp["SALT"],
139
+ cp["SECRET_BLOCK"],
140
+ user_id_for_srp,
141
+ self.pool_name,
142
+ self._password,
143
+ )
144
+ responses = {
145
+ "USERNAME": srp_username,
146
+ "PASSWORD_CLAIM_SECRET_BLOCK": cp["SECRET_BLOCK"],
147
+ "PASSWORD_CLAIM_SIGNATURE": signature,
148
+ "TIMESTAMP": ts,
149
+ }
150
+ if device_key:
151
+ responses["DEVICE_KEY"] = device_key
152
+ resp = await self._respond_to_challenge("PASSWORD_VERIFIER", responses)
153
+
154
+ # If a remembered device exists, Cognito returns DEVICE_SRP_AUTH next.
155
+ if resp.get("ChallengeName") == "DEVICE_SRP_AUTH":
156
+ if not (device_key and device_group_key and device_password):
157
+ raise RatioAuthError(
158
+ "DEVICE_SRP_AUTH challenge issued but no stored device"
159
+ )
160
+ device_srp = _srp.DeviceSrp(
161
+ device_group_key, device_key, device_password
162
+ )
163
+ device_a = device_srp.start()
164
+ cp2 = resp["ChallengeParameters"]
165
+ username2 = cp2.get("USERNAME", srp_username)
166
+ resp2 = await self._respond_to_challenge(
167
+ "DEVICE_SRP_AUTH",
168
+ {
169
+ "USERNAME": username2,
170
+ "DEVICE_KEY": device_key,
171
+ "SRP_A": device_a,
172
+ },
173
+ )
174
+ if resp2.get("ChallengeName") != "DEVICE_PASSWORD_VERIFIER":
175
+ self._raise_unsupported(resp2.get("ChallengeName"))
176
+ cp3 = resp2["ChallengeParameters"]
177
+ username3 = cp3.get("USERNAME", username2)
178
+ sig2, ts2 = device_srp.process_challenge(
179
+ cp3["SRP_B"], cp3["SALT"], cp3["SECRET_BLOCK"]
180
+ )
181
+ resp3 = await self._respond_to_challenge(
182
+ "DEVICE_PASSWORD_VERIFIER",
183
+ {
184
+ "USERNAME": username3,
185
+ "PASSWORD_CLAIM_SECRET_BLOCK": cp3["SECRET_BLOCK"],
186
+ "PASSWORD_CLAIM_SIGNATURE": sig2,
187
+ "TIMESTAMP": ts2,
188
+ "DEVICE_KEY": device_key,
189
+ },
190
+ )
191
+ auth_result = self._extract_auth_result(resp3)
192
+ bundle = self._build_bundle(
193
+ auth_result,
194
+ device_key=device_key,
195
+ device_group_key=device_group_key,
196
+ device_password=device_password,
197
+ fallback_refresh=existing.refresh_token if existing else None,
198
+ )
199
+ await self._token_store.save(bundle)
200
+ return bundle
201
+
202
+ # Otherwise expect AuthenticationResult and possibly NewDeviceMetadata.
203
+ if "AuthenticationResult" not in resp:
204
+ self._raise_unsupported(resp.get("ChallengeName"))
205
+ auth_result = resp["AuthenticationResult"]
206
+ new_dev = auth_result.get("NewDeviceMetadata") or {}
207
+ new_device_key = new_dev.get("DeviceKey")
208
+ new_device_group_key = new_dev.get("DeviceGroupKey")
209
+ new_device_password: str | None = None
210
+ if new_device_key and new_device_group_key:
211
+ verifier = _srp.generate_device_verifier(
212
+ new_device_group_key, new_device_key
213
+ )
214
+ new_device_password = verifier["password"]
215
+ await self._confirm_device(
216
+ access_token=auth_result["AccessToken"],
217
+ device_key=new_device_key,
218
+ password_verifier=verifier["verifier_b64"],
219
+ salt=verifier["salt_b64"],
220
+ )
221
+ await self._update_device_status(
222
+ access_token=auth_result["AccessToken"],
223
+ device_key=new_device_key,
224
+ )
225
+
226
+ bundle = self._build_bundle(
227
+ auth_result,
228
+ device_key=new_device_key,
229
+ device_group_key=new_device_group_key,
230
+ device_password=new_device_password,
231
+ )
232
+ await self._token_store.save(bundle)
233
+ return bundle
234
+
235
+ async def _refresh_locked(self, bundle: TokenBundle) -> TokenBundle:
236
+ if not bundle.refresh_token:
237
+ raise RatioAuthError("no refresh token available")
238
+ params: dict[str, str] = {"REFRESH_TOKEN": bundle.refresh_token}
239
+ if bundle.device_key:
240
+ params["DEVICE_KEY"] = bundle.device_key
241
+ resp = await self._initiate_auth("REFRESH_TOKEN_AUTH", params)
242
+ if "AuthenticationResult" not in resp:
243
+ self._raise_unsupported(resp.get("ChallengeName"))
244
+ auth_result = resp["AuthenticationResult"]
245
+ new_bundle = self._build_bundle(
246
+ auth_result,
247
+ device_key=bundle.device_key,
248
+ device_group_key=bundle.device_group_key,
249
+ device_password=bundle.device_password,
250
+ fallback_refresh=bundle.refresh_token,
251
+ )
252
+ await self._token_store.save(new_bundle)
253
+ return new_bundle
254
+
255
+ # ------------------------------------------------------------------
256
+ # Cognito wire calls
257
+ # ------------------------------------------------------------------
258
+ async def _initiate_auth(
259
+ self, auth_flow: str, auth_parameters: dict[str, str]
260
+ ) -> dict[str, Any]:
261
+ return await self._cognito_call(
262
+ "InitiateAuth",
263
+ {
264
+ "AuthFlow": auth_flow,
265
+ "ClientId": self._client_id,
266
+ "AuthParameters": auth_parameters,
267
+ },
268
+ )
269
+
270
+ async def _respond_to_challenge(
271
+ self, challenge_name: str, responses: dict[str, str]
272
+ ) -> dict[str, Any]:
273
+ return await self._cognito_call(
274
+ "RespondToAuthChallenge",
275
+ {
276
+ "ChallengeName": challenge_name,
277
+ "ClientId": self._client_id,
278
+ "ChallengeResponses": responses,
279
+ },
280
+ )
281
+
282
+ async def _confirm_device(
283
+ self,
284
+ *,
285
+ access_token: str,
286
+ device_key: str,
287
+ password_verifier: str,
288
+ salt: str,
289
+ ) -> None:
290
+ await self._cognito_call(
291
+ "ConfirmDevice",
292
+ {
293
+ "AccessToken": access_token,
294
+ "DeviceKey": device_key,
295
+ "DeviceName": _DEVICE_NAME,
296
+ "DeviceSecretVerifierConfig": {
297
+ "PasswordVerifier": password_verifier,
298
+ "Salt": salt,
299
+ },
300
+ },
301
+ )
302
+
303
+ async def _update_device_status(
304
+ self, *, access_token: str, device_key: str
305
+ ) -> None:
306
+ await self._cognito_call(
307
+ "UpdateDeviceStatus",
308
+ {
309
+ "AccessToken": access_token,
310
+ "DeviceKey": device_key,
311
+ "DeviceRememberedStatus": "remembered",
312
+ },
313
+ )
314
+
315
+ async def _cognito_call(self, target: str, body: dict[str, Any]) -> dict[str, Any]:
316
+ url = _cognito_url(self._region)
317
+ headers = {
318
+ "Content-Type": "application/x-amz-json-1.1",
319
+ "X-Amz-Target": f"AWSCognitoIdentityProviderService.{target}",
320
+ }
321
+ try:
322
+ async with self._session.post(url, headers=headers, json=body) as resp:
323
+ status = resp.status
324
+ text = await resp.text()
325
+ except aiohttp.ClientError as err:
326
+ raise RatioConnectionError(str(err)) from err
327
+ except asyncio.TimeoutError as err:
328
+ raise RatioConnectionError("request timed out") from err
329
+
330
+ try:
331
+ import json
332
+ data = json.loads(text) if text else {}
333
+ except ValueError as err:
334
+ raise RatioAuthError(f"invalid JSON from Cognito: {text!r}") from err
335
+
336
+ if status >= 400 or "__type" in data:
337
+ self._raise_cognito_error(data, status)
338
+ return data
339
+
340
+ # ------------------------------------------------------------------
341
+ # Helpers
342
+ # ------------------------------------------------------------------
343
+ def _build_bundle(
344
+ self,
345
+ auth_result: dict[str, Any],
346
+ *,
347
+ device_key: str | None,
348
+ device_group_key: str | None,
349
+ device_password: str | None,
350
+ fallback_refresh: str | None = None,
351
+ ) -> TokenBundle:
352
+ refresh = auth_result.get("RefreshToken") or fallback_refresh or ""
353
+ return TokenBundle(
354
+ access_token=auth_result["AccessToken"],
355
+ id_token=auth_result.get("IdToken", ""),
356
+ refresh_token=refresh,
357
+ expires_at=_expires_at(auth_result.get("ExpiresIn", 3600)),
358
+ token_type=auth_result.get("TokenType", "Bearer"),
359
+ device_key=device_key,
360
+ device_group_key=device_group_key,
361
+ device_password=device_password,
362
+ )
363
+
364
+ @staticmethod
365
+ def _extract_auth_result(resp: dict[str, Any]) -> dict[str, Any]:
366
+ if "AuthenticationResult" not in resp:
367
+ raise RatioAuthError(
368
+ f"unexpected Cognito response: {resp.get('ChallengeName')!r}"
369
+ )
370
+ return resp["AuthenticationResult"]
371
+
372
+ @staticmethod
373
+ def _raise_unsupported(name: str | None) -> None:
374
+ raise RatioAuthError(f"unsupported challenge: {name}")
375
+
376
+ @staticmethod
377
+ def _raise_cognito_error(data: dict[str, Any], status: int) -> None:
378
+ err_type = data.get("__type", "")
379
+ message = data.get("message") or data.get("Message") or err_type or "Cognito error"
380
+ short = err_type.rsplit("#", 1)[-1] if err_type else ""
381
+ if short in {
382
+ "NotAuthorizedException",
383
+ "UserNotFoundException",
384
+ "PasswordResetRequiredException",
385
+ "UserNotConfirmedException",
386
+ "InvalidParameterException",
387
+ }:
388
+ raise RatioAuthError(f"{short}: {message}")
389
+ if short == "TooManyRequestsException":
390
+ raise RatioRateLimitError(f"{short}: {message}")
391
+ if status >= 500:
392
+ raise RatioApiError(f"Cognito {status}: {message}")
393
+ raise RatioAuthError(f"{short or 'CognitoError'}: {message}")
394
+
395
+
396
+ __all__ = ["CognitoSrpAuth", "TokenBundle"]