stalzone-api 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.
stalzone_api/auth.py ADDED
@@ -0,0 +1,525 @@
1
+ """OAuth 2.0 helpers and credential providers for the Stalzone API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ import threading
8
+ from dataclasses import dataclass, field
9
+ from datetime import datetime, timedelta, timezone
10
+ from typing import Any, Callable
11
+ from urllib.parse import urlencode
12
+
13
+ import httpx
14
+
15
+ from .constants import (
16
+ DEFAULT_TIMEOUT,
17
+ DEFAULT_USER_AGENT,
18
+ OAUTH_AUTHORIZE_URL,
19
+ OAUTH_TOKEN_URL,
20
+ OAUTH_USERINFO_URL,
21
+ )
22
+ from .errors import AuthError, JwtError, error_from_response
23
+
24
+ __all__ = [
25
+ "AppSecretCredentials",
26
+ "Credentials",
27
+ "OAuth",
28
+ "StaticTokenCredentials",
29
+ "Token",
30
+ "TokenCredentials",
31
+ "UserInfo",
32
+ "decode_jwt",
33
+ "fetch_user_info",
34
+ ]
35
+
36
+
37
+ def _utcnow() -> datetime:
38
+ return datetime.now(timezone.utc)
39
+
40
+
41
+ def decode_jwt(token: str) -> dict[str, Any]:
42
+ """Decode a JWT payload **without** verifying the signature.
43
+
44
+ Stalzone tokens are RS256 JWTs. Signature verification requires EXBO's public
45
+ keys, which are not published, so this helper is only useful for reading
46
+ ``exp``/``sub``/``aud`` and for debugging.
47
+ """
48
+
49
+ try:
50
+ payload = token.split(".")[1]
51
+ except IndexError as exc: # pragma: no cover - defensive
52
+ raise JwtError("malformed JWT: expected three dot-separated parts") from exc
53
+ padding = "=" * (-len(payload) % 4)
54
+ try:
55
+ raw = base64.urlsafe_b64decode(payload + padding)
56
+ decoded = json.loads(raw)
57
+ except (ValueError, json.JSONDecodeError) as exc:
58
+ raise JwtError("malformed JWT payload") from exc
59
+ if not isinstance(decoded, dict):
60
+ raise JwtError("malformed JWT payload: expected an object")
61
+ return decoded
62
+
63
+
64
+ @dataclass
65
+ class Token:
66
+ """An OAuth access token (optionally with a refresh token)."""
67
+
68
+ access_token: str
69
+ token_type: str = "Bearer"
70
+ expires_in: int | None = None
71
+ refresh_token: str | None = None
72
+ scope: str | None = None
73
+ acquired_at: datetime = field(default_factory=_utcnow)
74
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
75
+
76
+ @classmethod
77
+ def from_dict(cls, data: dict[str, Any]) -> "Token":
78
+ return cls(
79
+ access_token=str(data.get("access_token", "")),
80
+ token_type=str(data.get("token_type") or "Bearer"),
81
+ expires_in=data.get("expires_in"),
82
+ refresh_token=data.get("refresh_token"),
83
+ scope=data.get("scope"),
84
+ raw=dict(data),
85
+ )
86
+
87
+ @property
88
+ def payload(self) -> dict[str, Any]:
89
+ return decode_jwt(self.access_token)
90
+
91
+ @property
92
+ def expires_at(self) -> datetime | None:
93
+ try:
94
+ exp = self.payload.get("exp")
95
+ except JwtError:
96
+ exp = None
97
+ if exp is not None:
98
+ return datetime.fromtimestamp(int(exp), tz=timezone.utc)
99
+ if self.expires_in is not None:
100
+ return self.acquired_at + timedelta(seconds=int(self.expires_in))
101
+ return None
102
+
103
+ def is_expired(self, leeway: int = 60) -> bool:
104
+ expires_at = self.expires_at
105
+ if expires_at is None:
106
+ return False
107
+ return expires_at <= _utcnow() + timedelta(seconds=leeway)
108
+
109
+ def authorization(self) -> str:
110
+ return f"{self.token_type or 'Bearer'} {self.access_token}"
111
+
112
+ def to_dict(self) -> dict[str, Any]:
113
+ data: dict[str, Any] = {
114
+ "access_token": self.access_token,
115
+ "token_type": self.token_type,
116
+ }
117
+ if self.expires_in is not None:
118
+ data["expires_in"] = self.expires_in
119
+ if self.refresh_token:
120
+ data["refresh_token"] = self.refresh_token
121
+ if self.scope is not None:
122
+ data["scope"] = self.scope
123
+ return data
124
+
125
+
126
+ @dataclass
127
+ class UserInfo:
128
+ """Response of ``GET https://exbo.net/oauth/user``."""
129
+
130
+ id: int | None = None
131
+ uuid: str | None = None
132
+ login: str | None = None
133
+ display_login: str | None = None
134
+ distributor: str | None = None
135
+ distributor_id: str | None = None
136
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
137
+
138
+ @classmethod
139
+ def from_dict(cls, data: dict[str, Any]) -> "UserInfo":
140
+ return cls(
141
+ id=data.get("id"),
142
+ uuid=data.get("uuid"),
143
+ login=data.get("login"),
144
+ display_login=data.get("display_login"),
145
+ distributor=data.get("distributor"),
146
+ distributor_id=data.get("distributor_id"),
147
+ raw=dict(data),
148
+ )
149
+
150
+
151
+ class OAuth:
152
+ """OAuth 2.0 client for EXBO (authorization code, refresh and client credentials)."""
153
+
154
+ def __init__(
155
+ self,
156
+ client_id: str | int,
157
+ client_secret: str = "",
158
+ *,
159
+ authorize_url: str = OAUTH_AUTHORIZE_URL,
160
+ token_url: str = OAUTH_TOKEN_URL,
161
+ userinfo_url: str = OAUTH_USERINFO_URL,
162
+ timeout: float = DEFAULT_TIMEOUT,
163
+ user_agent: str | None = None,
164
+ client: httpx.Client | None = None,
165
+ async_client: httpx.AsyncClient | None = None,
166
+ ) -> None:
167
+ self.client_id = str(client_id)
168
+ self.client_secret = client_secret
169
+ self.authorize_endpoint = authorize_url
170
+ self.token_url = token_url
171
+ self.userinfo_url = userinfo_url
172
+ self.timeout = timeout
173
+ self.user_agent = user_agent or DEFAULT_USER_AGENT
174
+ self._client = client
175
+ self._async_client = async_client
176
+ self._owns_client = client is None
177
+ self._owns_async_client = async_client is None
178
+
179
+ # ------------------------------------------------------------------ helpers
180
+ def _http(self) -> httpx.Client:
181
+ if self._client is None:
182
+ self._client = httpx.Client(
183
+ timeout=self.timeout,
184
+ headers={"User-Agent": self.user_agent, "Accept": "application/json"},
185
+ )
186
+ return self._client
187
+
188
+ def _ahttp(self) -> httpx.AsyncClient:
189
+ if self._async_client is None:
190
+ self._async_client = httpx.AsyncClient(
191
+ timeout=self.timeout,
192
+ headers={"User-Agent": self.user_agent, "Accept": "application/json"},
193
+ )
194
+ return self._async_client
195
+
196
+ def _token_from_response(self, response: httpx.Response, context: str) -> Token:
197
+ if response.status_code >= 400:
198
+ try:
199
+ payload: Any = response.json()
200
+ except ValueError:
201
+ payload = response.text
202
+ error = error_from_response(
203
+ response.status_code,
204
+ payload,
205
+ url=str(response.request.url),
206
+ body=response.text[:2000],
207
+ )
208
+ raise AuthError(f"{context}: {error}") from None
209
+ try:
210
+ data = response.json()
211
+ except ValueError as exc:
212
+ raise AuthError(f"{context}: response is not valid JSON") from exc
213
+ token = Token.from_dict(data)
214
+ if not token.access_token:
215
+ raise AuthError(f"{context}: response does not contain an access token")
216
+ return token
217
+
218
+ def _userinfo_from_response(self, response: httpx.Response) -> UserInfo:
219
+ if response.status_code >= 400:
220
+ try:
221
+ payload: Any = response.json()
222
+ except ValueError:
223
+ payload = response.text
224
+ raise AuthError(f"user info request failed: {error_from_response(response.status_code, payload)}")
225
+ return UserInfo.from_dict(response.json())
226
+
227
+ # ------------------------------------------------------------------ sync API
228
+ def authorize_url(
229
+ self,
230
+ redirect_uri: str,
231
+ *,
232
+ state: str | None = None,
233
+ scope: str = "",
234
+ ) -> str:
235
+ """Build the URL the user should be redirected to in order to grant access."""
236
+
237
+ params = {
238
+ "client_id": self.client_id,
239
+ "redirect_uri": redirect_uri,
240
+ "scope": scope,
241
+ "response_type": "code",
242
+ }
243
+ if state is not None:
244
+ params["state"] = state
245
+ return f"{self.authorize_endpoint}?{urlencode(params)}"
246
+
247
+ def client_credentials(self, scope: str = "") -> Token:
248
+ """Obtain an application access token (client credentials grant)."""
249
+
250
+ response = self._http().post(
251
+ self.token_url,
252
+ data={
253
+ "client_id": self.client_id,
254
+ "client_secret": self.client_secret,
255
+ "grant_type": "client_credentials",
256
+ "scope": scope,
257
+ },
258
+ )
259
+ return self._token_from_response(response, "client_credentials grant failed")
260
+
261
+ def exchange_code(self, code: str, redirect_uri: str) -> Token:
262
+ """Exchange an authorization code for an access/refresh token pair."""
263
+
264
+ response = self._http().post(
265
+ self.token_url,
266
+ data={
267
+ "client_id": self.client_id,
268
+ "client_secret": self.client_secret,
269
+ "code": code,
270
+ "grant_type": "authorization_code",
271
+ "redirect_uri": redirect_uri,
272
+ },
273
+ )
274
+ return self._token_from_response(response, "authorization code exchange failed")
275
+
276
+ def refresh(self, refresh_token: str, scope: str = "") -> Token:
277
+ """Refresh an expired user access token."""
278
+
279
+ response = self._http().post(
280
+ self.token_url,
281
+ data={
282
+ "client_id": self.client_id,
283
+ "client_secret": self.client_secret,
284
+ "grant_type": "refresh_token",
285
+ "refresh_token": refresh_token,
286
+ "scope": scope,
287
+ },
288
+ )
289
+ return self._token_from_response(response, "token refresh failed")
290
+
291
+ def user_info(self, access_token: str) -> UserInfo:
292
+ """Fetch the EXBO account attached to a user access token."""
293
+
294
+ response = self._http().get(
295
+ self.userinfo_url,
296
+ headers={"Authorization": f"Bearer {access_token}"},
297
+ )
298
+ return self._userinfo_from_response(response)
299
+
300
+ # ----------------------------------------------------------------- async API
301
+ async def async_client_credentials(self, scope: str = "") -> Token:
302
+ response = await self._ahttp().post(
303
+ self.token_url,
304
+ data={
305
+ "client_id": self.client_id,
306
+ "client_secret": self.client_secret,
307
+ "grant_type": "client_credentials",
308
+ "scope": scope,
309
+ },
310
+ )
311
+ return self._token_from_response(response, "client_credentials grant failed")
312
+
313
+ async def async_exchange_code(self, code: str, redirect_uri: str) -> Token:
314
+ response = await self._ahttp().post(
315
+ self.token_url,
316
+ data={
317
+ "client_id": self.client_id,
318
+ "client_secret": self.client_secret,
319
+ "code": code,
320
+ "grant_type": "authorization_code",
321
+ "redirect_uri": redirect_uri,
322
+ },
323
+ )
324
+ return self._token_from_response(response, "authorization code exchange failed")
325
+
326
+ async def async_refresh(self, refresh_token: str, scope: str = "") -> Token:
327
+ response = await self._ahttp().post(
328
+ self.token_url,
329
+ data={
330
+ "client_id": self.client_id,
331
+ "client_secret": self.client_secret,
332
+ "grant_type": "refresh_token",
333
+ "refresh_token": refresh_token,
334
+ "scope": scope,
335
+ },
336
+ )
337
+ return self._token_from_response(response, "token refresh failed")
338
+
339
+ async def async_user_info(self, access_token: str) -> UserInfo:
340
+ response = await self._ahttp().get(
341
+ self.userinfo_url,
342
+ headers={"Authorization": f"Bearer {access_token}"},
343
+ )
344
+ return self._userinfo_from_response(response)
345
+
346
+ # -------------------------------------------------------------------- close
347
+ def close(self) -> None:
348
+ if self._owns_client and self._client is not None:
349
+ self._client.close()
350
+ self._client = None
351
+
352
+ async def aclose(self) -> None:
353
+ if self._owns_async_client and self._async_client is not None:
354
+ await self._async_client.aclose()
355
+ self._async_client = None
356
+ self.close()
357
+
358
+ def __enter__(self) -> "OAuth":
359
+ return self
360
+
361
+ def __exit__(self, *_: Any) -> None:
362
+ self.close()
363
+
364
+ async def __aenter__(self) -> "OAuth":
365
+ return self
366
+
367
+ async def __aexit__(self, *_: Any) -> None:
368
+ await self.aclose()
369
+
370
+
371
+ def fetch_user_info(
372
+ access_token: str,
373
+ *,
374
+ userinfo_url: str = OAUTH_USERINFO_URL,
375
+ timeout: float = DEFAULT_TIMEOUT,
376
+ user_agent: str | None = None,
377
+ ) -> UserInfo:
378
+ """Standalone helper to fetch EXBO account info for a token."""
379
+
380
+ oauth = OAuth("", "", userinfo_url=userinfo_url, timeout=timeout, user_agent=user_agent)
381
+ try:
382
+ return oauth.user_info(access_token)
383
+ finally:
384
+ oauth.close()
385
+
386
+
387
+ async def async_fetch_user_info(
388
+ access_token: str,
389
+ *,
390
+ userinfo_url: str = OAUTH_USERINFO_URL,
391
+ timeout: float = DEFAULT_TIMEOUT,
392
+ user_agent: str | None = None,
393
+ ) -> UserInfo:
394
+ oauth = OAuth("", "", userinfo_url=userinfo_url, timeout=timeout, user_agent=user_agent)
395
+ try:
396
+ return await oauth.async_user_info(access_token)
397
+ finally:
398
+ await oauth.aclose()
399
+
400
+
401
+ # --------------------------------------------------------------------- credentials
402
+ class Credentials:
403
+ """Credential provider used by the HTTP transports."""
404
+
405
+ token: str | None = None
406
+
407
+ def headers(self) -> dict[str, str]:
408
+ return {}
409
+
410
+ async def async_headers(self) -> dict[str, str]:
411
+ return self.headers()
412
+
413
+ def ensure_token(self) -> str | None:
414
+ return self.token
415
+
416
+ async def async_ensure_token(self) -> str | None:
417
+ return self.ensure_token()
418
+
419
+ def refresh(self) -> bool:
420
+ return False
421
+
422
+ async def async_refresh(self) -> bool:
423
+ return self.refresh()
424
+
425
+
426
+ class StaticTokenCredentials(Credentials):
427
+ """Use an access token obtained elsewhere (user or application token)."""
428
+
429
+ def __init__(self, token: str) -> None:
430
+ self.token = token
431
+ self._headers = {"Authorization": f"Bearer {token}"}
432
+
433
+ def headers(self) -> dict[str, str]:
434
+ return dict(self._headers)
435
+
436
+
437
+ class AppSecretCredentials(Credentials):
438
+ """Secret-based authentication using ``Client-Id``/``Client-Secret`` headers."""
439
+
440
+ def __init__(self, client_id: str | int, client_secret: str) -> None:
441
+ self.client_id = str(client_id)
442
+ self.client_secret = client_secret
443
+ self._headers = {"Client-Id": self.client_id, "Client-Secret": self.client_secret}
444
+
445
+ def headers(self) -> dict[str, str]:
446
+ return dict(self._headers)
447
+
448
+
449
+ class TokenCredentials(Credentials):
450
+ """Client-credentials flow with automatic caching and refresh on ``401``."""
451
+
452
+ def __init__(
453
+ self,
454
+ oauth: OAuth,
455
+ *,
456
+ token: Token | None = None,
457
+ refresh_token: str | None = None,
458
+ on_update: Callable[[Token], Any] | None = None,
459
+ ) -> None:
460
+ self.oauth = oauth
461
+ self._token = token
462
+ self._refresh_token = refresh_token or (token.refresh_token if token else None)
463
+ self._on_update = on_update
464
+ self._lock = threading.Lock()
465
+
466
+ @property
467
+ def token(self) -> str | None: # type: ignore[override]
468
+ return self._token.access_token if self._token is not None else None
469
+
470
+ def _store(self, token: Token) -> Token:
471
+ self._token = token
472
+ if token.refresh_token:
473
+ self._refresh_token = token.refresh_token
474
+ if self._on_update is not None:
475
+ try:
476
+ self._on_update(token)
477
+ except Exception: # pragma: no cover - user callback must not break requests
478
+ pass
479
+ return token
480
+
481
+ def _ensure(self) -> Token:
482
+ if self._token is not None and not self._token.is_expired():
483
+ return self._token
484
+ with self._lock:
485
+ if self._token is not None and not self._token.is_expired():
486
+ return self._token
487
+ token = self.oauth.client_credentials()
488
+ return self._store(token)
489
+
490
+ def headers(self) -> dict[str, str]:
491
+ return {"Authorization": f"Bearer {self._ensure().access_token}"}
492
+
493
+ def ensure_token(self) -> str:
494
+ return self._ensure().access_token
495
+
496
+ def refresh(self) -> bool:
497
+ with self._lock:
498
+ try:
499
+ if self._refresh_token:
500
+ self._store(self.oauth.refresh(self._refresh_token))
501
+ else:
502
+ self._store(self.oauth.client_credentials())
503
+ except AuthError:
504
+ return False
505
+ return True
506
+
507
+ async def async_headers(self) -> dict[str, str]:
508
+ token = await self.async_ensure_token()
509
+ return {"Authorization": f"Bearer {token}"}
510
+
511
+ async def async_ensure_token(self) -> str:
512
+ if self._token is not None and not self._token.is_expired():
513
+ return self._token.access_token
514
+ token = await self.oauth.async_client_credentials()
515
+ return self._store(token).access_token
516
+
517
+ async def async_refresh(self) -> bool:
518
+ try:
519
+ if self._refresh_token:
520
+ self._store(await self.oauth.async_refresh(self._refresh_token))
521
+ else:
522
+ self._store(await self.oauth.async_client_credentials())
523
+ except AuthError:
524
+ return False
525
+ return True