brego 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.
brego/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """Brego partner SDK: OAuth connect flow, token refresh, API calls and
2
+ webhook signature checks for Brego partner apps. Standard library only."""
3
+
4
+ from .client import (
5
+ BregoApiError,
6
+ BregoOAuthError,
7
+ BregoPartnerClient,
8
+ BregoTokenCheckError,
9
+ BregoTokenStoreError,
10
+ BregoTokensRefusedError,
11
+ ConnectionTokens,
12
+ create_pkce,
13
+ create_state,
14
+ verify_webhook_signature,
15
+ )
16
+
17
+ __all__ = [
18
+ "BregoApiError",
19
+ "BregoOAuthError",
20
+ "BregoPartnerClient",
21
+ "BregoTokenCheckError",
22
+ "BregoTokenStoreError",
23
+ "BregoTokensRefusedError",
24
+ "ConnectionTokens",
25
+ "create_pkce",
26
+ "create_state",
27
+ "verify_webhook_signature",
28
+ ]
brego/client.py ADDED
@@ -0,0 +1,468 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import secrets
6
+ import threading
7
+ import time
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Callable, Dict, List, Optional, Tuple
13
+
14
+
15
+ @dataclass
16
+ class ConnectionTokens:
17
+ access_token: str
18
+ refresh_token: str
19
+ expires_at: float # epoch seconds
20
+ connection_id: str
21
+ organization_id: str
22
+ scope: List[str] = field(default_factory=list)
23
+
24
+
25
+ class BregoOAuthError(Exception):
26
+ def __init__(self, code: str, status: int, description: Optional[str] = None):
27
+ super().__init__(description or code)
28
+ self.code = code
29
+ self.status = status
30
+
31
+
32
+ INVALID_TOKEN_MESSAGE = "The access token is invalid, expired or revoked."
33
+ """How Brego's refusal of an invalid, expired or revoked token begins."""
34
+
35
+
36
+ class BregoTokensRefusedError(Exception):
37
+ """An exchange returned tokens Brego already refuses, as it does the
38
+ stored ones: the connection was approved again (its newest tokens are
39
+ still on their way to the store) or revoked. Nothing was saved. Read the
40
+ connection's tokens from the store again, or ask the organisation to
41
+ connect again if none work.
42
+ """
43
+
44
+ def __init__(self, tokens: "ConnectionTokens"):
45
+ super().__init__(
46
+ "Brego refused both the new tokens and the stored ones; nothing was saved."
47
+ )
48
+ self.tokens = tokens
49
+
50
+
51
+ class BregoTokenCheckError(Exception):
52
+ """An exchange returned tokens that differ from the stored ones, and
53
+ Brego could not be reached to tell which still work.
54
+
55
+ Neither set was overwritten: ``tokens`` are the new ones (their code is
56
+ spent) and ``stored`` the old ones. Check again later, or keep whichever
57
+ works.
58
+ """
59
+
60
+ def __init__(self, tokens: "ConnectionTokens", stored: "ConnectionTokens"):
61
+ super().__init__(
62
+ "Could not check which of the connection's tokens still work; both are on the error."
63
+ )
64
+ self.tokens = tokens
65
+ self.stored = stored
66
+
67
+
68
+ class BregoTokenStoreError(Exception):
69
+ """The token store could not save tokens Brego has already issued.
70
+
71
+ The code or refresh token that produced them is spent, so save
72
+ ``tokens`` yourself (they are the connection's only usable credentials).
73
+ """
74
+
75
+ def __init__(self, tokens: "ConnectionTokens", cause: BaseException):
76
+ super().__init__(
77
+ "The token store could not save the new tokens; save error.tokens yourself."
78
+ )
79
+ self.tokens = tokens
80
+ self.__cause__ = cause
81
+
82
+
83
+ class BregoApiError(Exception):
84
+ def __init__(self, status: int, body: Any):
85
+ super().__init__(f"Brego API request failed with {status}")
86
+ self.status = status
87
+ self.body = body
88
+
89
+
90
+ def _b64url(data: bytes) -> str:
91
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
92
+
93
+
94
+ def create_pkce() -> Tuple[str, str]:
95
+ """Returns (verifier, S256 challenge)."""
96
+ verifier = _b64url(secrets.token_bytes(32))
97
+ challenge = _b64url(hashlib.sha256(verifier.encode()).digest())
98
+ return verifier, challenge
99
+
100
+
101
+ def create_state() -> str:
102
+ return _b64url(secrets.token_bytes(24))
103
+
104
+
105
+ def verify_webhook_signature(
106
+ header: Optional[str],
107
+ raw_body: bytes,
108
+ secret: str,
109
+ now_ms: Optional[int] = None,
110
+ tolerance_ms: int = 5 * 60 * 1000,
111
+ ) -> bool:
112
+ """Checks ``X-Signature: t={ms},v1={hex}[,v1=...]``; any v1 may match."""
113
+ if not header:
114
+ return False
115
+ parts = header.split(",")
116
+ try:
117
+ timestamp = int(next(p[2:] for p in parts if p.startswith("t=")))
118
+ except (StopIteration, ValueError):
119
+ return False
120
+ now_ms = int(time.time() * 1000) if now_ms is None else now_ms
121
+ if abs(now_ms - timestamp) > tolerance_ms:
122
+ return False
123
+ expected = hmac.new(
124
+ secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256
125
+ ).hexdigest()
126
+ return any(
127
+ hmac.compare_digest(p[3:], expected) for p in parts if p.startswith("v1=")
128
+ )
129
+
130
+
131
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes]], Tuple[int, bytes]]
132
+
133
+
134
+ def _urllib_transport(
135
+ method: str, url: str, headers: Dict[str, str], body: Optional[bytes]
136
+ ) -> Tuple[int, bytes]:
137
+ request = urllib.request.Request(url, data=body, headers=headers, method=method)
138
+ try:
139
+ with urllib.request.urlopen(request, timeout=30) as response:
140
+ return response.status, response.read()
141
+ except urllib.error.HTTPError as error:
142
+ return error.code, error.read()
143
+
144
+
145
+ def _query_value(value: Any) -> str:
146
+ """Formats a query value as the API expects; booleans are lowercase."""
147
+ if isinstance(value, bool):
148
+ return "true" if value else "false"
149
+ return str(value)
150
+
151
+
152
+ class BregoPartnerClient:
153
+ """Calls the Brego API for a partner app's connections.
154
+
155
+ ``token_store`` needs ``get(connection_id) -> ConnectionTokens | None``,
156
+ ``set(tokens)`` and ``delete(connection_id)``, which is called once a
157
+ connection is revoked; persist tokens there yourself. When several processes
158
+ share the store, also give it ``with_lock(connection_id, fn)``, which runs
159
+ ``fn`` while holding a lock they all respect (a database row lock, say)
160
+ and returns its result, so only one of them refreshes at a time.
161
+ """
162
+
163
+ def __init__(
164
+ self,
165
+ client_id: str,
166
+ client_secret: str,
167
+ token_store: Any,
168
+ api_base_url: str = "https://api.brego.io",
169
+ transport: Transport = _urllib_transport,
170
+ refresh_margin_seconds: int = 60,
171
+ ):
172
+ self.client_id = client_id
173
+ self.client_secret = client_secret
174
+ self.token_store = token_store
175
+ self.api_base_url = api_base_url.rstrip("/")
176
+ self.transport = transport
177
+ self.refresh_margin_seconds = refresh_margin_seconds
178
+ # Per-connection refresh locks with how many callers use each, so an
179
+ # entry is dropped once no refresh holds or waits on it.
180
+ self._locks: Dict[str, List[Any]] = {}
181
+ self._locks_guard = threading.Lock()
182
+
183
+ def authorize_url(
184
+ self,
185
+ redirect_uri: str,
186
+ state: str,
187
+ code_challenge: str,
188
+ scopes: Optional[List[str]] = None,
189
+ ) -> str:
190
+ query = urllib.parse.urlencode(
191
+ {
192
+ "response_type": "code",
193
+ "client_id": self.client_id,
194
+ "redirect_uri": redirect_uri,
195
+ "scope": " ".join(scopes or []),
196
+ "state": state,
197
+ "code_challenge": code_challenge,
198
+ "code_challenge_method": "S256",
199
+ }
200
+ )
201
+ return f"{self.api_base_url}/v1/oauth/authorize?{query}"
202
+
203
+ def exchange_code(
204
+ self, code: str, redirect_uri: str, code_verifier: str
205
+ ) -> ConnectionTokens:
206
+ tokens = self._token_request(
207
+ {
208
+ "grant_type": "authorization_code",
209
+ "code": code,
210
+ "redirect_uri": redirect_uri,
211
+ "code_verifier": code_verifier,
212
+ }
213
+ )
214
+ # Two approvals for the same connection can be exchanged at once: the
215
+ # later one replaces the earlier tokens. Saved one at a time per
216
+ # connection, and never over newer tokens that still work.
217
+ def run() -> ConnectionTokens:
218
+ kept = self._newer_stored_tokens(tokens)
219
+ if kept is not None:
220
+ return kept
221
+ self._save_issued(tokens)
222
+ return tokens
223
+
224
+ def locked(lock: threading.Lock) -> ConnectionTokens:
225
+ with lock:
226
+ shared_lock = getattr(self.token_store, "with_lock", None)
227
+ if shared_lock is not None:
228
+ return shared_lock(tokens.connection_id, run)
229
+ return run()
230
+
231
+ return self._with_connection_lock(tokens.connection_id, locked)
232
+
233
+ def _newer_stored_tokens(
234
+ self, issued: ConnectionTokens
235
+ ) -> Optional[ConnectionTokens]:
236
+ """The stored tokens when they are newer than ``issued``: ``issued``
237
+ is refused while the different stored ones still work. Raises
238
+ ``BregoTokenCheckError`` when neither can be shown to be refused, and
239
+ ``BregoTokensRefusedError`` when both are."""
240
+ stored = self.token_store.get(issued.connection_id)
241
+ if stored is None or stored.access_token == issued.access_token:
242
+ return None
243
+ issued_works = self._works(issued.access_token)
244
+ if issued_works is True:
245
+ return None
246
+ stored_works = self._works(stored.access_token)
247
+ if stored_works is True:
248
+ return stored
249
+ # Neither works: a later approval replaced both, or the connection
250
+ # was revoked. Saving either would only store tokens known not to work.
251
+ if stored_works is False and issued_works is False:
252
+ raise BregoTokensRefusedError(issued)
253
+ # Replace the stored tokens only once they are known to be refused,
254
+ # and keep them while the new ones are.
255
+ if stored_works is False:
256
+ return None
257
+ if issued_works is False:
258
+ return stored
259
+ raise BregoTokenCheckError(issued, stored)
260
+
261
+ def _works(self, access_token: str) -> Optional[bool]:
262
+ """Whether Brego accepts the token: False only when it says the token
263
+ itself is invalid, None when that is not clear. A 403 for any other
264
+ reason (the app suspended, say) applies to every token of the
265
+ connection, so it says nothing about which one is current."""
266
+ try:
267
+ status, body = self.transport(
268
+ "GET",
269
+ self.api_base_url + "/v1/oauth/connection",
270
+ {"Authorization": f"Bearer {access_token}"},
271
+ None,
272
+ )
273
+ except Exception: # noqa: BLE001 - the check could not be completed
274
+ return None
275
+ if 200 <= status < 300:
276
+ return True
277
+ if status == 401:
278
+ return False
279
+ if status != 403:
280
+ return None
281
+ try:
282
+ message = json.loads(body or b"{}").get("message")
283
+ except (ValueError, AttributeError):
284
+ return None
285
+ if isinstance(message, str) and message.startswith(INVALID_TOKEN_MESSAGE):
286
+ return False
287
+ return None
288
+
289
+ def _save_issued(self, tokens: ConnectionTokens) -> None:
290
+ """Saves just-issued tokens, retrying a failing store a few times.
291
+
292
+ If it still fails they come back on ``BregoTokenStoreError``, as the
293
+ code or refresh token that produced them can't be used again.
294
+ """
295
+ last_error: Optional[BaseException] = None
296
+ for delay in (0, 0.2, 1.0):
297
+ if delay:
298
+ time.sleep(delay)
299
+ try:
300
+ self.token_store.set(tokens)
301
+ return
302
+ except Exception as error: # noqa: BLE001 - any store failure
303
+ last_error = error
304
+ raise BregoTokenStoreError(tokens, last_error) # type: ignore[arg-type]
305
+
306
+ def _with_connection_lock(
307
+ self, connection_id: str, fn: Callable[[threading.Lock], Any]
308
+ ) -> Any:
309
+ """Runs ``fn`` with the connection's lock, dropping it once unused."""
310
+ with self._locks_guard:
311
+ entry = self._locks.setdefault(connection_id, [threading.Lock(), 0])
312
+ entry[1] += 1
313
+ try:
314
+ return fn(entry[0])
315
+ finally:
316
+ with self._locks_guard:
317
+ entry[1] -= 1
318
+ if entry[1] == 0 and self._locks.get(connection_id) is entry:
319
+ del self._locks[connection_id]
320
+
321
+ def refresh(self, connection_id: str) -> ConnectionTokens:
322
+ """One refresh at a time per connection; others wait and reuse it."""
323
+ return self._with_connection_lock(
324
+ connection_id, lambda lock: self._refresh_with(connection_id, lock)
325
+ )
326
+
327
+ def _refresh_with(
328
+ self, connection_id: str, lock: threading.Lock
329
+ ) -> ConnectionTokens:
330
+ before = self.token_store.get(connection_id)
331
+
332
+ def run() -> ConnectionTokens:
333
+ current = self.token_store.get(connection_id)
334
+ if current is None:
335
+ raise ValueError(f"No tokens stored for {connection_id}")
336
+ if before is not None and current.refresh_token != before.refresh_token:
337
+ return current # another thread or process refreshed meanwhile
338
+ tokens = self._token_request(
339
+ {"grant_type": "refresh_token", "refresh_token": current.refresh_token}
340
+ )
341
+ self._save_issued(tokens)
342
+ return tokens
343
+
344
+ with lock:
345
+ # A store shared by several processes supplies a lock they all
346
+ # respect, so only one of them spends the refresh token.
347
+ shared_lock = getattr(self.token_store, "with_lock", None)
348
+ if shared_lock is not None:
349
+ return shared_lock(connection_id, run)
350
+ return run()
351
+
352
+ def revoke(self, connection_id: str) -> None:
353
+ """Ends the connection. Runs under the same locks as a refresh, so a
354
+ refresh in progress cannot store new tokens after they are deleted."""
355
+
356
+ def run() -> None:
357
+ current = self.token_store.get(connection_id)
358
+ if current is None:
359
+ return
360
+ status, body = self._form(
361
+ "/v1/oauth/revoke", {"token": current.refresh_token}
362
+ )
363
+ if status != 200:
364
+ raise BregoApiError(status, _parse(body))
365
+ # The connection is ended for good, so its tokens are of no use.
366
+ self.token_store.delete(connection_id)
367
+
368
+ def locked(lock: threading.Lock) -> None:
369
+ with lock:
370
+ shared_lock = getattr(self.token_store, "with_lock", None)
371
+ if shared_lock is not None:
372
+ shared_lock(connection_id, run)
373
+ else:
374
+ run()
375
+
376
+ self._with_connection_lock(connection_id, locked)
377
+
378
+ def request(
379
+ self,
380
+ connection_id: str,
381
+ method: str,
382
+ path: str,
383
+ query: Optional[Dict[str, Any]] = None,
384
+ body: Any = None,
385
+ ) -> Any:
386
+ tokens = self.token_store.get(connection_id)
387
+ if tokens is None:
388
+ raise ValueError(f"No tokens stored for {connection_id}")
389
+ if tokens.expires_at - self.refresh_margin_seconds <= time.time():
390
+ tokens = self.refresh(connection_id)
391
+
392
+ # Only paths on the configured API: the access token must not reach
393
+ # another host.
394
+ if not path.startswith("/") or path.startswith("//"):
395
+ raise ValueError("path must be an API path starting with a single /")
396
+
397
+ def send(access_token: str) -> Tuple[int, bytes]:
398
+ url = self.api_base_url + path
399
+ if query:
400
+ # Lists and tuples become repeated fields, as array
401
+ # parameters such as `expand` need.
402
+ url += "?" + urllib.parse.urlencode(
403
+ {
404
+ k: [_query_value(item) for item in v]
405
+ if isinstance(v, (list, tuple))
406
+ else _query_value(v)
407
+ for k, v in query.items()
408
+ if v is not None
409
+ },
410
+ doseq=True,
411
+ )
412
+ headers = {"Authorization": f"Bearer {access_token}"}
413
+ data = None
414
+ if body is not None:
415
+ headers["Content-Type"] = "application/json"
416
+ data = json.dumps(body).encode()
417
+ return self.transport(method, url, headers, data)
418
+
419
+ # A 403 is raised without a refresh; its body's message says why, for
420
+ # example that the token is expired or revoked, lacks a scope or the
421
+ # app is suspended.
422
+ status, raw = send(tokens.access_token)
423
+ parsed = _parse(raw)
424
+ if not 200 <= status < 300:
425
+ raise BregoApiError(status, parsed)
426
+ return parsed
427
+
428
+ def get_connection(self, connection_id: str) -> Any:
429
+ return self.request(connection_id, "GET", "/v1/oauth/connection")
430
+
431
+ def _form(self, path: str, fields: Dict[str, str]) -> Tuple[int, bytes]:
432
+ basic = base64.b64encode(
433
+ f"{self.client_id}:{self.client_secret}".encode()
434
+ ).decode()
435
+ return self.transport(
436
+ "POST",
437
+ self.api_base_url + path,
438
+ {
439
+ "Authorization": f"Basic {basic}",
440
+ "Content-Type": "application/x-www-form-urlencoded",
441
+ },
442
+ urllib.parse.urlencode(fields).encode(),
443
+ )
444
+
445
+ def _token_request(self, fields: Dict[str, str]) -> ConnectionTokens:
446
+ status, raw = self._form("/v1/oauth/token", fields)
447
+ body = _parse(raw) or {}
448
+ if status != 200:
449
+ raise BregoOAuthError(
450
+ body.get("error", "server_error"), status, body.get("error_description")
451
+ )
452
+ return ConnectionTokens(
453
+ access_token=body["access_token"],
454
+ refresh_token=body["refresh_token"],
455
+ expires_at=time.time() + int(body["expires_in"]),
456
+ connection_id=body["connection_id"],
457
+ organization_id=body["organization_id"],
458
+ scope=body.get("scope", "").split(),
459
+ )
460
+
461
+
462
+ def _parse(raw: bytes) -> Any:
463
+ if not raw:
464
+ return None
465
+ try:
466
+ return json.loads(raw)
467
+ except ValueError:
468
+ return raw.decode(errors="replace")
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: brego
3
+ Version: 0.1.0
4
+ Summary: Brego API client for partner apps: OAuth connect flow, token refresh and webhook signature checks.
5
+ Requires-Python: >=3.8
6
+ Description-Content-Type: text/markdown
7
+
8
+ # Brego SDK for Python
9
+
10
+ ```bash
11
+ pip install brego
12
+ ```
13
+
14
+ The partner connect flow for Python 3.8 or later, standard library only:
15
+ PKCE and the authorise URL, code exchange, thread-safe refresh, revoke, API
16
+ calls and webhook signature checks.
17
+
18
+ ```python
19
+ from brego import BregoPartnerClient, create_pkce, create_state
20
+
21
+ brego = BregoPartnerClient(client_id, client_secret, token_store)
22
+ verifier, challenge = create_pkce()
23
+ state = create_state()
24
+ url = brego.authorize_url(redirect_uri, state, challenge, scopes=["api:vehicle:read"])
25
+
26
+ # In your callback, after checking state:
27
+ connection = brego.exchange_code(code, redirect_uri, verifier)
28
+ info = brego.get_connection(connection.connection_id)
29
+ ```
30
+
31
+ `token_store` needs `get(connection_id)`, `set(tokens)` and
32
+ `delete(connection_id)`, which `revoke` calls once the connection is ended. Store the newest
33
+ refresh token after every refresh. Refresh tokens are single use: if several
34
+ processes share the store, also give it `with_lock(connection_id, fn)`, which
35
+ runs `fn` while holding a lock they all respect (a database row lock, for
36
+ example) and returns its result, so only one of them refreshes at a time. `request` refreshes the access token before it expires and
37
+ raises `BregoApiError` on a `403`: if `get_connection` also fails, refresh
38
+ once, and ask the organisation to connect again if that fails too.
39
+
40
+ Pass API paths that start with a single `/` (for example `/v1/vehicles`); anything else is refused, so a connection's token is only ever sent to the configured API.
41
+
42
+ If two approvals of the same connection are exchanged at once, the later one replaces the earlier tokens. The SDK saves exchanged tokens one connection at a time and never over stored tokens that still work while the new ones are refused; the exchange then returns the stored tokens. If Brego can't be reached to check which tokens work, nothing is overwritten and the exchange raises `BregoTokenCheckError`, carrying the new tokens in `tokens` and the stored ones in `stored`. The code that produced the new tokens can't be used again, so keep whichever set works once you can check. If Brego refuses both sets, nothing is saved and the exchange raises `BregoTokensRefusedError`: the connection was approved again or revoked, so read its tokens from your store again.
43
+
44
+ If your token store cannot save tokens Brego has just issued, the SDK retries a few times and then raises `BregoTokenStoreError`, carrying the new tokens in `tokens`. The code or refresh token that produced them can't be used again, so save those tokens yourself.
@@ -0,0 +1,6 @@
1
+ brego/__init__.py,sha256=r_ZXq0T91qZwkv2yHkNfxGMXawJjlTffm7JUzlGHgRM,670
2
+ brego/client.py,sha256=1ao9yxj4zSpZutZSZBnQgquAEfufz4smvv_Uf-ExEj0,17525
3
+ brego-0.1.0.dist-info/METADATA,sha256=DkqwIcc_EiNX6ruq0LamPXE69G6WBK9XxRx4snuBnfY,2772
4
+ brego-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
+ brego-0.1.0.dist-info/top_level.txt,sha256=2h1u8FOcFQ8NhDrmtfOJIChtn6Uj9auoRQFnh1-10a4,6
6
+ brego-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ brego