pontive 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.
pontive/__init__.py ADDED
@@ -0,0 +1,89 @@
1
+ """
2
+ Pontive SDK for Python.
3
+
4
+ - :class:`ResourceServer`: protect an API or an MCP server with Pontive access tokens.
5
+ - :class:`ServerAuth`: server-side sessions for web apps (sign-in, a sealed session cookie, safe refresh).
6
+ - :class:`AuthorizationClient`: permission checks and listings for a verified principal.
7
+
8
+ Framework adapters: ``pontive.fastapi``, ``pontive.flask``, ``pontive.django``, ``pontive.mcp``.
9
+ """
10
+
11
+ from ._env import PONTIVE_ENV
12
+ from ._management import ClientCredentials, ManagementCredential, management_audience
13
+ from ._version import __version__
14
+ from .authorization import AccessibleResourcePage, AuthorizationClient, CheckItem, ResourceRef
15
+ from .errors import (
16
+ AuthorizationError,
17
+ BearerError,
18
+ ConfigurationError,
19
+ ListingTooLargeError,
20
+ PontiveError,
21
+ TokenEndpointError,
22
+ )
23
+ from .http import AuthRequest, AuthResponse
24
+ from .organization import (
25
+ ORGANIZATION_ERROR_PARAM,
26
+ SWITCH_ORGANIZATION_ROUTE,
27
+ Organization,
28
+ switch_organization_path,
29
+ )
30
+ from .resource_server import (
31
+ ApiScope,
32
+ ApiScopeTool,
33
+ MetadataFetch,
34
+ Principal,
35
+ PrincipalActor,
36
+ PrincipalKind,
37
+ ResourceServer,
38
+ bearer_token,
39
+ )
40
+ from .server_auth import (
41
+ ACCESS_COOKIE,
42
+ SESSION_HINT_COOKIE,
43
+ ProviderProps,
44
+ RefreshOutcome,
45
+ ServerAuth,
46
+ Session,
47
+ SessionUser,
48
+ is_page_navigation,
49
+ )
50
+
51
+ __all__ = [
52
+ "ACCESS_COOKIE",
53
+ "ORGANIZATION_ERROR_PARAM",
54
+ "PONTIVE_ENV",
55
+ "SESSION_HINT_COOKIE",
56
+ "SWITCH_ORGANIZATION_ROUTE",
57
+ "AccessibleResourcePage",
58
+ "ApiScope",
59
+ "ApiScopeTool",
60
+ "AuthRequest",
61
+ "AuthResponse",
62
+ "AuthorizationClient",
63
+ "AuthorizationError",
64
+ "BearerError",
65
+ "CheckItem",
66
+ "ClientCredentials",
67
+ "ConfigurationError",
68
+ "ListingTooLargeError",
69
+ "ManagementCredential",
70
+ "MetadataFetch",
71
+ "Organization",
72
+ "PontiveError",
73
+ "Principal",
74
+ "PrincipalActor",
75
+ "PrincipalKind",
76
+ "ProviderProps",
77
+ "RefreshOutcome",
78
+ "ResourceRef",
79
+ "ResourceServer",
80
+ "ServerAuth",
81
+ "Session",
82
+ "SessionUser",
83
+ "TokenEndpointError",
84
+ "__version__",
85
+ "bearer_token",
86
+ "is_page_navigation",
87
+ "management_audience",
88
+ "switch_organization_path",
89
+ ]
pontive/_env.py ADDED
@@ -0,0 +1,38 @@
1
+ """The environment contract (pontive-spec 47 §6.1), shared with every Pontive SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Mapping
7
+ from types import MappingProxyType
8
+
9
+ #: The variables the SDK falls back to when the app does not pass a field.
10
+ #: Explicit configuration always wins; a blank value counts as unset.
11
+ #:
12
+ #: ====================== ======================================================
13
+ #: ``PONTIVE_ISSUER`` the instance's issuer (its auth domain origin)
14
+ #: ``PONTIVE_CLIENT_ID`` the app's id
15
+ #: ``PONTIVE_CLIENT_SECRET`` a confidential (``web``) app's client secret
16
+ #: ``PONTIVE_SESSION_SECRET`` 32+ random characters, generated locally
17
+ #: ``PONTIVE_SECRET_KEY`` the instance's secret key (not read in this release)
18
+ #: ``PONTIVE_INSTANCE_ID`` the instance's id (not read in this release)
19
+ #: ====================== ======================================================
20
+ PONTIVE_ENV: Mapping[str, str] = MappingProxyType(
21
+ {
22
+ "issuer": "PONTIVE_ISSUER",
23
+ "client_id": "PONTIVE_CLIENT_ID",
24
+ "client_secret": "PONTIVE_CLIENT_SECRET",
25
+ "session_secret": "PONTIVE_SESSION_SECRET",
26
+ "secret_key": "PONTIVE_SECRET_KEY",
27
+ "instance_id": "PONTIVE_INSTANCE_ID",
28
+ }
29
+ )
30
+
31
+
32
+ def env_value(field: str, env: Mapping[str, str] | None = None) -> str | None:
33
+ """The environment's value for a config field, trimmed, or None when unset or blank."""
34
+ source = os.environ if env is None else env
35
+ raw = source.get(PONTIVE_ENV[field])
36
+ if raw is None or not raw.strip():
37
+ return None
38
+ return raw.strip()
pontive/_http.py ADDED
@@ -0,0 +1,186 @@
1
+ """
2
+ HTTP for the SDK's own calls: discovery, keys, the token endpoint, AuthZEN.
3
+
4
+ The protocol logic is written once, as generators that yield the
5
+ ``httpx.Request`` they need sent and receive its ``httpx.Response``;
6
+ :func:`run` and :func:`arun` drive them with a sync or an async client. So the
7
+ sync and async APIs cannot drift apart.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import threading
14
+ from collections.abc import Awaitable, Callable, Generator
15
+ from concurrent.futures import Future
16
+ from typing import Any, Generic, TypeVar
17
+
18
+ import httpx
19
+
20
+ from ._util import now, sha256_hex
21
+ from ._version import __version__
22
+ from .errors import PontiveError
23
+
24
+ T = TypeVar("T")
25
+
26
+ #: A protocol step: yields requests, receives responses, returns T.
27
+ Flow = Generator[httpx.Request, httpx.Response, T]
28
+
29
+ USER_AGENT = f"pontive-python/{__version__}"
30
+ DEFAULT_TIMEOUT = 10.0
31
+
32
+
33
+ def request(method: str, url: str, **kwargs: Any) -> httpx.Request:
34
+ headers = {"user-agent": USER_AGENT, "accept": "application/json", **kwargs.pop("headers", {})}
35
+ return httpx.Request(method, url, headers=headers, **kwargs)
36
+
37
+
38
+ def json_body(response: httpx.Response, what: str) -> Any:
39
+ try:
40
+ return response.json()
41
+ except ValueError as err:
42
+ raise PontiveError(f"{what}: the response is not JSON") from err
43
+
44
+
45
+ class HttpClients:
46
+ """
47
+ The app's clients, or the SDK's own. A sync client is shared (httpx's is
48
+ thread-safe); without an async client each async call opens one, since an
49
+ ``AsyncClient`` belongs to the event loop it was first used on. Pass
50
+ ``async_http_client`` to reuse connections.
51
+ """
52
+
53
+ def __init__(self, http_client: httpx.Client | None, async_http_client: httpx.AsyncClient | None) -> None:
54
+ self._sync = http_client
55
+ self._async = async_http_client
56
+ self._lock = threading.Lock()
57
+
58
+ def send(self, req: httpx.Request) -> httpx.Response:
59
+ if self._sync is None:
60
+ with self._lock:
61
+ if self._sync is None:
62
+ self._sync = httpx.Client(timeout=DEFAULT_TIMEOUT)
63
+ return self._sync.send(req)
64
+
65
+ async def asend(self, req: httpx.Request) -> httpx.Response:
66
+ if self._async is not None:
67
+ return await self._async.send(req)
68
+ async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
69
+ return await client.send(req)
70
+
71
+
72
+ def run(flow: Flow[T], http: HttpClients) -> T:
73
+ """Drives a flow with the sync client. A transport error is raised inside the flow, where it may be handled."""
74
+ try:
75
+ req = next(flow)
76
+ while True:
77
+ try:
78
+ res = http.send(req)
79
+ except httpx.HTTPError as err:
80
+ req = flow.throw(err)
81
+ continue
82
+ req = flow.send(res)
83
+ except StopIteration as stop:
84
+ return stop.value # type: ignore[no-any-return]
85
+
86
+
87
+ async def arun(flow: Flow[T], http: HttpClients) -> T:
88
+ """Drives a flow with the async client, as :func:`run` does."""
89
+ try:
90
+ req = next(flow)
91
+ while True:
92
+ try:
93
+ res = await http.asend(req)
94
+ except httpx.HTTPError as err:
95
+ req = flow.throw(err)
96
+ continue
97
+ req = flow.send(res)
98
+ except StopIteration as stop:
99
+ return stop.value # type: ignore[no-any-return]
100
+
101
+
102
+ #: How long a refresh's result is handed to late arrivals. Matches the issuer's grace window.
103
+ RECENT_RESULT_SECONDS = 30.0
104
+
105
+
106
+ class RefreshCoordinator(Generic[T]):
107
+ """
108
+ One refresh per session, however many requests ask for it.
109
+
110
+ With rotation on, every refresh spends the token it presents. A page that
111
+ fires several requests the moment its access token expires would otherwise
112
+ refresh once per request, and every request after the first would present
113
+ a token the first had already spent, which the issuer reads as theft.
114
+
115
+ Two layers, in this process:
116
+
117
+ - In flight: requests for the same refresh token share one call (threads
118
+ wait on the first; coroutines on one event loop await one task).
119
+ - Recently done: a request that arrives a moment later still holding the
120
+ old cookie is handed the same result rather than spending the old token
121
+ again.
122
+
123
+ Across processes the issuer's reuse grace window covers the same race.
124
+ Keys are the token's SHA-256, so the maps never hold a live credential.
125
+ """
126
+
127
+ def __init__(self, recent_seconds: float = RECENT_RESULT_SECONDS) -> None:
128
+ self._recent_seconds = recent_seconds
129
+ self._lock = threading.Lock()
130
+ self._recent: dict[str, tuple[float, T]] = {}
131
+ self._threads: dict[str, Future[T]] = {}
132
+ self._tasks: dict[str, asyncio.Task[T]] = {}
133
+
134
+ def _sweep(self) -> None:
135
+ cutoff = now() - self._recent_seconds
136
+ for key in [k for k, (at, _) in self._recent.items() if at < cutoff]:
137
+ del self._recent[key]
138
+
139
+ def run(self, refresh_token: str, refresh: Callable[[], T]) -> T:
140
+ key = sha256_hex(refresh_token)
141
+ with self._lock:
142
+ self._sweep()
143
+ if key in self._recent:
144
+ return self._recent[key][1]
145
+ pending = self._threads.get(key)
146
+ owner = pending is None
147
+ if pending is None:
148
+ pending = Future()
149
+ self._threads[key] = pending
150
+ if not owner:
151
+ return pending.result()
152
+ try:
153
+ result = refresh()
154
+ except BaseException as err:
155
+ with self._lock:
156
+ self._threads.pop(key, None)
157
+ pending.set_exception(err)
158
+ raise
159
+ with self._lock:
160
+ self._recent[key] = (now(), result)
161
+ self._threads.pop(key, None)
162
+ pending.set_result(result)
163
+ return result
164
+
165
+ async def arun(self, refresh_token: str, refresh: Callable[[], Awaitable[T]]) -> T:
166
+ key = sha256_hex(refresh_token)
167
+ loop = asyncio.get_running_loop()
168
+ with self._lock:
169
+ self._sweep()
170
+ if key in self._recent:
171
+ return self._recent[key][1]
172
+ task = self._tasks.get(key)
173
+ if task is None or task.done() or task.get_loop() is not loop:
174
+ task = loop.create_task(self._complete(key, refresh))
175
+ self._tasks[key] = task
176
+ return await asyncio.shield(task)
177
+
178
+ async def _complete(self, key: str, refresh: Callable[[], Awaitable[T]]) -> T:
179
+ try:
180
+ result = await refresh()
181
+ finally:
182
+ with self._lock:
183
+ self._tasks.pop(key, None)
184
+ with self._lock:
185
+ self._recent[key] = (now(), result)
186
+ return result
pontive/_jwt.py ADDED
@@ -0,0 +1,206 @@
1
+ """
2
+ JWT verification: the parts pontkit-server gets from jose's ``jwtVerify``.
3
+ Signatures are checked by joserfc; header and claim rules are here, so each
4
+ refusal says exactly why.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import threading
11
+ from collections.abc import Collection, Iterable, Mapping
12
+ from typing import Any
13
+
14
+ from joserfc import jws
15
+ from joserfc.errors import JoseError
16
+ from joserfc.jwk import ECKey, RSAKey
17
+
18
+ from ._util import b64url_decode, is_number, now
19
+
20
+ #: The algorithms Pontive signs with (pontive-spec 04a): asymmetric only.
21
+ DEFAULT_ALGORITHMS: tuple[str, ...] = ("RS256", "PS256", "ES256")
22
+
23
+ _ASYMMETRIC = {
24
+ "RS256": ("RSA", None),
25
+ "RS384": ("RSA", None),
26
+ "RS512": ("RSA", None),
27
+ "PS256": ("RSA", None),
28
+ "PS384": ("RSA", None),
29
+ "PS512": ("RSA", None),
30
+ "ES256": ("EC", "P-256"),
31
+ "ES384": ("EC", "P-384"),
32
+ "ES512": ("EC", "P-521"),
33
+ }
34
+
35
+ Key = RSAKey | ECKey
36
+
37
+
38
+ class TokenInvalid(Exception):
39
+ """The token is bad (as opposed to: the keys could not be fetched)."""
40
+
41
+ def __init__(self, message: str, *, expired: bool = False) -> None:
42
+ super().__init__(message)
43
+ self.expired = expired
44
+
45
+
46
+ def check_algorithms(algorithms: Iterable[str]) -> tuple[str, ...]:
47
+ """The allow-list, refusing ``none``, HMAC and anything unknown: a public key is never an HMAC secret."""
48
+ out = tuple(algorithms)
49
+ if not out:
50
+ raise ValueError("algorithms must name at least one algorithm")
51
+ for alg in out:
52
+ if alg not in _ASYMMETRIC:
53
+ raise ValueError(f"algorithm {alg!r} is not allowed: use RS*, PS* or ES* (none and HMAC are refused)")
54
+ return out
55
+
56
+
57
+ def _json_segment(segment: str, what: str) -> dict[str, Any]:
58
+ try:
59
+ value = json.loads(b64url_decode(segment))
60
+ except (ValueError, UnicodeDecodeError) as err:
61
+ raise TokenInvalid(f"the token's {what} is not base64url JSON") from err
62
+ if not isinstance(value, dict):
63
+ raise TokenInvalid(f"the token's {what} is not a JSON object")
64
+ return value
65
+
66
+
67
+ def decode_unverified(token: str) -> tuple[dict[str, Any], dict[str, Any]]:
68
+ """The header and payload of a compact JWS, unverified. Anything else (a JWE, junk) is refused."""
69
+ parts = token.split(".")
70
+ if len(parts) != 3 or not all(parts[:2]):
71
+ raise TokenInvalid("the token is not a JWT")
72
+ return _json_segment(parts[0], "header"), _json_segment(parts[1], "payload")
73
+
74
+
75
+ def claims_unverified(token: str) -> dict[str, Any]:
76
+ """
77
+ A token's claims, or none when it is not a JWT. Read, not verified: only
78
+ ever called on a token that was verified, or that came straight from the
79
+ token endpoint over TLS.
80
+ """
81
+ try:
82
+ return decode_unverified(token)[1]
83
+ except TokenInvalid:
84
+ return {}
85
+
86
+
87
+ def verify_signature(token: str, key: Key, algorithms: Collection[str]) -> None:
88
+ try:
89
+ jws.deserialize_compact(token, key, algorithms=list(algorithms))
90
+ except (JoseError, ValueError, TypeError) as err:
91
+ raise TokenInvalid("signature verification failed") from err
92
+
93
+
94
+ def check_header(header: Mapping[str, Any], algorithms: Collection[str], typ: str | None) -> str:
95
+ alg = header.get("alg")
96
+ if not isinstance(alg, str) or alg not in algorithms:
97
+ raise TokenInvalid(f'the token\'s algorithm "{alg}" is not allowed')
98
+ if header.get("crit") is not None:
99
+ raise TokenInvalid("the token names critical header parameters this verifier does not understand")
100
+ if typ is not None:
101
+ got = header.get("typ")
102
+ normalized = got.lower().removeprefix("application/") if isinstance(got, str) else None
103
+ if normalized != typ:
104
+ raise TokenInvalid(f'the token\'s "typ" is not "{typ}"')
105
+ return alg
106
+
107
+
108
+ def check_claims(
109
+ payload: Mapping[str, Any],
110
+ *,
111
+ issuer: str | None,
112
+ audience: str | None,
113
+ leeway: float,
114
+ required: Iterable[str] = ("exp",),
115
+ ) -> None:
116
+ for claim in required:
117
+ if claim not in payload:
118
+ raise TokenInvalid(f'missing required "{claim}" claim')
119
+ if issuer is not None and payload.get("iss") != issuer:
120
+ raise TokenInvalid('unexpected "iss" claim value')
121
+ if audience is not None:
122
+ aud = payload.get("aud")
123
+ auds = [aud] if isinstance(aud, str) else aud if isinstance(aud, list) else []
124
+ if audience not in auds:
125
+ raise TokenInvalid('unexpected "aud" claim value')
126
+ current = now()
127
+ for claim in ("exp", "nbf", "iat"):
128
+ if claim in payload and not is_number(payload[claim]):
129
+ raise TokenInvalid(f'"{claim}" claim must be a number')
130
+ if "exp" in payload and payload["exp"] <= current - leeway:
131
+ raise TokenInvalid('"exp" claim timestamp check failed', expired=True)
132
+ if "nbf" in payload and payload["nbf"] > current + leeway:
133
+ raise TokenInvalid('"nbf" claim timestamp check failed')
134
+ if "sub" in required and (not isinstance(payload.get("sub"), str) or not payload["sub"]):
135
+ raise TokenInvalid('"sub" claim must be a non-empty string')
136
+
137
+
138
+ #: Keys are kept this long, then refetched on the next verification.
139
+ JWKS_MAX_AGE_SECONDS = 600.0
140
+ #: An unknown kid refetches the set at most this often.
141
+ JWKS_COOLDOWN_SECONDS = 30.0
142
+
143
+
144
+ class KeySetCache:
145
+ """
146
+ One issuer's signing keys. Kept ten minutes; a ``kid`` the set does not
147
+ hold refetches it at most once per 30 seconds, which is how a rotation at
148
+ the issuer is picked up at once without a stream of junk kids hammering
149
+ it. The same rules as jose's ``createRemoteJWKSet``.
150
+ """
151
+
152
+ def __init__(self) -> None:
153
+ self._lock = threading.Lock()
154
+ self._keys: list[tuple[dict[str, Any], Key]] = []
155
+ self._fetched_at: float | None = None
156
+
157
+ @property
158
+ def has_keys(self) -> bool:
159
+ return self._fetched_at is not None
160
+
161
+ def fresh(self) -> bool:
162
+ return self._fetched_at is not None and now() - self._fetched_at < JWKS_MAX_AGE_SECONDS
163
+
164
+ def may_refetch(self) -> bool:
165
+ return self._fetched_at is None or now() - self._fetched_at >= JWKS_COOLDOWN_SECONDS
166
+
167
+ def store(self, document: Any) -> None:
168
+ jwks = document.get("keys") if isinstance(document, dict) else None
169
+ if not isinstance(jwks, list):
170
+ raise ValueError("the JWKS document has no keys array")
171
+ keys: list[tuple[dict[str, Any], Key]] = []
172
+ for jwk in jwks:
173
+ if not isinstance(jwk, dict):
174
+ continue
175
+ try:
176
+ if jwk.get("kty") == "RSA":
177
+ keys.append((jwk, RSAKey.import_key(jwk)))
178
+ elif jwk.get("kty") == "EC":
179
+ keys.append((jwk, ECKey.import_key(jwk)))
180
+ except (JoseError, ValueError, TypeError):
181
+ continue # A key this verifier cannot use is skipped, as jose does.
182
+ with self._lock:
183
+ self._keys = keys
184
+ self._fetched_at = now()
185
+
186
+ def candidates(self, header: Mapping[str, Any]) -> list[Key]:
187
+ """The keys that could have signed a token with this header."""
188
+ alg = header.get("alg")
189
+ kid = header.get("kid")
190
+ kty, crv = _ASYMMETRIC.get(alg, (None, None)) if isinstance(alg, str) else (None, None)
191
+ out: list[Key] = []
192
+ with self._lock:
193
+ keys = list(self._keys)
194
+ for jwk, key in keys:
195
+ if kty is None or jwk.get("kty") != kty:
196
+ continue
197
+ if crv is not None and jwk.get("crv") != crv:
198
+ continue
199
+ if kid is not None and jwk.get("kid") != kid:
200
+ continue
201
+ if jwk.get("use") not in (None, "sig"):
202
+ continue
203
+ if jwk.get("alg") not in (None, alg):
204
+ continue
205
+ out.append(key)
206
+ return out
pontive/_management.py ADDED
@@ -0,0 +1,122 @@
1
+ """How a server gets a management API token, and where the management API is."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import re
7
+ import threading
8
+ from collections.abc import Awaitable, Callable
9
+ from dataclasses import dataclass
10
+ from urllib.parse import urlsplit
11
+
12
+ from ._http import Flow, HttpClients, arun, run
13
+ from ._oidc import ClientAuth, Oidc
14
+ from ._util import now, trim_slash
15
+ from .errors import ConfigurationError
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class ClientCredentials:
20
+ """A service account's client credentials, exchanged at the issuer for a management token."""
21
+
22
+ client_id: str
23
+ client_secret: str
24
+
25
+ def __repr__(self) -> str:
26
+ return f"ClientCredentials(client_id={self.client_id!r}, client_secret='***')"
27
+
28
+
29
+ #: A token, a function returning one (sync, or async for the async methods), or client credentials.
30
+ ManagementCredential = str | Callable[[], str] | Callable[[], Awaitable[str]] | ClientCredentials
31
+
32
+ _SUFFIX = re.compile(r"/(mgmt(/v1)?|v1)$")
33
+
34
+
35
+ def management_base(management_url: str) -> str:
36
+ """
37
+ The management API's base: origin and any gateway path, without a
38
+ trailing slash and without a ``/v1``, ``/mgmt`` or ``/mgmt/v1`` suffix.
39
+ """
40
+ raw = management_url.strip()
41
+ base = raw
42
+ parts = urlsplit(raw)
43
+ if parts.scheme and parts.netloc:
44
+ base = f"{parts.scheme}://{parts.netloc}{parts.path}"
45
+ return _SUFFIX.sub("", trim_slash(base))
46
+
47
+
48
+ def management_audience(management_url: str) -> str:
49
+ """The management API's audience: its origin, ``https://api.us.pontive.com``, with no path."""
50
+ raw = management_url.strip()
51
+ parts = urlsplit(raw)
52
+ if parts.scheme and parts.netloc:
53
+ return f"{parts.scheme}://{parts.netloc}"
54
+ return trim_slash(raw)
55
+
56
+
57
+ class ManagementTokenSource:
58
+ """
59
+ A management API bearer token for a credential. Client credentials are
60
+ exchanged at ``issuer`` for the management API's audience and the token is
61
+ reused until a minute before it expires.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ credential: ManagementCredential,
67
+ *,
68
+ management_url: str,
69
+ issuer: str | None,
70
+ oidc: Oidc,
71
+ http: HttpClients,
72
+ ) -> None:
73
+ self._credential = credential
74
+ self._management_url = management_url
75
+ self._issuer = issuer
76
+ self._oidc = oidc
77
+ self._http = http
78
+ self._lock = threading.Lock()
79
+ self._cached: tuple[str, float] | None = None
80
+
81
+ def _exchange(self, credential: ClientCredentials) -> Flow[str]:
82
+ if not self._issuer:
83
+ raise ConfigurationError("pontive: client credentials need the issuer to exchange them at")
84
+ client = ClientAuth(self._issuer, credential.client_id, credential.client_secret)
85
+ res = yield from self._oidc.token(
86
+ client, {"grant_type": "client_credentials", "resource": management_audience(self._management_url)}
87
+ )
88
+ with self._lock:
89
+ self._cached = (res.access_token, now() + (res.expires_in or 300) - 60)
90
+ return res.access_token
91
+
92
+ def _cached_token(self) -> str | None:
93
+ with self._lock:
94
+ if self._cached and now() < self._cached[1]:
95
+ return self._cached[0]
96
+ return None
97
+
98
+ def get(self) -> str:
99
+ cred = self._credential
100
+ if isinstance(cred, str):
101
+ return cred
102
+ if isinstance(cred, ClientCredentials):
103
+ cached = self._cached_token()
104
+ return cached if cached is not None else run(self._exchange(cred), self._http)
105
+ value = cred()
106
+ if inspect.isawaitable(value):
107
+ if inspect.iscoroutine(value):
108
+ value.close()
109
+ raise ConfigurationError("pontive: an async credential function needs the async methods")
110
+ return value
111
+
112
+ async def aget(self) -> str:
113
+ cred = self._credential
114
+ if isinstance(cred, str):
115
+ return cred
116
+ if isinstance(cred, ClientCredentials):
117
+ cached = self._cached_token()
118
+ return cached if cached is not None else await arun(self._exchange(cred), self._http)
119
+ value = cred()
120
+ if inspect.isawaitable(value):
121
+ return await value
122
+ return value