cellpy-connectors 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Pluggable connectors for cellpy."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,305 @@
1
+ """BatBase connector: OAuth2 client-credentials transport and a read passthrough.
2
+
3
+ BatBase (IFE's Django app for cell-testing metadata) mounts django-oauth-toolkit
4
+ at ``/o/`` and a DRF API at ``/api/``. Scripts authenticate with the
5
+ client-credentials grant: ``POST /o/token/`` with the client id/secret as HTTP
6
+ Basic auth, then ``Authorization: Bearer <token>`` on every API call. Tokens
7
+ are short-lived and there is no refresh token, so this client caches the token
8
+ in memory and fetches a fresh one when it expires or is rejected.
9
+
10
+ Credentials follow the connector-base precedence: explicit argument, then
11
+ ``CELLPY_BATBASE_CLIENT_ID`` / ``CELLPY_BATBASE_CLIENT_SECRET``, then the OS
12
+ keyring (filled by ``cellpy connectors configure batbase``). The host comes
13
+ from the ``base_url`` argument, else ``CELLPY_BATBASE_URL``, else the local
14
+ dev server. A local dev server accepts anonymous reads; pass
15
+ ``anonymous=True`` to skip authentication there.
16
+
17
+ Examples:
18
+ ```python
19
+ from cellpy_connectors.batbase import BatBaseClient
20
+
21
+ bb = BatBaseClient("https://d1-odin-01.ad.ife.no")
22
+ tags = bb.get("test-cellpy-tag", search="SAL_010")
23
+ for row in bb.get_all("project"):
24
+ print(row["name"])
25
+ ```
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import os
31
+ import time
32
+ from collections.abc import Iterator
33
+ from dataclasses import dataclass
34
+ from typing import Any
35
+
36
+ import requests
37
+ from pydantic import SecretStr
38
+
39
+ from cellpy_connectors.client import ApiClientBase, SupportsRequest, _raise_for_status
40
+ from cellpy_connectors.credentials import CredentialField, resolve_secret
41
+ from cellpy_connectors.errors import (
42
+ ConnectorAuthError,
43
+ ConnectorCredentialsError,
44
+ ConnectorError,
45
+ )
46
+ from cellpy_connectors.registry import ConnectorSpec, register
47
+
48
+ CONNECTOR_NAME = "batbase"
49
+ DEFAULT_URL = "http://localhost:8000"
50
+ URL_ENV_VAR = "CELLPY_BATBASE_URL"
51
+ # A bearer token issued elsewhere (e.g. by a BatBase worker for one job).
52
+ # Used as is: no client credentials, no refresh.
53
+ TOKEN_ENV_VAR = "CELLPY_BATBASE_TOKEN"
54
+ TOKEN_PATH = "o/token/"
55
+ API_PREFIX = "api/"
56
+ DEFAULT_SCOPE = "read"
57
+
58
+ #: Seconds before ``expires_in`` elapses at which the token is treated as stale.
59
+ EXPIRY_MARGIN = 60.0
60
+
61
+ _KEYRING_SERVICE = "cellpy-connectors/batbase"
62
+
63
+ CLIENT_ID_FIELD = CredentialField(
64
+ name="BatBase client id",
65
+ env_var="CELLPY_BATBASE_CLIENT_ID",
66
+ keyring_service=_KEYRING_SERVICE,
67
+ keyring_username="client_id",
68
+ prompt="BatBase client id",
69
+ )
70
+ CLIENT_SECRET_FIELD = CredentialField(
71
+ name="BatBase client secret",
72
+ env_var="CELLPY_BATBASE_CLIENT_SECRET",
73
+ keyring_service=_KEYRING_SERVICE,
74
+ keyring_username="client_secret",
75
+ prompt="BatBase client secret",
76
+ )
77
+
78
+ SPEC = ConnectorSpec(name=CONNECTOR_NAME, fields=(CLIENT_ID_FIELD, CLIENT_SECRET_FIELD))
79
+ register(SPEC)
80
+
81
+
82
+ class BatBaseAuthError(ConnectorAuthError):
83
+ """No BatBase credentials are configured, or BatBase rejected them."""
84
+
85
+
86
+ @dataclass(frozen=True, slots=True)
87
+ class _Token:
88
+ access_token: str
89
+ expires_at: float # time.monotonic() seconds
90
+
91
+ def is_fresh(self, now: float) -> bool:
92
+ return now < self.expires_at - EXPIRY_MARGIN
93
+
94
+
95
+ def resolve_base_url(base_url: str | None = None) -> str:
96
+ """``base_url`` argument, else ``CELLPY_BATBASE_URL``, else the dev server."""
97
+ return (base_url or os.environ.get(URL_ENV_VAR) or DEFAULT_URL).rstrip("/")
98
+
99
+
100
+ def api_path(endpoint: str) -> str:
101
+ """Normalise ``endpoint`` to a DRF path under ``api/``.
102
+
103
+ ``"test-cellpy-tag"``, ``"/test-cellpy-tag/"`` and ``"api/test-cellpy-tag"``
104
+ all give ``"api/test-cellpy-tag/"``. A trailing slash is added because DRF
105
+ routers redirect without it. Query strings are left alone.
106
+ """
107
+ path, sep, query = endpoint.partition("?")
108
+ path = path.strip().lstrip("/")
109
+ if not path.startswith(API_PREFIX.rstrip("/")):
110
+ path = API_PREFIX + path
111
+ if not path.endswith("/"):
112
+ path += "/"
113
+ return path + sep + query
114
+
115
+
116
+ class BatBaseClient(ApiClientBase):
117
+ """HTTP client for the BatBase API with transparent bearer-token handling.
118
+
119
+ Args:
120
+ base_url: BatBase host (scheme + host [+ port]); see `resolve_base_url`.
121
+ client_id / client_secret: explicit credentials; normally left ``None``
122
+ so the environment or the keyring is used.
123
+ scope: OAuth2 scope requested for the token. ``"read"`` by default;
124
+ ``"read write"`` needs membership of BatBase's ``api-write`` group.
125
+ anonymous: skip authentication entirely (local dev server).
126
+ access_token: a bearer token issued elsewhere; default
127
+ ``$CELLPY_BATBASE_TOKEN``. When set, client credentials are not
128
+ used and the token is never refreshed.
129
+ timeout / session: see `ApiClientBase`.
130
+
131
+ Raises:
132
+ BatBaseAuthError: on the first authenticated request when no
133
+ credentials are configured, or when BatBase rejects them.
134
+ """
135
+
136
+ health_path = API_PREFIX
137
+
138
+ def __init__(
139
+ self,
140
+ base_url: str | None = None,
141
+ *,
142
+ client_id: str | SecretStr | None = None,
143
+ client_secret: str | SecretStr | None = None,
144
+ scope: str = DEFAULT_SCOPE,
145
+ anonymous: bool = False,
146
+ access_token: str | None = None,
147
+ timeout: float = 10.0,
148
+ session: SupportsRequest | None = None,
149
+ clock=time.monotonic,
150
+ ) -> None:
151
+ super().__init__(resolve_base_url(base_url), timeout=timeout, session=session)
152
+ self._static_token = access_token or os.environ.get(TOKEN_ENV_VAR) or None
153
+ self._client_id = client_id
154
+ self._client_secret = client_secret
155
+ self.scope = scope
156
+ self.anonymous = anonymous
157
+ self._clock = clock
158
+ self._token: _Token | None = None
159
+
160
+ # -- auth -------------------------------------------------------------
161
+ def credentials(self) -> tuple[SecretStr, SecretStr]:
162
+ """Resolved (client id, client secret). Raises `BatBaseAuthError` if unset."""
163
+ try:
164
+ client_id = resolve_secret(self._client_id, CLIENT_ID_FIELD)
165
+ client_secret = resolve_secret(self._client_secret, CLIENT_SECRET_FIELD)
166
+ except ConnectorCredentialsError as exc:
167
+ raise BatBaseAuthError(
168
+ "No BatBase credentials configured. Create an API client in BatBase "
169
+ "(user menu -> API credentials), then run "
170
+ "`cellpy connectors configure batbase` or set "
171
+ f"{CLIENT_ID_FIELD.env_var} and {CLIENT_SECRET_FIELD.env_var}."
172
+ ) from exc
173
+ return client_id, client_secret
174
+
175
+ def fetch_token(self) -> str:
176
+ """Request a new access token from ``o/token/`` and cache it."""
177
+ client_id, client_secret = self.credentials()
178
+ url = self.base_url + TOKEN_PATH
179
+ try:
180
+ response = self.session.request(
181
+ "POST",
182
+ url,
183
+ auth=(client_id.get_secret_value(), client_secret.get_secret_value()),
184
+ data={"grant_type": "client_credentials", "scope": self.scope},
185
+ timeout=self.timeout,
186
+ )
187
+ except requests.RequestException as exc:
188
+ raise ConnectorError(f"Token request to {url} failed: {exc}") from exc
189
+ if response.status_code in (400, 401, 403):
190
+ raise BatBaseAuthError(
191
+ f"BatBase rejected the client credentials at {url} "
192
+ f"({response.status_code}): {(response.text or '').strip()[:200]}. "
193
+ "Check the client id/secret (rotate it in BatBase if lost) and "
194
+ f"that the scope {self.scope!r} is allowed for your user."
195
+ )
196
+ _raise_for_status(response)
197
+ try:
198
+ payload = response.json()
199
+ access_token = payload["access_token"]
200
+ expires_in = float(payload.get("expires_in", 36000))
201
+ except (ValueError, KeyError, TypeError) as exc:
202
+ raise ConnectorError(f"Unexpected token response from {url}: {exc}") from exc
203
+ self._token = _Token(access_token, self._clock() + expires_in)
204
+ return access_token
205
+
206
+ def token(self) -> str:
207
+ """A fresh access token (cached until close to expiry)."""
208
+ if self._static_token:
209
+ return self._static_token
210
+ now = self._clock()
211
+ if self._token is not None and self._token.is_fresh(now):
212
+ return self._token.access_token
213
+ return self.fetch_token()
214
+
215
+ def invalidate_token(self) -> None:
216
+ """Forget the cached token so the next call fetches a new one."""
217
+ self._token = None
218
+
219
+ # -- transport --------------------------------------------------------
220
+ def request(self, method: str, path: str, **kwargs: Any) -> requests.Response:
221
+ """Send ``method`` to ``path`` with a bearer token; re-auth once on 401."""
222
+ return self._request(method, path, retry_auth=True, **kwargs)
223
+
224
+ def _request(self, method: str, path: str, *, retry_auth: bool, **kwargs: Any) -> requests.Response:
225
+ url = self.base_url + path.lstrip("/") # base_url always ends with "/"
226
+ headers = dict(kwargs.pop("headers", None) or {})
227
+ if not self.anonymous:
228
+ headers["Authorization"] = f"Bearer {self.token()}"
229
+ kwargs.setdefault("timeout", self.timeout)
230
+ try:
231
+ response = self.session.request(method, url, headers=headers, **kwargs)
232
+ except requests.RequestException as exc:
233
+ raise ConnectorError(f"Request to {url} failed: {exc}") from exc
234
+ if response.status_code == 401 and not self.anonymous and retry_auth and not self._static_token:
235
+ # Token revoked or the secret rotated mid-session: one fresh token, one retry.
236
+ self.invalidate_token()
237
+ return self._request(method, path, retry_auth=False, **kwargs)
238
+ if response.status_code in (401, 403):
239
+ hint = " (anonymous access; this host requires a token)" if self.anonymous else ""
240
+ raise BatBaseAuthError(
241
+ f"BatBase refused {method} {url} ({response.status_code}){hint}: "
242
+ f"{(response.text or '').strip()[:200]}"
243
+ )
244
+ return _raise_for_status(response)
245
+
246
+ # -- read passthrough -------------------------------------------------
247
+ def get(self, endpoint: str, **params: Any) -> Any:
248
+ """GET one API endpoint and return the decoded JSON.
249
+
250
+ ``endpoint`` is a resource under ``api/`` (``"test-cellpy-tag"``,
251
+ ``"project/12"``); keyword arguments become the query string
252
+ (``search="SAL"``, ``page=2``). Returns whatever the endpoint returns —
253
+ a DRF page (``{"count", "next", "previous", "results"}``), a list, or
254
+ one object.
255
+ """
256
+ response = self.request("GET", api_path(endpoint), params=params or None)
257
+ try:
258
+ return response.json()
259
+ except ValueError as exc:
260
+ raise ConnectorError(f"Non-JSON response from {response.url}") from exc
261
+
262
+ def post(self, endpoint: str, payload: Any) -> Any:
263
+ """POST JSON to one API endpoint and return the decoded JSON.
264
+
265
+ Needs a token with the ``write`` scope (``scope="read write"``). Not
266
+ retried: BatBase writes are not all idempotent.
267
+ """
268
+ response = self.request("POST", api_path(endpoint), json=payload)
269
+ try:
270
+ return response.json()
271
+ except ValueError as exc:
272
+ raise ConnectorError(f"Non-JSON response from {response.url}") from exc
273
+
274
+ def get_all(self, endpoint: str, **params: Any) -> list[Any]:
275
+ """GET every row of a list endpoint, following DRF pagination."""
276
+ return list(self.iter_rows(endpoint, **params))
277
+
278
+ def iter_rows(self, endpoint: str, **params: Any) -> Iterator[Any]:
279
+ """Yield rows of a list endpoint page by page."""
280
+ payload = self.get(endpoint, **params)
281
+ while True:
282
+ if isinstance(payload, list):
283
+ yield from payload
284
+ return
285
+ if not isinstance(payload, dict) or "results" not in payload:
286
+ yield payload
287
+ return
288
+ yield from payload["results"]
289
+ next_url = payload.get("next")
290
+ if not next_url:
291
+ return
292
+ # ``next`` is absolute and already carries the query string.
293
+ path = next_url.split(self.base_url, 1)[-1] if next_url.startswith(self.base_url) else next_url
294
+ response = self.request("GET", path)
295
+ payload = response.json()
296
+
297
+ def whoami(self) -> dict[str, Any]:
298
+ """Token + connection check: GET ``api/`` and report what worked."""
299
+ response = self.check_connection()
300
+ return {
301
+ "url": self.base_url,
302
+ "status": response.status_code,
303
+ "authenticated": not self.anonymous,
304
+ "scope": None if self.anonymous else self.scope,
305
+ }