brego 0.1.0__tar.gz
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-0.1.0/PKG-INFO +44 -0
- brego-0.1.0/README.md +37 -0
- brego-0.1.0/brego/__init__.py +28 -0
- brego-0.1.0/brego/client.py +468 -0
- brego-0.1.0/brego.egg-info/PKG-INFO +44 -0
- brego-0.1.0/brego.egg-info/SOURCES.txt +9 -0
- brego-0.1.0/brego.egg-info/dependency_links.txt +1 -0
- brego-0.1.0/brego.egg-info/top_level.txt +1 -0
- brego-0.1.0/pyproject.toml +14 -0
- brego-0.1.0/setup.cfg +4 -0
- brego-0.1.0/tests/test_client.py +371 -0
brego-0.1.0/PKG-INFO
ADDED
|
@@ -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.
|
brego-0.1.0/README.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Brego SDK for Python
|
|
2
|
+
|
|
3
|
+
```bash
|
|
4
|
+
pip install brego
|
|
5
|
+
```
|
|
6
|
+
|
|
7
|
+
The partner connect flow for Python 3.8 or later, standard library only:
|
|
8
|
+
PKCE and the authorise URL, code exchange, thread-safe refresh, revoke, API
|
|
9
|
+
calls and webhook signature checks.
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from brego import BregoPartnerClient, create_pkce, create_state
|
|
13
|
+
|
|
14
|
+
brego = BregoPartnerClient(client_id, client_secret, token_store)
|
|
15
|
+
verifier, challenge = create_pkce()
|
|
16
|
+
state = create_state()
|
|
17
|
+
url = brego.authorize_url(redirect_uri, state, challenge, scopes=["api:vehicle:read"])
|
|
18
|
+
|
|
19
|
+
# In your callback, after checking state:
|
|
20
|
+
connection = brego.exchange_code(code, redirect_uri, verifier)
|
|
21
|
+
info = brego.get_connection(connection.connection_id)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`token_store` needs `get(connection_id)`, `set(tokens)` and
|
|
25
|
+
`delete(connection_id)`, which `revoke` calls once the connection is ended. Store the newest
|
|
26
|
+
refresh token after every refresh. Refresh tokens are single use: if several
|
|
27
|
+
processes share the store, also give it `with_lock(connection_id, fn)`, which
|
|
28
|
+
runs `fn` while holding a lock they all respect (a database row lock, for
|
|
29
|
+
example) and returns its result, so only one of them refreshes at a time. `request` refreshes the access token before it expires and
|
|
30
|
+
raises `BregoApiError` on a `403`: if `get_connection` also fails, refresh
|
|
31
|
+
once, and ask the organisation to connect again if that fails too.
|
|
32
|
+
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
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.
|
|
36
|
+
|
|
37
|
+
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,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
|
+
]
|
|
@@ -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 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
brego
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "brego"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Brego API client for partner apps: OAuth connect flow, token refresh and webhook signature checks."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.8"
|
|
7
|
+
dependencies = []
|
|
8
|
+
|
|
9
|
+
[build-system]
|
|
10
|
+
requires = ["setuptools>=68"]
|
|
11
|
+
build-backend = "setuptools.build_meta"
|
|
12
|
+
|
|
13
|
+
[tool.setuptools]
|
|
14
|
+
packages = ["brego"]
|
brego-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
from brego import (
|
|
10
|
+
BregoApiError,
|
|
11
|
+
BregoOAuthError,
|
|
12
|
+
BregoPartnerClient,
|
|
13
|
+
BregoTokenCheckError,
|
|
14
|
+
BregoTokensRefusedError,
|
|
15
|
+
BregoTokenStoreError,
|
|
16
|
+
ConnectionTokens,
|
|
17
|
+
create_pkce,
|
|
18
|
+
verify_webhook_signature,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class MemoryStore:
|
|
23
|
+
def __init__(self):
|
|
24
|
+
self.tokens = {}
|
|
25
|
+
|
|
26
|
+
def get(self, connection_id):
|
|
27
|
+
return self.tokens.get(connection_id)
|
|
28
|
+
|
|
29
|
+
def set(self, tokens):
|
|
30
|
+
self.tokens[tokens.connection_id] = tokens
|
|
31
|
+
|
|
32
|
+
def delete(self, connection_id):
|
|
33
|
+
self.tokens.pop(connection_id, None)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _locked(lock, fn):
|
|
37
|
+
with lock:
|
|
38
|
+
return fn()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def token_body(n):
|
|
42
|
+
return json.dumps(
|
|
43
|
+
{
|
|
44
|
+
"access_token": f"bat_live_{n}",
|
|
45
|
+
"refresh_token": f"brt_live_{n}",
|
|
46
|
+
"expires_in": 3600,
|
|
47
|
+
"scope": "api:vehicle:read",
|
|
48
|
+
"connection_id": "c1",
|
|
49
|
+
"organization_id": "o1",
|
|
50
|
+
}
|
|
51
|
+
).encode()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ClientTest(unittest.TestCase):
|
|
55
|
+
def test_pkce_and_authorize_url(self):
|
|
56
|
+
verifier, challenge = create_pkce()
|
|
57
|
+
import base64
|
|
58
|
+
|
|
59
|
+
expected = (
|
|
60
|
+
base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
|
|
61
|
+
.rstrip(b"=")
|
|
62
|
+
.decode()
|
|
63
|
+
)
|
|
64
|
+
self.assertEqual(challenge, expected)
|
|
65
|
+
client = BregoPartnerClient("pca_x", "pcs_x", MemoryStore())
|
|
66
|
+
url = client.authorize_url("https://app.example.com/cb", "s", challenge)
|
|
67
|
+
self.assertTrue(url.startswith("https://api.brego.io/v1/oauth/authorize?"))
|
|
68
|
+
self.assertIn("code_challenge_method=S256", url)
|
|
69
|
+
|
|
70
|
+
def test_older_exchange_does_not_overwrite_newer_tokens(self):
|
|
71
|
+
store = MemoryStore()
|
|
72
|
+
|
|
73
|
+
def transport(method, url, headers, body):
|
|
74
|
+
if url.endswith("/v1/oauth/token"):
|
|
75
|
+
return 200, token_body(2 if b"newer" in body else 1)
|
|
76
|
+
if headers["Authorization"] == "Bearer bat_live_2":
|
|
77
|
+
return 200, b'{"connectionId": "c1"}'
|
|
78
|
+
return (
|
|
79
|
+
403,
|
|
80
|
+
b'{"message": "The access token is invalid, expired or revoked. Refresh it."}',
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
84
|
+
client.exchange_code("newer", "https://app.example.com/cb", "v")
|
|
85
|
+
result = client.exchange_code("older", "https://app.example.com/cb", "v")
|
|
86
|
+
self.assertEqual(result.access_token, "bat_live_2")
|
|
87
|
+
self.assertEqual(store.get("c1").access_token, "bat_live_2")
|
|
88
|
+
|
|
89
|
+
def test_a_suspended_app_does_not_prove_stored_tokens_old(self):
|
|
90
|
+
store = MemoryStore()
|
|
91
|
+
calls = {"token": 0}
|
|
92
|
+
|
|
93
|
+
def transport(method, url, headers, body):
|
|
94
|
+
if url.endswith("/v1/oauth/token"):
|
|
95
|
+
calls["token"] += 1
|
|
96
|
+
return 200, token_body(calls["token"])
|
|
97
|
+
return 403, b'{"message": "This partner app is suspended."}'
|
|
98
|
+
|
|
99
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
100
|
+
client.exchange_code("newer", "https://app.example.com/cb", "v")
|
|
101
|
+
with self.assertRaises(BregoTokenCheckError):
|
|
102
|
+
client.exchange_code("older", "https://app.example.com/cb", "v")
|
|
103
|
+
self.assertEqual(store.get("c1").access_token, "bat_live_1")
|
|
104
|
+
|
|
105
|
+
def test_exchange_saves_nothing_when_both_sets_are_refused(self):
|
|
106
|
+
store = MemoryStore()
|
|
107
|
+
calls = {"token": 0}
|
|
108
|
+
|
|
109
|
+
def transport(method, url, headers, body):
|
|
110
|
+
if url.endswith("/v1/oauth/token"):
|
|
111
|
+
calls["token"] += 1
|
|
112
|
+
return 200, token_body(calls["token"])
|
|
113
|
+
return 401, b'{"message": "Unauthorised"}'
|
|
114
|
+
|
|
115
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
116
|
+
client.exchange_code("first", "https://app.example.com/cb", "v")
|
|
117
|
+
with self.assertRaises(BregoTokensRefusedError):
|
|
118
|
+
client.exchange_code("second", "https://app.example.com/cb", "v")
|
|
119
|
+
self.assertEqual(store.get("c1").access_token, "bat_live_1")
|
|
120
|
+
|
|
121
|
+
def test_exchange_overwrites_nothing_when_it_cannot_check(self):
|
|
122
|
+
store = MemoryStore()
|
|
123
|
+
calls = {"token": 0}
|
|
124
|
+
|
|
125
|
+
def transport(method, url, headers, body):
|
|
126
|
+
if url.endswith("/v1/oauth/token"):
|
|
127
|
+
calls["token"] += 1
|
|
128
|
+
return 200, token_body(calls["token"])
|
|
129
|
+
raise OSError("network down")
|
|
130
|
+
|
|
131
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
132
|
+
client.exchange_code("newer", "https://app.example.com/cb", "v")
|
|
133
|
+
with self.assertRaises(BregoTokenCheckError) as raised:
|
|
134
|
+
client.exchange_code("older", "https://app.example.com/cb", "v")
|
|
135
|
+
self.assertEqual(raised.exception.tokens.access_token, "bat_live_2")
|
|
136
|
+
self.assertEqual(raised.exception.stored.access_token, "bat_live_1")
|
|
137
|
+
self.assertEqual(store.get("c1").access_token, "bat_live_1")
|
|
138
|
+
|
|
139
|
+
def test_revoke_removes_the_connections_tokens(self):
|
|
140
|
+
store = MemoryStore()
|
|
141
|
+
|
|
142
|
+
def transport(method, url, headers, body):
|
|
143
|
+
if url.endswith("/v1/oauth/revoke"):
|
|
144
|
+
return 200, b""
|
|
145
|
+
return 200, token_body(1)
|
|
146
|
+
|
|
147
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
148
|
+
client.exchange_code("code", "https://app.example.com/cb", "v")
|
|
149
|
+
client.revoke("c1")
|
|
150
|
+
self.assertIsNone(store.get("c1"))
|
|
151
|
+
|
|
152
|
+
def test_revoke_waits_for_a_refresh_in_progress(self):
|
|
153
|
+
store = MemoryStore()
|
|
154
|
+
refresh_started = threading.Event()
|
|
155
|
+
release_refresh = threading.Event()
|
|
156
|
+
|
|
157
|
+
def transport(method, url, headers, body):
|
|
158
|
+
if url.endswith("/v1/oauth/revoke"):
|
|
159
|
+
return 200, b""
|
|
160
|
+
if b"refresh_token" in body:
|
|
161
|
+
refresh_started.set()
|
|
162
|
+
release_refresh.wait(5)
|
|
163
|
+
return 200, token_body(2)
|
|
164
|
+
return 200, token_body(1)
|
|
165
|
+
|
|
166
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
167
|
+
client.exchange_code("code", "https://app.example.com/cb", "v")
|
|
168
|
+
refresher = threading.Thread(target=lambda: client.refresh("c1"))
|
|
169
|
+
refresher.start()
|
|
170
|
+
refresh_started.wait(5)
|
|
171
|
+
revoker = threading.Thread(target=lambda: client.revoke("c1"))
|
|
172
|
+
revoker.start()
|
|
173
|
+
release_refresh.set()
|
|
174
|
+
refresher.join(5)
|
|
175
|
+
revoker.join(5)
|
|
176
|
+
self.assertIsNone(store.get("c1"))
|
|
177
|
+
|
|
178
|
+
def test_exchange_then_refresh_expiring_token_once(self):
|
|
179
|
+
store = MemoryStore()
|
|
180
|
+
refreshes = []
|
|
181
|
+
|
|
182
|
+
def transport(method, url, headers, body):
|
|
183
|
+
if url.endswith("/v1/oauth/token"):
|
|
184
|
+
if b"refresh_token" in body:
|
|
185
|
+
refreshes.append(1)
|
|
186
|
+
return 200, token_body(2)
|
|
187
|
+
return 200, token_body(1)
|
|
188
|
+
if headers["Authorization"] == "Bearer bat_live_2":
|
|
189
|
+
return 200, b'{"connectionId": "c1"}'
|
|
190
|
+
return 403, b'{"message": "Forbidden"}'
|
|
191
|
+
|
|
192
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
193
|
+
client.exchange_code("code", "https://app.example.com/cb", "v")
|
|
194
|
+
self.assertEqual(store.get("c1").refresh_token, "brt_live_1")
|
|
195
|
+
store.set(dataclasses.replace(store.get("c1"), expires_at=time.time()))
|
|
196
|
+
|
|
197
|
+
results = []
|
|
198
|
+
threads = [
|
|
199
|
+
threading.Thread(target=lambda: results.append(client.get_connection("c1")))
|
|
200
|
+
for _ in range(3)
|
|
201
|
+
]
|
|
202
|
+
for thread in threads:
|
|
203
|
+
thread.start()
|
|
204
|
+
for thread in threads:
|
|
205
|
+
thread.join()
|
|
206
|
+
self.assertEqual(results, [{"connectionId": "c1"}] * 3)
|
|
207
|
+
self.assertEqual(len(refreshes), 1)
|
|
208
|
+
|
|
209
|
+
def test_drops_a_connections_refresh_lock_once_no_refresh_uses_it(self):
|
|
210
|
+
store = MemoryStore()
|
|
211
|
+
|
|
212
|
+
def transport(method, url, headers, body):
|
|
213
|
+
if b"refresh_token" in body:
|
|
214
|
+
return 200, token_body(2)
|
|
215
|
+
return 200, token_body(1)
|
|
216
|
+
|
|
217
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
218
|
+
client.exchange_code("code", "https://app.example.com/cb", "v")
|
|
219
|
+
client.refresh("c1")
|
|
220
|
+
self.assertEqual(client._locks, {})
|
|
221
|
+
|
|
222
|
+
def test_refreshes_once_across_clients_sharing_a_store_with_a_lock(self):
|
|
223
|
+
store = MemoryStore()
|
|
224
|
+
shared_lock = threading.Lock()
|
|
225
|
+
store.with_lock = lambda connection_id, fn: _locked(shared_lock, fn)
|
|
226
|
+
refreshes = []
|
|
227
|
+
|
|
228
|
+
def transport(method, url, headers, body):
|
|
229
|
+
refreshes.append(1)
|
|
230
|
+
time.sleep(0.01)
|
|
231
|
+
return 200, token_body(len(refreshes) + 1)
|
|
232
|
+
|
|
233
|
+
store.set(
|
|
234
|
+
ConnectionTokens(
|
|
235
|
+
access_token="bat_live_old",
|
|
236
|
+
refresh_token="brt_live_old",
|
|
237
|
+
expires_at=time.time(),
|
|
238
|
+
scope=[],
|
|
239
|
+
connection_id="c1",
|
|
240
|
+
organization_id="o1",
|
|
241
|
+
)
|
|
242
|
+
)
|
|
243
|
+
results = []
|
|
244
|
+
clients = [
|
|
245
|
+
BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
246
|
+
for _ in range(2)
|
|
247
|
+
]
|
|
248
|
+
threads = [
|
|
249
|
+
threading.Thread(target=lambda c=c: results.append(c.refresh("c1")))
|
|
250
|
+
for c in clients
|
|
251
|
+
]
|
|
252
|
+
for thread in threads:
|
|
253
|
+
thread.start()
|
|
254
|
+
for thread in threads:
|
|
255
|
+
thread.join()
|
|
256
|
+
self.assertEqual(len(refreshes), 1)
|
|
257
|
+
self.assertEqual([r.refresh_token for r in results], ["brt_live_2"] * 2)
|
|
258
|
+
|
|
259
|
+
def test_refuses_off_api_paths_and_non_2xx_responses(self):
|
|
260
|
+
store = MemoryStore()
|
|
261
|
+
store.set(
|
|
262
|
+
ConnectionTokens(
|
|
263
|
+
access_token="bat_live_1",
|
|
264
|
+
refresh_token="brt_live_1",
|
|
265
|
+
expires_at=time.time() + 3600,
|
|
266
|
+
scope=[],
|
|
267
|
+
connection_id="c1",
|
|
268
|
+
organization_id="o1",
|
|
269
|
+
)
|
|
270
|
+
)
|
|
271
|
+
calls = []
|
|
272
|
+
|
|
273
|
+
def transport(method, url, headers, body):
|
|
274
|
+
calls.append(url)
|
|
275
|
+
return 302, b'{"location": "https://elsewhere.example.com"}'
|
|
276
|
+
|
|
277
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
278
|
+
for path in ["https://evil.example.com/x", "//evil.example.com", "@evil.example.com/x"]:
|
|
279
|
+
with self.assertRaises(ValueError):
|
|
280
|
+
client.request("c1", "GET", path)
|
|
281
|
+
self.assertEqual(calls, [])
|
|
282
|
+
with self.assertRaises(BregoApiError) as caught:
|
|
283
|
+
client.request("c1", "GET", "/v1/oauth/connection")
|
|
284
|
+
self.assertEqual(caught.exception.status, 302)
|
|
285
|
+
|
|
286
|
+
def test_returns_issued_tokens_when_the_store_cannot_save_them(self):
|
|
287
|
+
attempts = []
|
|
288
|
+
|
|
289
|
+
class FailingStore:
|
|
290
|
+
def get(self, connection_id):
|
|
291
|
+
return None
|
|
292
|
+
|
|
293
|
+
def set(self, tokens):
|
|
294
|
+
attempts.append(1)
|
|
295
|
+
raise RuntimeError("database down")
|
|
296
|
+
|
|
297
|
+
client = BregoPartnerClient(
|
|
298
|
+
"pca_x",
|
|
299
|
+
"pcs_x",
|
|
300
|
+
FailingStore(),
|
|
301
|
+
transport=lambda method, url, headers, body: (200, token_body(1)),
|
|
302
|
+
)
|
|
303
|
+
with self.assertRaises(BregoTokenStoreError) as caught:
|
|
304
|
+
client.exchange_code("code", "https://app.example.com/cb", "v")
|
|
305
|
+
self.assertEqual(caught.exception.tokens.refresh_token, "brt_live_1")
|
|
306
|
+
self.assertEqual(len(attempts), 3)
|
|
307
|
+
|
|
308
|
+
def test_errors(self):
|
|
309
|
+
store = MemoryStore()
|
|
310
|
+
|
|
311
|
+
def transport(method, url, headers, body):
|
|
312
|
+
if url.endswith("/v1/oauth/token"):
|
|
313
|
+
return 400, b'{"error": "invalid_grant"}'
|
|
314
|
+
return 403, b'{"message": "Forbidden"}'
|
|
315
|
+
|
|
316
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
317
|
+
with self.assertRaises(BregoOAuthError) as caught:
|
|
318
|
+
client.exchange_code("x", "r", "v")
|
|
319
|
+
self.assertEqual(caught.exception.code, "invalid_grant")
|
|
320
|
+
store.set(ConnectionTokens("a", "r", 9e12, "c1", "o1"))
|
|
321
|
+
with self.assertRaises(BregoApiError) as api_error:
|
|
322
|
+
client.request("c1", "GET", "/v1/vehicles")
|
|
323
|
+
self.assertEqual(api_error.exception.status, 403)
|
|
324
|
+
|
|
325
|
+
def test_array_query_parameters_repeat(self):
|
|
326
|
+
store = MemoryStore()
|
|
327
|
+
store.set(ConnectionTokens("a", "r", 9e12, "c1", "o1"))
|
|
328
|
+
urls = []
|
|
329
|
+
|
|
330
|
+
def transport(method, url, headers, body):
|
|
331
|
+
urls.append(url)
|
|
332
|
+
return 200, b"{}"
|
|
333
|
+
|
|
334
|
+
client = BregoPartnerClient("pca_x", "pcs_x", store, transport=transport)
|
|
335
|
+
client.request(
|
|
336
|
+
"c1",
|
|
337
|
+
"GET",
|
|
338
|
+
"/v1/vehicles/vrm/DE21AAA",
|
|
339
|
+
query={
|
|
340
|
+
"expand": ["metadata", "mots"],
|
|
341
|
+
"countryCode": "gb",
|
|
342
|
+
"isValuation": True,
|
|
343
|
+
"skip": None,
|
|
344
|
+
},
|
|
345
|
+
)
|
|
346
|
+
self.assertEqual(
|
|
347
|
+
urls[0],
|
|
348
|
+
"https://api.brego.io/v1/vehicles/vrm/DE21AAA"
|
|
349
|
+
"?expand=metadata&expand=mots&countryCode=gb&isValuation=true",
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
def test_webhook_signature(self):
|
|
353
|
+
body = b'{"event":"connection.created"}'
|
|
354
|
+
t = 1763720100000
|
|
355
|
+
|
|
356
|
+
def sign(secret):
|
|
357
|
+
return hmac.new(
|
|
358
|
+
secret.encode(), f"{t}.".encode() + body, hashlib.sha256
|
|
359
|
+
).hexdigest()
|
|
360
|
+
|
|
361
|
+
header = f"t={t},v1={sign('old')},v1={sign('new')}"
|
|
362
|
+
self.assertTrue(verify_webhook_signature(header, body, "new", now_ms=t))
|
|
363
|
+
self.assertTrue(verify_webhook_signature(header, body, "old", now_ms=t))
|
|
364
|
+
self.assertFalse(verify_webhook_signature(header, body, "nope", now_ms=t))
|
|
365
|
+
self.assertFalse(
|
|
366
|
+
verify_webhook_signature(header, body, "new", now_ms=t + 600000)
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
if __name__ == "__main__":
|
|
371
|
+
unittest.main()
|