marmotgraph-sdk 4.0.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,173 @@
1
+ """Python SDK for the MarmotGraph v4 API (``/v4`` REST endpoints).
2
+
3
+ Quickstart::
4
+
5
+ from marmotgraph import Client, Stage
6
+
7
+ client = Client("core.marmotgraph.org", token="...")
8
+ page = client.instances.list(types=["https://openminds.ebrains.eu/core/Person"], stage=Stage.RELEASED)
9
+ for instance in page.all_items():
10
+ print(instance.uuid, instance.get("http://schema.org/name"))
11
+ """
12
+
13
+ from .auth import (
14
+ AuthenticationInformation,
15
+ CallableToken,
16
+ ClientCredentialsToken,
17
+ DeviceFlowToken,
18
+ OIDCConfig,
19
+ StaticToken,
20
+ TokenProvider,
21
+ )
22
+ from .batch import Batch, BatchResult
23
+ from .client import Client
24
+ from .errors import AuthenticationError, MarmotGraphAPIError, MarmotGraphError
25
+ from .models import (
26
+ AuthenticationConfig,
27
+ BatchItemError,
28
+ BatchItemStatus,
29
+ BatchJob,
30
+ BatchJobItem,
31
+ BatchJobStatus,
32
+ BatchOperation,
33
+ BatchSyncResult,
34
+ BatchUpsertItem,
35
+ BulkValidationResult,
36
+ BulkValidationState,
37
+ BulkValidationStatus,
38
+ ExecutionDetails,
39
+ GraphStatistics,
40
+ Functionality,
41
+ FunctionalityInstance,
42
+ GraphEntity,
43
+ IncomingLink,
44
+ Instance,
45
+ JsonLdDocument,
46
+ LinkingInstance,
47
+ Property,
48
+ ReleaseStatus,
49
+ ReleaseTreeScope,
50
+ RoleMapping,
51
+ Scope,
52
+ ScopeDefinition,
53
+ SpaceInformation,
54
+ SpaceReference,
55
+ SourceType,
56
+ SpaceSpecification,
57
+ Stage,
58
+ InstanceSortBy,
59
+ SortDirection,
60
+ TargetType,
61
+ TypeInformation,
62
+ TypeInSpace,
63
+ StoredQuery,
64
+ TypeSpecification,
65
+ PropertySpecification,
66
+ UserInfo,
67
+ UserProfile,
68
+ UserWithRoles,
69
+ ValidationError,
70
+ ValidationStatistics,
71
+ TypeValidationStatistics,
72
+ ValidationResult,
73
+ ValidationSchema,
74
+ SchemaValidationResult,
75
+ InstanceTimestamps,
76
+ Contributor,
77
+ InvitationCandidate,
78
+ InvitedUser,
79
+ PendingInvitation,
80
+ Comment,
81
+ CommentAuthor,
82
+ EVERY_AUTHENTICATED_USER,
83
+ Tool,
84
+ ToolCategory,
85
+ ToolCategoryReference,
86
+ ToolDefinition,
87
+ ToolSpecification,
88
+ )
89
+ from .pagination import Page
90
+ from .resources import BatchMode
91
+
92
+ __version__ = "4.0.0"
93
+
94
+ __all__ = [
95
+ "__version__",
96
+ "Client",
97
+ "Batch",
98
+ "BatchResult",
99
+ "BatchMode",
100
+ "BatchItemError",
101
+ "BatchItemStatus",
102
+ "BatchJob",
103
+ "BulkValidationResult",
104
+ "BulkValidationState",
105
+ "BulkValidationStatus",
106
+ "GraphStatistics",
107
+ "ValidationStatistics",
108
+ "TypeValidationStatistics",
109
+ "BatchJobItem",
110
+ "BatchJobStatus",
111
+ "BatchOperation",
112
+ "BatchSyncResult",
113
+ "BatchUpsertItem",
114
+ "Stage",
115
+ "InstanceSortBy",
116
+ "SortDirection",
117
+ "ReleaseStatus",
118
+ "ReleaseTreeScope",
119
+ "Functionality",
120
+ "RoleMapping",
121
+ "Instance",
122
+ "JsonLdDocument",
123
+ "Page",
124
+ "ExecutionDetails",
125
+ "Scope",
126
+ "ScopeDefinition",
127
+ "GraphEntity",
128
+ "SpaceInformation",
129
+ "SpaceSpecification",
130
+ "SpaceReference",
131
+ "SourceType",
132
+ "TypeInformation",
133
+ "StoredQuery",
134
+ "TypeSpecification",
135
+ "PropertySpecification",
136
+ "ValidationSchema",
137
+ "ValidationResult",
138
+ "SchemaValidationResult",
139
+ "InstanceTimestamps",
140
+ "Contributor",
141
+ "InvitationCandidate",
142
+ "InvitedUser",
143
+ "PendingInvitation",
144
+ "Comment",
145
+ "CommentAuthor",
146
+ "EVERY_AUTHENTICATED_USER",
147
+ "Tool",
148
+ "ToolCategory",
149
+ "ToolCategoryReference",
150
+ "ToolDefinition",
151
+ "ToolSpecification",
152
+ "ValidationError",
153
+ "TypeInSpace",
154
+ "TargetType",
155
+ "Property",
156
+ "IncomingLink",
157
+ "LinkingInstance",
158
+ "AuthenticationConfig",
159
+ "AuthenticationInformation",
160
+ "UserInfo",
161
+ "UserProfile",
162
+ "UserWithRoles",
163
+ "FunctionalityInstance",
164
+ "TokenProvider",
165
+ "StaticToken",
166
+ "CallableToken",
167
+ "ClientCredentialsToken",
168
+ "DeviceFlowToken",
169
+ "OIDCConfig",
170
+ "MarmotGraphError",
171
+ "MarmotGraphAPIError",
172
+ "AuthenticationError",
173
+ ]
marmotgraph/_http.py ADDED
@@ -0,0 +1,211 @@
1
+ """Low-level HTTP plumbing: request construction, auth headers, response
2
+ envelope parsing, and error translation. Not part of the public API -
3
+ resource classes in ``resources/`` are the intended entry point.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from enum import Enum
9
+ from typing import Any, Dict, Optional
10
+ from uuid import UUID
11
+
12
+ import requests
13
+
14
+ from .auth import TokenProvider
15
+ from .errors import MarmotGraphAPIError
16
+ from .models import ExecutionDetails
17
+ from .pagination import PageEnvelope
18
+
19
+
20
+ def _coerce(value: Any) -> Any:
21
+ if isinstance(value, bool):
22
+ return "true" if value else "false"
23
+ if isinstance(value, Enum):
24
+ return value.value
25
+ if isinstance(value, UUID):
26
+ return str(value)
27
+ if isinstance(value, (list, tuple)):
28
+ return [_coerce(v) for v in value]
29
+ return value
30
+
31
+
32
+ def clean_params(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
33
+ if not params:
34
+ return None
35
+ return {k: _coerce(v) for k, v in params.items() if v is not None}
36
+
37
+
38
+ class HttpClient:
39
+ def __init__(
40
+ self,
41
+ base_url: str,
42
+ token_provider: Optional[TokenProvider] = None,
43
+ *,
44
+ session: Optional[requests.Session] = None,
45
+ timeout: float = 30.0,
46
+ retry_on_unauthorized: bool = True,
47
+ ):
48
+ """``retry_on_unauthorized`` controls whether a 401 response triggers
49
+ one retry with a force-refreshed token. Disable it when the token
50
+ can't be refreshed (e.g. a token forwarded from an upstream caller),
51
+ since the retry would just fail again. It is skipped automatically
52
+ when ``token_provider`` reports it isn't refreshable."""
53
+ self.base_url = base_url.rstrip("/")
54
+ self.token_provider = token_provider
55
+ self.session = session or requests.Session()
56
+ self.timeout = timeout
57
+ self._retry_on_unauthorized_requested = retry_on_unauthorized
58
+ self.retry_on_unauthorized = (
59
+ retry_on_unauthorized and token_provider is not None and token_provider.is_refreshable()
60
+ )
61
+
62
+ def with_token_provider(self, token_provider: Optional[TokenProvider]) -> "HttpClient":
63
+ """Returns an ``HttpClient`` that sends ``token_provider``'s token as
64
+ ``Authorization`` but shares this one's base URL, timeout and session
65
+ (and therefore its connection pool) and 401-retry setting."""
66
+ return HttpClient(self.base_url, token_provider, session=self.session, timeout=self.timeout,
67
+ retry_on_unauthorized=self._retry_on_unauthorized_requested)
68
+
69
+ def _headers(self, force_refresh: bool) -> Dict[str, str]:
70
+ headers: Dict[str, str] = {}
71
+ if self.token_provider:
72
+ token = self.token_provider.get_token(force_refresh)
73
+ if token:
74
+ headers["Authorization"] = f"Bearer {token}"
75
+ return headers
76
+
77
+ def request(
78
+ self,
79
+ method: str,
80
+ path: str,
81
+ *,
82
+ params: Optional[Dict[str, Any]] = None,
83
+ json_body: Any = None,
84
+ data: Any = None,
85
+ files: Any = None,
86
+ ) -> requests.Response:
87
+ url = f"{self.base_url}{path}"
88
+ query = clean_params(params)
89
+ response = self.session.request(
90
+ method, url, params=query, json=json_body, data=data, files=files,
91
+ headers=self._headers(False), timeout=self.timeout,
92
+ )
93
+ if response.status_code == 401 and self.retry_on_unauthorized:
94
+ response = self.session.request(
95
+ method, url, params=query, json=json_body, data=data, files=files,
96
+ headers=self._headers(True), timeout=self.timeout,
97
+ )
98
+ return response
99
+
100
+ @staticmethod
101
+ def _parse_json(response: requests.Response) -> Any:
102
+ if not response.content:
103
+ return None
104
+ try:
105
+ return response.json()
106
+ except ValueError:
107
+ return None
108
+
109
+ @staticmethod
110
+ def _raise_for_error(response: requests.Response, body: Any) -> None:
111
+ if response.ok:
112
+ return
113
+ message = None
114
+ instance_id = None
115
+ if isinstance(body, dict):
116
+ error = body.get("error")
117
+ if isinstance(error, dict):
118
+ message = error.get("message")
119
+ raw_id = error.get("instanceId")
120
+ if raw_id:
121
+ try:
122
+ instance_id = UUID(str(raw_id))
123
+ except ValueError:
124
+ pass
125
+ elif isinstance(body.get("message"), str):
126
+ message = body["message"]
127
+ elif isinstance(body, str):
128
+ message = body
129
+ elif body is None and response.text and response.text.strip():
130
+ # e.g. a 400 for an invalid request: the server sends the reason as plain text
131
+ message = response.text.strip()
132
+ raise MarmotGraphAPIError(response.status_code, message, instance_id, payload=body)
133
+
134
+ def result(self, method: str, path: str, **kwargs) -> Any:
135
+ """For endpoints wrapped in a ``Result``/``ResultWithExecutionDetails`` envelope.
136
+
137
+ Returns the unwrapped ``data`` payload (``None`` for void responses).
138
+ """
139
+ response = self.request(method, path, **kwargs)
140
+ body = self._parse_json(response)
141
+ self._raise_for_error(response, body)
142
+ if not isinstance(body, dict):
143
+ return None
144
+ return body.get("data")
145
+
146
+ def result_with_execution(self, method: str, path: str, **kwargs) -> tuple:
147
+ """Like :meth:`result` but also returns :class:`ExecutionDetails`."""
148
+ response = self.request(method, path, **kwargs)
149
+ body = self._parse_json(response)
150
+ self._raise_for_error(response, body)
151
+ if not isinstance(body, dict):
152
+ return None, ExecutionDetails()
153
+ execution = ExecutionDetails(
154
+ message=body.get("message"),
155
+ start_time=body.get("startTime"),
156
+ duration_in_ms=body.get("durationInMs"),
157
+ transaction_id=body.get("transactionId"),
158
+ )
159
+ return body.get("data"), execution
160
+
161
+ def paginated(self, method: str, path: str, **kwargs) -> PageEnvelope:
162
+ response = self.request(method, path, **kwargs)
163
+ body = self._parse_json(response)
164
+ self._raise_for_error(response, body)
165
+ body = body or {}
166
+ return PageEnvelope(
167
+ items=body.get("data") or [],
168
+ total=body.get("total"),
169
+ size=body.get("size"),
170
+ marker=body.get("marker"),
171
+ next_marker=body.get("nextMarker"),
172
+ execution=ExecutionDetails(
173
+ message=body.get("message"),
174
+ start_time=body.get("startTime"),
175
+ duration_in_ms=body.get("durationInMs"),
176
+ transaction_id=body.get("transactionId"),
177
+ ),
178
+ )
179
+
180
+ def raw(self, method: str, path: str, **kwargs) -> Any:
181
+ """For endpoints that return a plain JSON object/list, not wrapped in a ``Result`` envelope."""
182
+ response = self.request(method, path, **kwargs)
183
+ body = self._parse_json(response)
184
+ self._raise_for_error(response, body)
185
+ return body
186
+
187
+ def void(self, method: str, path: str, **kwargs) -> None:
188
+ response = self.request(method, path, **kwargs)
189
+ body = self._parse_json(response)
190
+ self._raise_for_error(response, body)
191
+
192
+ def text(self, method: str, path: str, **kwargs) -> str:
193
+ response = self.request(method, path, **kwargs)
194
+ if not response.ok:
195
+ self._raise_for_error(response, self._parse_json(response))
196
+ return response.text
197
+
198
+ def binary(self, method: str, path: str, **kwargs) -> bytes:
199
+ response = self.request(method, path, **kwargs)
200
+ if not response.ok:
201
+ self._raise_for_error(response, self._parse_json(response))
202
+ return response.content
203
+
204
+ def optional_binary(self, method: str, path: str, **kwargs) -> Optional[bytes]:
205
+ """Like :meth:`binary`, but returns ``None`` instead of raising on a 404."""
206
+ response = self.request(method, path, **kwargs)
207
+ if response.status_code == 404:
208
+ return None
209
+ if not response.ok:
210
+ self._raise_for_error(response, self._parse_json(response))
211
+ return response.content
marmotgraph/auth.py ADDED
@@ -0,0 +1,292 @@
1
+ """Token acquisition strategies used to authenticate against MarmotGraph.
2
+
3
+ MarmotGraph uses Keycloak (OIDC) for authentication; every strategy here
4
+ ultimately produces a bearer access token. See ``Client`` in ``client.py``
5
+ for the common entry points - most users won't need to touch this module
6
+ directly unless they need a custom token source (``CallableToken``) or the
7
+ interactive device flow (``DeviceFlowToken``).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import hashlib
14
+ import secrets
15
+ import threading
16
+ import time
17
+ from abc import ABC, abstractmethod
18
+ from dataclasses import dataclass
19
+ from typing import Callable, Optional
20
+
21
+ import requests
22
+
23
+ from .errors import AuthenticationError
24
+
25
+
26
+ class OIDCConfig:
27
+ """The subset of an OIDC discovery document needed to obtain tokens.
28
+
29
+ ``authorization_endpoint`` and ``end_session_endpoint`` are only needed by
30
+ applications that let users log in (and out) via the browser (authorization
31
+ code flow / RP-initiated logout), e.g. for a Swagger UI. Both can be
32
+ ``None`` if the provider doesn't advertise them.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ token_endpoint: str,
38
+ device_authorization_endpoint: Optional[str] = None,
39
+ authorization_endpoint: Optional[str] = None,
40
+ end_session_endpoint: Optional[str] = None,
41
+ ):
42
+ self.token_endpoint = token_endpoint
43
+ self.device_authorization_endpoint = device_authorization_endpoint
44
+ self.authorization_endpoint = authorization_endpoint
45
+ self.end_session_endpoint = end_session_endpoint
46
+
47
+ @classmethod
48
+ def discover(
49
+ cls, well_known_url: str, *, timeout: float = 10.0, session: Optional[requests.Session] = None
50
+ ) -> "OIDCConfig":
51
+ if session is not None:
52
+ response = session.request("GET", well_known_url, timeout=timeout)
53
+ else:
54
+ response = requests.get(well_known_url, timeout=timeout)
55
+ if not response.ok:
56
+ raise AuthenticationError(
57
+ f"OIDC discovery document at {well_known_url} returned HTTP {response.status_code}"
58
+ )
59
+ data = response.json()
60
+ token_endpoint = data.get("token_endpoint")
61
+ if not token_endpoint:
62
+ raise AuthenticationError(
63
+ f"OIDC discovery document at {well_known_url} has no token_endpoint"
64
+ )
65
+ return cls(
66
+ token_endpoint,
67
+ data.get("device_authorization_endpoint"),
68
+ data.get("authorization_endpoint"),
69
+ data.get("end_session_endpoint"),
70
+ )
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class AuthenticationInformation:
75
+ """Everything needed to authenticate against a MarmotGraph server: its
76
+ OIDC configuration (resolved from the advertised ``.well-known``
77
+ document) and the client id to use for interactive (browser) logins -
78
+ ``None`` if the server doesn't advertise one."""
79
+
80
+ oidc_config: OIDCConfig
81
+ login_client_id: Optional[str] = None
82
+
83
+ @property
84
+ def authorization_endpoint(self) -> Optional[str]:
85
+ return self.oidc_config.authorization_endpoint
86
+
87
+ @property
88
+ def token_endpoint(self) -> str:
89
+ return self.oidc_config.token_endpoint
90
+
91
+ @property
92
+ def device_authorization_endpoint(self) -> Optional[str]:
93
+ return self.oidc_config.device_authorization_endpoint
94
+
95
+ @property
96
+ def end_session_endpoint(self) -> Optional[str]:
97
+ """The endpoint terminating the user's session at the OIDC provider
98
+ (RP-initiated logout) - ``None`` if not advertised."""
99
+ return self.oidc_config.end_session_endpoint
100
+
101
+
102
+ class TokenProvider(ABC):
103
+ """Base class for strategies that produce a bearer access token.
104
+
105
+ Tokens are cached until a caller explicitly requests a refresh (the HTTP
106
+ layer does this automatically after a 401 response). ``get_token`` is
107
+ lock-protected so that many concurrent callers (e.g. a :class:`~marmotgraph.batch.Batch`
108
+ of uploads starting at once) share one fetch instead of each racing to
109
+ hit the token endpoint before any of them has cached a result.
110
+ """
111
+
112
+ def __init__(self):
113
+ self._token: Optional[str] = None
114
+ self._lock = threading.Lock()
115
+
116
+ def get_token(self, force_refresh: bool = False) -> Optional[str]:
117
+ if self._token is None or force_refresh:
118
+ with self._lock:
119
+ if self._token is None or force_refresh:
120
+ self._token = self._fetch_token()
121
+ return self._token
122
+
123
+ def is_refreshable(self) -> bool:
124
+ """Whether a forced refresh can yield a different token than the
125
+ cached one. The HTTP layer only retries a 401 response when this is
126
+ true; return ``False`` in providers that merely hand out a fixed or
127
+ forwarded token, so the 401 surfaces immediately."""
128
+ return True
129
+
130
+ @abstractmethod
131
+ def _fetch_token(self) -> Optional[str]:
132
+ ...
133
+
134
+
135
+ class StaticToken(TokenProvider):
136
+ """Wraps a fixed, already-obtained bearer token."""
137
+
138
+ def __init__(self, token: str):
139
+ super().__init__()
140
+ self._static_token = token
141
+
142
+ def _fetch_token(self) -> Optional[str]:
143
+ return self._static_token
144
+
145
+ def is_refreshable(self) -> bool:
146
+ return False
147
+
148
+
149
+ class CallableToken(TokenProvider):
150
+ """Delegates token acquisition to a user-supplied callable.
151
+
152
+ Useful for integrating with an existing authentication stack (e.g. a
153
+ web framework's session, or another SDK's token cache).
154
+ """
155
+
156
+ def __init__(self, callback: Callable[[], Optional[str]]):
157
+ super().__init__()
158
+ self._callback = callback
159
+
160
+ def _fetch_token(self) -> Optional[str]:
161
+ return self._callback()
162
+
163
+
164
+ class ClientCredentialsToken(TokenProvider):
165
+ """OAuth2 client-credentials grant, for service accounts / machine clients."""
166
+
167
+ def __init__(self, client_id: str, client_secret: str, oidc_config: OIDCConfig, *, timeout: float = 10.0):
168
+ super().__init__()
169
+ self._client_id = client_id
170
+ self._client_secret = client_secret
171
+ self._oidc_config = oidc_config
172
+ self._timeout = timeout
173
+
174
+ def _fetch_token(self) -> Optional[str]:
175
+ response = requests.post(
176
+ self._oidc_config.token_endpoint,
177
+ data={
178
+ "grant_type": "client_credentials",
179
+ "client_id": self._client_id,
180
+ "client_secret": self._client_secret,
181
+ },
182
+ timeout=self._timeout,
183
+ )
184
+ if response.status_code != 200:
185
+ return None
186
+ return response.json().get("access_token")
187
+
188
+
189
+ class DeviceFlowToken(TokenProvider):
190
+ """OAuth2 device-authorization grant for interactive (human) logins
191
+ without a browser redirect - e.g. notebooks or CLIs.
192
+
193
+ Always uses PKCE (``S256``): it's required by OIDC providers that enforce
194
+ PKCE for the client (e.g. Keycloak's "PKCE Method" client setting) and
195
+ harmless for the others.
196
+ """
197
+
198
+ def __init__(
199
+ self,
200
+ client_id: str,
201
+ oidc_config: OIDCConfig,
202
+ *,
203
+ on_verification_uri: Optional[Callable[[str], None]] = None,
204
+ timeout: float = 10.0,
205
+ ):
206
+ super().__init__()
207
+ if not oidc_config.device_authorization_endpoint:
208
+ raise AuthenticationError("The OIDC provider does not advertise a device_authorization_endpoint")
209
+ self._client_id = client_id
210
+ self._oidc_config = oidc_config
211
+ self._device_authorization_endpoint: str = oidc_config.device_authorization_endpoint
212
+ self._on_verification_uri = on_verification_uri or self._print_verification_uri
213
+ self._refresh_token: Optional[str] = None
214
+ self._timeout = timeout
215
+
216
+ @staticmethod
217
+ def _print_verification_uri(uri: str) -> None:
218
+ print(f"To continue, please authenticate at: {uri}")
219
+
220
+ def _fetch_token(self) -> Optional[str]:
221
+ if self._refresh_token:
222
+ token = self._refresh()
223
+ if token:
224
+ return token
225
+ return self._device_flow()
226
+
227
+ def _refresh(self) -> Optional[str]:
228
+ response = requests.post(
229
+ self._oidc_config.token_endpoint,
230
+ data={
231
+ "grant_type": "refresh_token",
232
+ "client_id": self._client_id,
233
+ "refresh_token": self._refresh_token,
234
+ },
235
+ timeout=self._timeout,
236
+ )
237
+ if response.status_code != 200:
238
+ self._refresh_token = None
239
+ return None
240
+ data = response.json()
241
+ self._refresh_token = data.get("refresh_token", self._refresh_token)
242
+ return data.get("access_token")
243
+
244
+ @staticmethod
245
+ def _pkce_pair() -> tuple[str, str]:
246
+ """A PKCE code verifier and its ``S256`` code challenge (RFC 7636)."""
247
+ verifier = secrets.token_urlsafe(64)
248
+ digest = hashlib.sha256(verifier.encode("ascii")).digest()
249
+ return verifier, base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
250
+
251
+ def _device_flow(self) -> Optional[str]:
252
+ code_verifier, code_challenge = self._pkce_pair()
253
+ response = requests.post(
254
+ self._device_authorization_endpoint,
255
+ data={
256
+ "client_id": self._client_id,
257
+ "code_challenge": code_challenge,
258
+ "code_challenge_method": "S256",
259
+ },
260
+ timeout=self._timeout,
261
+ )
262
+ response.raise_for_status()
263
+ data = response.json()
264
+ verification_uri = data.get("verification_uri_complete") or data["verification_uri"]
265
+ device_code = data["device_code"]
266
+ interval = float(data.get("interval", 1))
267
+ self._on_verification_uri(verification_uri)
268
+ return self._poll(device_code, code_verifier, interval)
269
+
270
+ def _poll(self, device_code: str, code_verifier: str, interval: float) -> Optional[str]:
271
+ while True:
272
+ time.sleep(interval)
273
+ response = requests.post(
274
+ self._oidc_config.token_endpoint,
275
+ data={
276
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
277
+ "client_id": self._client_id,
278
+ "device_code": device_code,
279
+ "code_verifier": code_verifier,
280
+ },
281
+ timeout=self._timeout,
282
+ )
283
+ if response.status_code == 200:
284
+ data = response.json()
285
+ self._refresh_token = data.get("refresh_token")
286
+ return data.get("access_token")
287
+ error = response.json().get("error") if response.content else None
288
+ if error in ("authorization_pending", "slow_down"):
289
+ if error == "slow_down":
290
+ interval += 1
291
+ continue
292
+ return None