openbadgefactory 0.1.0a1__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,43 @@
1
+ """Unofficial Python client for the Open Badge Factory REST API."""
2
+
3
+ from ._client import AsyncClient, Client
4
+ from ._spec import API_SPEC_VERSION
5
+ from ._version import __version__
6
+ from .exceptions import (
7
+ APIConnectionError,
8
+ APIError,
9
+ APITimeoutError,
10
+ AuthenticationError,
11
+ BadRequestError,
12
+ NotFoundError,
13
+ OBFError,
14
+ PermissionDeniedError,
15
+ RateLimitError,
16
+ ResponseValidationError,
17
+ ServerError,
18
+ )
19
+ from .models import Badge, Event, Evidence, OperationResult, Page, Recipient
20
+
21
+ __all__ = [
22
+ "API_SPEC_VERSION",
23
+ "APIConnectionError",
24
+ "APIError",
25
+ "APITimeoutError",
26
+ "AsyncClient",
27
+ "AuthenticationError",
28
+ "BadRequestError",
29
+ "Badge",
30
+ "Client",
31
+ "Event",
32
+ "Evidence",
33
+ "NotFoundError",
34
+ "OBFError",
35
+ "OperationResult",
36
+ "Page",
37
+ "PermissionDeniedError",
38
+ "RateLimitError",
39
+ "Recipient",
40
+ "ResponseValidationError",
41
+ "ServerError",
42
+ "__version__",
43
+ ]
@@ -0,0 +1,218 @@
1
+ """OAuth2 *client credentials* authentication for httpx.
2
+
3
+ The access token is requested on the first API call, cached, and renewed
4
+ shortly before it expires. If the API still answers 401 (e.g. the token was
5
+ revoked), the token is renewed once and the request sent again.
6
+
7
+ Credentials travel only in the form body of the token request: OBF documents
8
+ HTTP Basic auth too, but it does not work in practice.
9
+
10
+ One :class:`ClientCredentialsAuth` serves both the sync and the async client:
11
+ locks make concurrent requests share a single token renewal.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import threading
17
+ import time
18
+ from dataclasses import dataclass
19
+ from typing import TYPE_CHECKING
20
+
21
+ import anyio
22
+ import httpx
23
+ from pydantic import SecretStr
24
+
25
+ from . import exceptions as exc
26
+ from ._generated import OAuth2AccessToken
27
+ from ._response import decode_body, parse_model, raise_for_status
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import AsyncGenerator, Callable, Generator, Mapping
31
+
32
+ __all__ = ["TOKEN_PATH", "ClientCredentialsAuth"]
33
+
34
+ TOKEN_PATH = "/v2/client/oauth2/token" # noqa: S105 - a URL path, not a secret
35
+
36
+ #: Renew the token this many seconds before it expires...
37
+ EXPIRY_MARGIN = 60.0
38
+ #: ...but never later than this fraction of its lifetime (for short-lived tokens).
39
+ MAX_MARGIN_FRACTION = 0.5
40
+ #: Lifetime assumed when the token response has no ``expires_in``. Deliberately
41
+ #: short (OBF tokens last hours): renewing early is cheap, using an expired token is not.
42
+ DEFAULT_TOKEN_LIFETIME = 600.0
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class _Token:
47
+ value: SecretStr
48
+ renew_at: float
49
+
50
+ def is_fresh(self, now: float) -> bool:
51
+ return now < self.renew_at
52
+
53
+
54
+ class ClientCredentialsAuth(httpx.Auth):
55
+ """httpx auth flow for the OBF OAuth2 client credentials grant.
56
+
57
+ Args:
58
+ client_id: Your organisation id.
59
+ client_secret: The API secret generated in *Admin tools > API*.
60
+ token_url: Absolute URL of the token endpoint.
61
+ headers: Extra headers for the token request (e.g. ``User-Agent``):
62
+ requests made by an auth flow do not get the client's default headers.
63
+ clock: Monotonic clock, replaceable in tests.
64
+
65
+ """
66
+
67
+ requires_request_body = False
68
+ requires_response_body = False
69
+
70
+ def __init__(
71
+ self,
72
+ client_id: str,
73
+ client_secret: SecretStr,
74
+ token_url: str,
75
+ *,
76
+ headers: Mapping[str, str] | None = None,
77
+ clock: Callable[[], float] = time.monotonic,
78
+ ) -> None:
79
+ self._client_id = client_id
80
+ self._client_secret = client_secret
81
+ self._token_url = token_url
82
+ self._headers = dict(headers or {})
83
+ self._clock = clock
84
+ self._token: _Token | None = None
85
+ self._sync_lock = threading.Lock()
86
+ # anyio.Lock is not bound to an event loop until used, and works with
87
+ # both asyncio and trio (like httpx itself).
88
+ self._async_lock = anyio.Lock()
89
+
90
+ def __repr__(self) -> str: # never expose the secret
91
+ return f"{type(self).__name__}(client_id={self._client_id!r})"
92
+
93
+ def invalidate(self) -> None:
94
+ """Forget the cached token: the next request fetches a new one."""
95
+ self._token = None
96
+
97
+ def _needs_token(self, used: _Token | None = None) -> bool:
98
+ """Tell whether a token must be fetched.
99
+
100
+ ``used`` is the token a request was rejected with: if another request
101
+ already replaced it, the new token is reused instead of fetching yet
102
+ another one.
103
+ """
104
+ token = self._token
105
+
106
+ if token is None:
107
+ return True
108
+
109
+ if used is not None and token is used:
110
+ return True
111
+
112
+ return not token.is_fresh(self._clock())
113
+
114
+ def _token_request(self) -> httpx.Request:
115
+ return httpx.Request(
116
+ "POST",
117
+ self._token_url,
118
+ data={
119
+ "grant_type": "client_credentials",
120
+ "client_id": self._client_id,
121
+ "client_secret": self._client_secret.get_secret_value(),
122
+ },
123
+ headers={**self._headers, "Accept": "application/json"},
124
+ )
125
+
126
+ def _store_token(self, response: httpx.Response) -> None:
127
+ """Validate the token response (body already read) and cache the token."""
128
+ if response.status_code in (400, 401, 403):
129
+ # Rejected credentials: whatever the exact status, for the caller
130
+ # this is an authentication problem.
131
+ raise exc.AuthenticationError(
132
+ "Unable to obtain an access token: check client_id and client_secret",
133
+ status_code=response.status_code,
134
+ body=decode_body(response),
135
+ )
136
+
137
+ raise_for_status(response) # 429, 5xx...: the usual exceptions
138
+
139
+ body = decode_body(response)
140
+ payload = parse_model(body, OAuth2AccessToken)
141
+
142
+ if not payload.access_token:
143
+ raise exc.ResponseValidationError("Token response without access_token", body=body)
144
+
145
+ lifetime = float(payload.expires_in or DEFAULT_TOKEN_LIFETIME)
146
+ margin = min(EXPIRY_MARGIN, lifetime * MAX_MARGIN_FRACTION)
147
+ self._token = _Token(
148
+ value=SecretStr(payload.access_token),
149
+ renew_at=self._clock() + lifetime - margin,
150
+ )
151
+
152
+ def _authorize(self, request: httpx.Request) -> _Token:
153
+ token = self._token
154
+
155
+ if token is None: # pragma: no cover - callers fetch a token first
156
+ raise exc.OBFError("No access token available")
157
+
158
+ request.headers["Authorization"] = f"Bearer {token.value.get_secret_value()}"
159
+
160
+ return token
161
+
162
+ def sync_auth_flow(
163
+ self, request: httpx.Request
164
+ ) -> Generator[httpx.Request, httpx.Response, None]:
165
+ with self._sync_lock:
166
+ if self._needs_token():
167
+ token_response = yield self._token_request()
168
+ token_response.read()
169
+
170
+ self._store_token(token_response)
171
+
172
+ used = self._authorize(request)
173
+
174
+ response = yield request
175
+
176
+ if response.status_code != 401:
177
+ return
178
+
179
+ # Token revoked or expired early: renew it once and retry.
180
+ with self._sync_lock:
181
+ if self._needs_token(used):
182
+ token_response = yield self._token_request()
183
+ token_response.read()
184
+
185
+ self._store_token(token_response)
186
+
187
+ self._authorize(request)
188
+
189
+ yield request
190
+
191
+ async def async_auth_flow(
192
+ self,
193
+ request: httpx.Request,
194
+ ) -> AsyncGenerator[httpx.Request, httpx.Response]:
195
+ async with self._async_lock:
196
+ if self._needs_token():
197
+ token_response = yield self._token_request()
198
+ await token_response.aread()
199
+
200
+ self._store_token(token_response)
201
+
202
+ used = self._authorize(request)
203
+
204
+ response = yield request
205
+
206
+ if response.status_code != 401:
207
+ return
208
+
209
+ async with self._async_lock:
210
+ if self._needs_token(used):
211
+ token_response = yield self._token_request()
212
+ await token_response.aread()
213
+
214
+ self._store_token(token_response)
215
+
216
+ self._authorize(request)
217
+
218
+ yield request
@@ -0,0 +1,310 @@
1
+ """Settings, retry policy and request description shared by both clients.
2
+
3
+ Nothing here performs I/O: the sync and async clients only differ in how they
4
+ send a :class:`RequestSpec` and how they wait between retries.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import random
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar
14
+ from urllib.parse import urlsplit
15
+
16
+ from pydantic import SecretStr
17
+
18
+ from . import exceptions as exc
19
+ from ._auth import TOKEN_PATH, ClientCredentialsAuth
20
+ from ._spec import API_SPEC_VERSION
21
+ from ._version import __version__
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Callable, Mapping
25
+
26
+
27
+ __all__ = [
28
+ "DEFAULT_BASE_URL",
29
+ "DEFAULT_MAX_RETRIES",
30
+ "DEFAULT_MAX_RETRY_AFTER",
31
+ "DEFAULT_TIMEOUT",
32
+ "USER_AGENT",
33
+ "RawBody",
34
+ "RequestSpec",
35
+ "RetryPolicy",
36
+ "Settings",
37
+ ]
38
+
39
+ DEFAULT_BASE_URL = "https://openbadgefactory.com"
40
+ DEFAULT_TIMEOUT = 30.0
41
+ DEFAULT_MAX_RETRIES = 2
42
+ DEFAULT_MAX_RETRY_AFTER = 60.0
43
+
44
+ ENV_CLIENT_ID = "OBF_CLIENT_ID"
45
+ ENV_CLIENT_SECRET = "OBF_CLIENT_SECRET" # noqa: S105 - name of a variable, not a secret
46
+ ENV_BASE_URL = "OBF_BASE_URL"
47
+
48
+ USER_AGENT = f"openbadgefactory-python/{__version__} (obf-api-spec/{API_SPEC_VERSION})"
49
+
50
+ #: Same pattern as the ``id`` schema of the OBF spec. Checking it up front gives
51
+ #: a clear error and guarantees the id can be put in URL paths unescaped.
52
+ _CLIENT_ID_PATTERN = re.compile(r"\w{1,100}", re.ASCII)
53
+
54
+ IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"})
55
+
56
+ T = TypeVar("T")
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class RequestSpec(Generic[T]):
61
+ """A fully described API call: the clients send it, ``parse`` builds the result.
62
+
63
+ ``parse`` receives the decoded body (JSON or text), or a :class:`RawBody`
64
+ when ``raw`` is set, e.g. for images. ``accept`` replaces the default
65
+ ``Accept: application/json`` header. ``idempotent`` overrides the guess
66
+ made from the HTTP method, for endpoints that do not follow HTTP semantics.
67
+ """
68
+
69
+ method: str
70
+ path: str
71
+ parse: Callable[[Any], T]
72
+ params: Mapping[str, Any] | None = None
73
+ json: Any = None
74
+ accept: str | None = None
75
+ raw: bool = False
76
+ idempotent: bool | None = None
77
+
78
+ @property
79
+ def is_idempotent(self) -> bool:
80
+ """Whether sending the request twice has the same effect as sending it once."""
81
+ if self.idempotent is not None:
82
+ return self.idempotent
83
+
84
+ return self.method.upper() in IDEMPOTENT_METHODS
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class RawBody:
89
+ """Undecoded response body, passed to ``RequestSpec.parse`` when ``raw`` is set."""
90
+
91
+ content: bytes
92
+ content_type: str
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class RetryPolicy:
97
+ """When to retry a failed request, and how long to wait.
98
+
99
+ A request is retried only when that cannot cause an operation to happen
100
+ twice: always if it never reached the API, otherwise only for idempotent
101
+ methods, or for 429 (the API refused it without processing it).
102
+
103
+ A ``Retry-After`` sent by the API is always honoured exactly: retrying
104
+ earlier would only hit the limit again. If it asks to wait longer than
105
+ ``max_retry_after``, the error is raised instead of blocking the caller.
106
+ """
107
+
108
+ max_retries: int = DEFAULT_MAX_RETRIES
109
+ backoff_factor: float = 0.5
110
+ #: Upper bound of the exponential backoff (not of ``Retry-After``).
111
+ max_backoff: float = 8.0
112
+ #: Longest ``Retry-After`` the client waits for by itself.
113
+ max_retry_after: float = DEFAULT_MAX_RETRY_AFTER
114
+ jitter: Callable[[], float] = field(default=random.random, repr=False)
115
+
116
+ def __post_init__(self) -> None:
117
+ if self.max_retries < 0:
118
+ raise ValueError("max_retries must be >= 0")
119
+
120
+ def should_retry(
121
+ self,
122
+ error: exc.OBFError,
123
+ *,
124
+ method: str,
125
+ attempt: int,
126
+ request_sent: bool,
127
+ idempotent: bool | None = None,
128
+ ) -> bool:
129
+ """Tell whether to retry after ``error`` on the given 0-based ``attempt``.
130
+
131
+ ``request_sent`` is False when the request surely did not reach the
132
+ API, e.g. the connection failed or the token could not be obtained.
133
+ ``idempotent`` overrides the guess made from ``method``.
134
+ """
135
+ if attempt >= self.max_retries:
136
+ return False
137
+
138
+ if isinstance(error, exc.RateLimitError):
139
+ return error.retry_after is None or error.retry_after <= self.max_retry_after
140
+
141
+ if not isinstance(error, (exc.APIConnectionError, exc.ServerError)):
142
+ return False
143
+
144
+ if idempotent is None:
145
+ idempotent = method.upper() in IDEMPOTENT_METHODS
146
+
147
+ return not request_sent or idempotent
148
+
149
+ def delay(self, attempt: int, retry_after: float | None = None) -> float:
150
+ """Seconds to wait before retry number ``attempt + 1``.
151
+
152
+ The server's ``Retry-After`` when given (:meth:`should_retry` already
153
+ refused values above ``max_retry_after``), otherwise exponential
154
+ backoff with jitter, up to ``max_backoff``.
155
+ """
156
+ if retry_after is not None:
157
+ return max(0.0, retry_after)
158
+
159
+ base = self.backoff_factor * 2.0**attempt
160
+
161
+ return min(base * (1 + self.jitter()), self.max_backoff)
162
+
163
+
164
+ @dataclass(frozen=True)
165
+ class Settings:
166
+ """Validated client configuration."""
167
+
168
+ client_id: str
169
+ client_secret: SecretStr
170
+ base_url: str
171
+ timeout: float
172
+ retry: RetryPolicy
173
+ user_agent: str = USER_AGENT
174
+ api_consumer_id: str | None = None
175
+
176
+ @classmethod
177
+ def resolve(
178
+ cls,
179
+ *,
180
+ client_id: str,
181
+ client_secret: str | SecretStr,
182
+ base_url: str | None = None,
183
+ timeout: float = DEFAULT_TIMEOUT,
184
+ max_retries: int = DEFAULT_MAX_RETRIES,
185
+ max_retry_after: float = DEFAULT_MAX_RETRY_AFTER,
186
+ user_agent: str | None = None,
187
+ api_consumer_id: str | None = None,
188
+ ) -> Settings:
189
+ """Validate explicit arguments; the environment is never read here.
190
+
191
+ Args:
192
+ client_id: Organisation id.
193
+ client_secret: API secret generated in *Admin tools > API*.
194
+ base_url: API host; default openbadgefactory.com.
195
+ timeout: Seconds for each HTTP request.
196
+ max_retries: Retries after the first attempt (0 disables them).
197
+ max_retry_after: Longest ``Retry-After`` to wait for before retrying;
198
+ longer waits raise :class:`~openbadgefactory.RateLimitError`.
199
+ user_agent: Identifies your application; appended to the library's
200
+ own ``User-Agent``, never replacing it.
201
+ api_consumer_id: Label stored with every badge this client issues,
202
+ to find them later (e.g. ``"moodle-plugin"``); ``None`` sends no label.
203
+
204
+ """
205
+ if not client_id or not client_secret: # an empty SecretStr is falsy too
206
+ raise exc.OBFError("Missing credentials: client_id and client_secret are required")
207
+
208
+ if not _CLIENT_ID_PATTERN.fullmatch(client_id):
209
+ raise exc.OBFError(
210
+ f"Invalid client_id {client_id!r}: expected 1-100 letters, digits or '_'"
211
+ )
212
+
213
+ if timeout <= 0:
214
+ raise ValueError("timeout must be > 0")
215
+
216
+ if max_retry_after < 0:
217
+ raise ValueError("max_retry_after must be >= 0")
218
+
219
+ if api_consumer_id is not None and not api_consumer_id.strip():
220
+ raise ValueError("api_consumer_id must not be empty; use None for no label")
221
+
222
+ return cls(
223
+ client_id=client_id,
224
+ client_secret=(
225
+ client_secret if isinstance(client_secret, SecretStr) else SecretStr(client_secret)
226
+ ),
227
+ base_url=_normalize_base_url(base_url or DEFAULT_BASE_URL),
228
+ timeout=timeout,
229
+ retry=RetryPolicy(max_retries=max_retries, max_retry_after=max_retry_after),
230
+ user_agent=f"{USER_AGENT} {user_agent.strip()}" if user_agent else USER_AGENT,
231
+ api_consumer_id=api_consumer_id.strip() if api_consumer_id else None,
232
+ )
233
+
234
+ @classmethod
235
+ def from_env(
236
+ cls,
237
+ environ: Mapping[str, str] | None = None,
238
+ *,
239
+ base_url: str | None = None,
240
+ timeout: float = DEFAULT_TIMEOUT,
241
+ max_retries: int = DEFAULT_MAX_RETRIES,
242
+ max_retry_after: float = DEFAULT_MAX_RETRY_AFTER,
243
+ user_agent: str | None = None,
244
+ api_consumer_id: str | None = None,
245
+ ) -> Settings:
246
+ """Read ``OBF_CLIENT_ID``, ``OBF_CLIENT_SECRET`` and ``OBF_BASE_URL``.
247
+
248
+ Credentials always come from the environment together; an explicit
249
+ ``base_url`` wins over ``OBF_BASE_URL``. ``environ`` defaults to
250
+ ``os.environ`` (pass a dict to read e.g. an already parsed ``.env``).
251
+ """
252
+ env = os.environ if environ is None else environ
253
+ client_id = env.get(ENV_CLIENT_ID, "")
254
+ client_secret = env.get(ENV_CLIENT_SECRET, "")
255
+ missing = [
256
+ name
257
+ for name, value in ((ENV_CLIENT_ID, client_id), (ENV_CLIENT_SECRET, client_secret))
258
+ if not value
259
+ ]
260
+
261
+ if missing:
262
+ raise exc.OBFError(f"Missing environment variables: {', '.join(missing)}")
263
+
264
+ return cls.resolve(
265
+ client_id=client_id,
266
+ client_secret=client_secret,
267
+ base_url=base_url or env.get(ENV_BASE_URL) or None,
268
+ timeout=timeout,
269
+ max_retries=max_retries,
270
+ max_retry_after=max_retry_after,
271
+ user_agent=user_agent,
272
+ api_consumer_id=api_consumer_id,
273
+ )
274
+
275
+ @property
276
+ def token_url(self) -> str:
277
+ return f"{self.base_url}{TOKEN_PATH}"
278
+
279
+ @property
280
+ def headers(self) -> dict[str, str]:
281
+ """Headers sent with every API request."""
282
+ return {"Accept": "application/json", "User-Agent": self.user_agent}
283
+
284
+ def url(self, path: str) -> str:
285
+ """Absolute URL of an API path (which must start with ``/``)."""
286
+ if not path.startswith("/"):
287
+ raise ValueError(f"API paths must start with '/': {path!r}")
288
+
289
+ return f"{self.base_url}{path}"
290
+
291
+ def make_auth(self) -> ClientCredentialsAuth:
292
+ return ClientCredentialsAuth(
293
+ self.client_id,
294
+ self.client_secret,
295
+ self.token_url,
296
+ headers={"User-Agent": self.user_agent},
297
+ )
298
+
299
+
300
+ def _normalize_base_url(url: str) -> str:
301
+ """Check that ``url`` is an absolute http(s) URL and drop any trailing ``/``."""
302
+ parts = urlsplit(url.strip())
303
+
304
+ if parts.scheme not in ("http", "https") or not parts.netloc:
305
+ raise ValueError(f"base_url must be an absolute http(s) URL, got {url!r}")
306
+
307
+ if parts.query or parts.fragment:
308
+ raise ValueError(f"base_url must not contain a query or fragment, got {url!r}")
309
+
310
+ return url.strip().rstrip("/")
@@ -0,0 +1,39 @@
1
+ """Base class for every model, generated or hand-written.
2
+
3
+ Kept in its own module, with no imports from the rest of the package, so that
4
+ ``_generated.py`` can import it without circular imports.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from pydantic import BaseModel, ConfigDict
12
+
13
+ __all__ = ["OBFModel"]
14
+
15
+
16
+ class OBFModel(BaseModel):
17
+ """Common configuration for Open Badge Factory models.
18
+
19
+ - ``extra="allow"``: fields the API adds after the spec version we were
20
+ generated from are kept (in ``model_extra``) instead of raising errors.
21
+ - ``frozen=True``: models are immutable and hashable; use
22
+ ``model.model_copy(update={...})`` to derive a modified copy.
23
+ - ``populate_by_name=True``: fields renamed with an alias (e.g. a Python
24
+ keyword in the spec) can set by either name.
25
+ """
26
+
27
+ model_config = ConfigDict(
28
+ extra="allow",
29
+ frozen=True,
30
+ populate_by_name=True,
31
+ )
32
+
33
+ def to_payload(self) -> dict[str, Any]:
34
+ """Serialize as a JSON request body.
35
+
36
+ Only fields that were explicitly set are sent: the API tells "missing"
37
+ (use the server default) apart from ``null`` (clear the value).
38
+ """
39
+ return self.model_dump(mode="json", by_alias=True, exclude_unset=True)