xtrom-engine 0.3.1__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.
xtrom/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """Xtrom Engine — deterministic runtime enforcement for AI agents."""
2
+ from .core import (
3
+ Engine, Policy, Value, Label, Trust, Sensitivity, Verdict, Decision,
4
+ looks_like_secret, inspect_result, ResultInspection, RESULT_FLAGS,
5
+ )
6
+
7
+ __all__ = [
8
+ "Engine", "Policy", "Value", "Label", "Trust", "Sensitivity",
9
+ "Verdict", "Decision", "looks_like_secret",
10
+ "inspect_result", "ResultInspection", "RESULT_FLAGS",
11
+ ]
12
+ __version__ = "0.3.1"
xtrom/allowances.py ADDED
@@ -0,0 +1,63 @@
1
+ """Allowances: a human approval for a held call (STEP_UP), scoped so the same kind of call isn't held
2
+ again (design/APPROVAL-ALLOWANCES.md). Reference implementation; the control plane, Go gateway,
3
+ TS SDK and Rust engine are gated on ../allowance_golden.json, generated from this module.
4
+
5
+ An allowance is consulted only after the engine returns STEP_UP, never for a BLOCK. It covers the
6
+ same tool, the same destination and the same or cleaner data, and it always expires.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Iterable
11
+
12
+ # Holds a human can answer for a flow, and the scopes each may take. A probabilistic score has no
13
+ # stable "same call" identity, so risk.elevated_stepup is never covered.
14
+ COVERABLE: dict[str, tuple[str, ...]] = {
15
+ "ifc.untrusted_content_stepup": ("call", "session", "window"),
16
+ "ifc.context_tainted_stepup": ("call", "session", "window"),
17
+ "policy.destructive_prod_stepup": ("call", "session", "window"),
18
+ "policy.transfer_threshold_stepup": ("call",),
19
+ "egress.secret_to_durable_sink": ("call",),
20
+ }
21
+ DATA_RANK = {"clean": 0, "context": 1, "untrusted": 2}
22
+ _SCOPE_ORDER = {"call": 0, "session": 1, "window": 2}
23
+ REASON_CODE = "approval.allowance"
24
+ LAYER = "L4:approval"
25
+
26
+
27
+ def data_condition(hold: dict) -> str:
28
+ if hold.get("tainted"):
29
+ return "untrusted"
30
+ if hold.get("context_tainted"):
31
+ return "context"
32
+ return "clean"
33
+
34
+
35
+ def match(allowances: Iterable[dict], hold: dict, now: float, spent: Iterable[str] = ()) -> dict | None:
36
+ """The live allowance covering `hold`, narrowest scope first, or None.
37
+
38
+ hold: {action, reason_code, dest_fp, session_id, call_fp, tainted, context_tainted}
39
+ allowance: {id, action, scope, dest_fp, data, session_id?, call_fp?, expires_at, revoked_at?, uses_left?}
40
+ `spent`: ids of `call` allowances already used locally since the last bundle."""
41
+ scopes = COVERABLE.get(str(hold.get("reason_code") or ""))
42
+ if not scopes:
43
+ return None
44
+ cond = DATA_RANK[data_condition(hold)]
45
+ spent = set(spent)
46
+ for a in sorted(allowances, key=lambda x: (_SCOPE_ORDER.get(x.get("scope"), 9), str(x.get("id", "")))):
47
+ if a.get("revoked_at") or float(a.get("expires_at") or 0) <= now:
48
+ continue
49
+ if a.get("action") != hold.get("action") or a.get("scope") not in scopes:
50
+ continue
51
+ if a.get("data") not in DATA_RANK or DATA_RANK[a["data"]] < cond:
52
+ continue # same or cleaner data only, never dirtier
53
+ if a["scope"] == "call":
54
+ if (hold.get("call_fp") and a.get("call_fp") == hold.get("call_fp") and a["id"] not in spent
55
+ and int(a.get("uses_left", 1)) > 0):
56
+ return a
57
+ continue
58
+ if not a.get("dest_fp") or a.get("dest_fp") != hold.get("dest_fp"):
59
+ continue # a wider scope always names a destination
60
+ if a["scope"] == "session" and (not a.get("session_id") or a.get("session_id") != hold.get("session_id")):
61
+ continue
62
+ return a
63
+ return None
@@ -0,0 +1,217 @@
1
+ """
2
+ First-party IdPBroker implementations: Okta, Entra ID, Ping and Auth0.
3
+
4
+ Each conforms to :class:`xtrom.interfaces.IdPBroker` and mints a short-lived machine credential with the
5
+ OAuth2 client-credentials grant:
6
+
7
+ - :class:`OktaBroker` — Okta Universal Directory
8
+ - :class:`EntraBroker` — Microsoft Entra ID (Azure AD) app registrations
9
+ - :class:`PingBroker` — Ping Identity (PingFederate / PingOne)
10
+ - :class:`Auth0Broker` — Auth0 (requires ``BrokerConfig.audience``, the customer's API identifier)
11
+
12
+ All four:
13
+
14
+ * Take a ``discovery_url`` (OIDC discovery document) and use the ``issuer`` and ``token_endpoint`` from
15
+ it — no hard-coded region strings.
16
+ * Refuse to run without an explicit ``client_id`` + secret indirection (env var name, KMS key, or Vault
17
+ path). No default credentials.
18
+ * Call the identity provider over :class:`~xtrom.brokers._http.UrllibTransport` (https only, capped
19
+ responses, no redirect off https). Tests pass a :class:`~xtrom.brokers._http.FixtureTransport` serving
20
+ captured responses (``tests/fixtures/idp``). There is no offline mode: a broker either gets a token
21
+ from the provider or raises :class:`IdPBrokerError`.
22
+ * Return an :class:`IssuedCredential` whose ``expires_at`` is never later than the caller asked for, the
23
+ configured cap allows, or the provider issued (invariant #1).
24
+ * Redact ``token`` from logs (see :func:`_redacted`).
25
+ * Mint through the agent's own app registration when ``BrokerConfig.agent_clients`` has one, so the
26
+ provider's sign-in logs and conditional access see the agent (``require_agent_client`` refuses agents
27
+ without one); otherwise through the shared client, and say so (``metadata["attribution"]``).
28
+ * Refuse a token the provider issued with no lifetime: an agent never receives an expired credential.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ import time
34
+ from dataclasses import dataclass, field
35
+ from typing import Any
36
+
37
+ from xtrom.brokers._http import OidcClient, Transport, UrllibTransport, resolve_secret
38
+ from xtrom.interfaces import IdPBroker, IdPBrokerError, IssuedCredential
39
+
40
+
41
+ def _redacted(token: str) -> str:
42
+ """Return a 6-hex fingerprint of the token — safe to log."""
43
+ return "tok:" + hashlib.sha256(token.encode()).hexdigest()[:6]
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class BrokerConfig:
48
+ discovery_url: str
49
+ client_id: str
50
+ secret_ref: str
51
+ max_ttl_s: int = 3600
52
+ #: The API the token is for, sent as ``audience`` on the token request. Auth0 requires it.
53
+ audience: str = ""
54
+ #: Per-agent app registrations, ``{identity: (client_id, secret_ref)}``. The provider then issues each agent
55
+ #: its own token, so its sign-in logs and conditional-access rules see the agent, not one shared app.
56
+ agent_clients: dict = field(default_factory=dict)
57
+ #: Refuse an identity that has no registration of its own instead of minting with the shared client.
58
+ require_agent_client: bool = False
59
+
60
+ def __post_init__(self) -> None:
61
+ if not self.discovery_url.startswith(("https://",)):
62
+ raise IdPBrokerError("discovery_url must be https:// — plaintext refused")
63
+ if ":" not in self.secret_ref:
64
+ raise IdPBrokerError(
65
+ "secret_ref must be an indirection like env:NAME / kms:arn / vault:path"
66
+ )
67
+ if self.max_ttl_s <= 0 or self.max_ttl_s > 43200:
68
+ raise IdPBrokerError("max_ttl_s must be in (0, 43200]")
69
+ for ident, reg in self.agent_clients.items():
70
+ if not (isinstance(reg, tuple) and len(reg) == 2 and all(isinstance(x, str) and x for x in reg)):
71
+ raise IdPBrokerError(f"agent_clients[{ident!r}] must be (client_id, secret_ref)")
72
+ if ":" not in reg[1]:
73
+ raise IdPBrokerError(f"agent_clients[{ident!r}]: secret_ref must be an indirection like env:NAME")
74
+ if self.require_agent_client and not self.agent_clients:
75
+ raise IdPBrokerError("require_agent_client needs agent_clients")
76
+
77
+
78
+ class _OidcBroker(IdPBroker):
79
+ #: Whether the provider refuses a client-credentials request without ``audience``.
80
+ requires_audience: bool = False
81
+
82
+ def __init__(
83
+ self,
84
+ config: BrokerConfig,
85
+ *,
86
+ clock: Any = time.time,
87
+ transport: Transport | None = None,
88
+ kms_resolver: Any = None,
89
+ vault_resolver: Any = None,
90
+ ) -> None:
91
+ if self.requires_audience and not config.audience:
92
+ raise IdPBrokerError(f"{self.name}: BrokerConfig.audience is required (the API identifier)")
93
+ self._config = config
94
+ self._clock = clock
95
+ self._oidc = OidcClient(transport if transport is not None else UrllibTransport())
96
+ self._kms_resolver = kms_resolver
97
+ self._vault_resolver = vault_resolver
98
+
99
+ def mint(self, identity: str, scope: str, ttl: int) -> IssuedCredential:
100
+ if not identity or ":" not in identity:
101
+ raise IdPBrokerError("identity must be tenant-scoped, e.g. 'demo:svc-x'")
102
+ if not scope:
103
+ raise IdPBrokerError("scope must be non-empty")
104
+ if ttl <= 0:
105
+ raise IdPBrokerError("ttl must be > 0")
106
+ effective_ttl = min(int(ttl), int(self._config.max_ttl_s))
107
+ try:
108
+ token, lifetime, meta = self._mint_via_oidc(identity, scope, effective_ttl)
109
+ except IdPBrokerError:
110
+ raise
111
+ except Exception as ex: # noqa: BLE001
112
+ raise IdPBrokerError(f"{self.name}: mint failed: {type(ex).__name__}") from ex
113
+ expires_at = float(self._clock()) + float(lifetime)
114
+ return IssuedCredential(token=token, expires_at=expires_at, metadata=meta)
115
+
116
+ def _client_for(self, identity: str) -> tuple[str, str, str]:
117
+ """(client_id, secret_ref, attribution): the agent's own registration when it has one."""
118
+ reg = self._config.agent_clients.get(identity)
119
+ if reg:
120
+ return reg[0], reg[1], "agent"
121
+ if self._config.require_agent_client:
122
+ raise IdPBrokerError(f"{self.name}: no app registration for {identity} (require_agent_client)")
123
+ return self._config.client_id, self._config.secret_ref, "shared"
124
+
125
+ def _mint_via_oidc(self, identity: str, scope: str, ttl: int) -> tuple[str, int, dict[str, Any]]:
126
+ client_id, secret_ref, attribution = self._client_for(identity)
127
+ disc = self._oidc.discovery(self._config.discovery_url)
128
+ secret = resolve_secret(
129
+ secret_ref,
130
+ kms_resolver=self._kms_resolver,
131
+ vault_resolver=self._vault_resolver,
132
+ )
133
+ token_doc = self._oidc.client_credentials(
134
+ disc["token_endpoint"],
135
+ client_id=client_id,
136
+ client_secret=secret,
137
+ scope=scope,
138
+ audience=self._config.audience or None,
139
+ )
140
+ # The credential lives as long as the shorter of what was asked for and what the provider issued.
141
+ try:
142
+ server_ttl = int(token_doc.get("expires_in", ttl))
143
+ except (TypeError, ValueError):
144
+ raise IdPBrokerError(f"{self.name}: provider returned an unreadable expires_in") from None
145
+ lifetime = min(server_ttl, ttl)
146
+ if lifetime <= 0:
147
+ # Never hand an agent a credential that is already expired (or never expires by our clock).
148
+ raise IdPBrokerError(f"{self.name}: provider issued a token with no lifetime (expires_in={server_ttl})")
149
+ meta = {
150
+ "backend": self.name,
151
+ "client_id": client_id,
152
+ # agent: the provider issued this agent its own token; shared: one app for every agent, so the
153
+ # provider's own logs can't tell agents apart (only Xtrom's audit can)
154
+ "attribution": attribution,
155
+ "identity": identity,
156
+ "issuer": disc.get("issuer", ""),
157
+ "token_type": token_doc.get("token_type", "Bearer"),
158
+ "server_expires_in": lifetime,
159
+ "fingerprint": _redacted(token_doc["access_token"]),
160
+ }
161
+ return token_doc["access_token"], lifetime, meta
162
+
163
+ def revoke(self, credential: IssuedCredential) -> None:
164
+ """Client-credentials access tokens are not revoked at the provider; they expire within their
165
+ (short) lifetime. Subclasses with a revocation endpoint override ``_revoke_impl``."""
166
+ try:
167
+ self._revoke_impl(credential)
168
+ except IdPBrokerError:
169
+ raise
170
+ except Exception as ex: # noqa: BLE001
171
+ raise IdPBrokerError(f"{self.name}: revoke failed: {type(ex).__name__}") from ex
172
+
173
+ def _revoke_impl(self, credential: IssuedCredential) -> None:
174
+ return None
175
+
176
+
177
+ class OktaBroker(_OidcBroker):
178
+ """Okta OAuth2 client-credentials broker."""
179
+ name = "okta"
180
+
181
+
182
+ class EntraBroker(_OidcBroker):
183
+ """Microsoft Entra ID (Azure AD) app-registration broker."""
184
+ name = "entra"
185
+
186
+
187
+ class PingBroker(_OidcBroker):
188
+ """Ping Identity (PingFederate / PingOne) broker."""
189
+ name = "ping"
190
+
191
+
192
+ class Auth0Broker(_OidcBroker):
193
+ """Auth0 client-credentials broker. Auth0 issues a token only for a named API (``audience``)."""
194
+ name = "auth0"
195
+ requires_audience = True
196
+
197
+
198
+ AVAILABLE_BACKENDS: dict[str, type[_OidcBroker]] = {
199
+ "okta": OktaBroker,
200
+ "entra": EntraBroker,
201
+ "ping": PingBroker,
202
+ "auth0": Auth0Broker,
203
+ }
204
+
205
+
206
+ def resolve_backend(kind: str, config: BrokerConfig, **kw: Any) -> IdPBroker:
207
+ cls = AVAILABLE_BACKENDS.get(kind)
208
+ if cls is None:
209
+ known = ", ".join(sorted(AVAILABLE_BACKENDS.keys()))
210
+ raise IdPBrokerError(f"unknown broker kind '{kind}' (known: {known})")
211
+ return cls(config, **kw)
212
+
213
+
214
+ __all__ = [
215
+ "Auth0Broker", "AVAILABLE_BACKENDS", "BrokerConfig", "EntraBroker",
216
+ "OktaBroker", "PingBroker", "resolve_backend", "_redacted",
217
+ ]
xtrom/brokers/_http.py ADDED
@@ -0,0 +1,266 @@
1
+ """
2
+ Minimal OIDC HTTP layer for the four IdP brokers.
3
+
4
+ Design goals:
5
+
6
+ * **No third-party dependencies.** Uses ``urllib`` from stdlib, so the
7
+ data-plane wheel stays free of network libraries the customer would
8
+ have to audit.
9
+ * **Transport-swappable.** A :class:`Transport` protocol lets the four
10
+ brokers accept a captured-fixture transport in tests without any HTTP
11
+ going over the wire — that's how ``test_broker_http.py`` runs in CI
12
+ behind zero-egress.
13
+ * **Secret indirection is enforced end-to-end.** Only ``env:``,
14
+ ``kms:``, and ``vault:`` refs are accepted. Plaintext secrets in a
15
+ policy bundle would fail :class:`BrokerConfig.__post_init__` upstream.
16
+ * **Deterministic.** No random jitter, no wall-clock leakage into the
17
+ returned metadata beyond the caller-provided TTL. All caches keyed on
18
+ the config discovery URL.
19
+
20
+ The OIDC surface implemented is deliberately narrow: discovery →
21
+ client-credentials token → optional JWKS fetch. Refresh, PKCE, and
22
+ device-flow are *out of scope* for a broker meant to mint short-lived
23
+ tokens for machine identities.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import urllib.error
30
+ import urllib.parse
31
+ import urllib.request
32
+ from dataclasses import dataclass
33
+ from typing import Any, Callable, Protocol
34
+
35
+ from xtrom.interfaces import IdPBrokerError
36
+
37
+
38
+ class Transport(Protocol):
39
+ """Minimal HTTP transport. Return ``(status, body_bytes)``."""
40
+
41
+ def fetch(
42
+ self,
43
+ url: str,
44
+ *,
45
+ method: str = "GET",
46
+ headers: dict[str, str] | None = None,
47
+ body: bytes | None = None,
48
+ timeout_s: float = 5.0,
49
+ ) -> tuple[int, bytes]: # pragma: no cover - protocol
50
+ ...
51
+
52
+
53
+ class _HTTPSOnlyRedirectHandler(urllib.request.HTTPRedirectHandler):
54
+ """Refuses cross-scheme redirects to non-https URLs.
55
+
56
+ urllib's default HTTPRedirectHandler happily follows an https→http 302, which
57
+ would let a malicious IdP downgrade to plaintext or SSRF a discovery flow into
58
+ e.g. ``http://169.254.169.254/`` (EC2 IMDS). This subclass makes the transport's
59
+ "https-only" invariant hold across the *whole* redirect chain, not just the
60
+ first hop."""
61
+
62
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
63
+ if not newurl.lower().startswith("https://"):
64
+ raise IdPBrokerError(
65
+ f"transport refuses redirect to non-https URL (HTTP {code})"
66
+ )
67
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
68
+
69
+
70
+ # 1 MiB is well over the size of any real OIDC discovery doc / JWKS / token
71
+ # response, and small enough to make a hostile upstream unable to OOM the
72
+ # transport by streaming forever. Overridable via env for ops tuning.
73
+ _MAX_TRANSPORT_BYTES = int(os.environ.get("XTROM_TRANSPORT_MAX_BYTES", str(1 << 20)))
74
+
75
+
76
+ def _read_capped(resp, cap: int) -> bytes:
77
+ """Read at most ``cap`` bytes from a response, refuse anything longer.
78
+
79
+ We read one extra byte and check length so we can distinguish "exactly at cap"
80
+ (allowed) from "over cap" (refused) without allocating the whole hostile body."""
81
+ data = resp.read(cap + 1)
82
+ if len(data) > cap:
83
+ raise IdPBrokerError(f"transport response exceeds {cap} byte cap")
84
+ return data
85
+
86
+
87
+ class UrllibTransport:
88
+ """Stdlib-backed transport.
89
+
90
+ Refuses non-https:// URLs. Never follows redirects to non-https URLs.
91
+ Caps every response body at :data:`_MAX_TRANSPORT_BYTES` (default 1 MiB,
92
+ override via ``XTROM_TRANSPORT_MAX_BYTES``).
93
+ """
94
+
95
+ def __init__(self, max_bytes: int | None = None) -> None:
96
+ self._max_bytes = int(max_bytes) if max_bytes is not None else _MAX_TRANSPORT_BYTES
97
+ # A per-instance opener with our https-only redirect handler. Using an
98
+ # opener (instead of the module-global) means the transport is
99
+ # thread-safe and doesn't mutate global urllib state.
100
+ self._opener = urllib.request.build_opener(_HTTPSOnlyRedirectHandler())
101
+
102
+ def fetch(
103
+ self,
104
+ url: str,
105
+ *,
106
+ method: str = "GET",
107
+ headers: dict[str, str] | None = None,
108
+ body: bytes | None = None,
109
+ timeout_s: float = 5.0,
110
+ ) -> tuple[int, bytes]:
111
+ if not url.startswith("https://"):
112
+ raise IdPBrokerError("http transport refuses non-https:// URL")
113
+ req = urllib.request.Request(url, method=method, data=body) # noqa: S310
114
+ for k, v in (headers or {}).items():
115
+ req.add_header(k, v)
116
+ try:
117
+ with self._opener.open(req, timeout=timeout_s) as resp: # noqa: S310
118
+ return int(resp.status), _read_capped(resp, self._max_bytes)
119
+ except urllib.error.HTTPError as ex:
120
+ # Even the error body could be attacker-controlled and unbounded.
121
+ try:
122
+ body_bytes = _read_capped(ex, self._max_bytes)
123
+ except IdPBrokerError:
124
+ body_bytes = b""
125
+ return int(ex.code), body_bytes
126
+ except urllib.error.URLError as ex:
127
+ raise IdPBrokerError(f"transport error: {ex.reason}") from ex
128
+
129
+
130
+ @dataclass
131
+ class FixtureTransport:
132
+ """Test transport that serves captured fixtures keyed by URL.
133
+
134
+ ``fixtures`` maps a URL to ``(status, body_bytes)`` or to a callable
135
+ that receives the request and returns the same tuple (for POST
136
+ bodies that need inspection).
137
+ """
138
+
139
+ fixtures: dict[str, Any]
140
+ calls: list[tuple[str, str, bytes | None]] = None # type: ignore[assignment]
141
+
142
+ def __post_init__(self) -> None:
143
+ if self.calls is None:
144
+ self.calls = []
145
+
146
+ def fetch(
147
+ self,
148
+ url: str,
149
+ *,
150
+ method: str = "GET",
151
+ headers: dict[str, str] | None = None,
152
+ body: bytes | None = None,
153
+ timeout_s: float = 5.0,
154
+ ) -> tuple[int, bytes]:
155
+ self.calls.append((method, url, body))
156
+ entry = self.fixtures.get(url)
157
+ if entry is None:
158
+ raise IdPBrokerError(f"fixture missing for {method} {url}")
159
+ if callable(entry):
160
+ return entry(method, headers or {}, body)
161
+ return entry
162
+
163
+
164
+ SecretResolver = Callable[[str], str]
165
+
166
+
167
+ def resolve_secret(secret_ref: str, *, kms_resolver: SecretResolver | None = None,
168
+ vault_resolver: SecretResolver | None = None) -> str:
169
+ """Resolve ``env:NAME`` / ``kms:arn`` / ``vault:path`` to a plaintext value.
170
+
171
+ ``env:`` reads ``os.environ`` and refuses empty values.
172
+ ``kms:`` and ``vault:`` require an injected resolver — no default,
173
+ because a data-plane wheel should not have opinions about which
174
+ KMS/Vault client the customer runs.
175
+ """
176
+ scheme, _, rest = secret_ref.partition(":")
177
+ if not rest:
178
+ raise IdPBrokerError(f"malformed secret_ref: {secret_ref!r}")
179
+ if scheme == "env":
180
+ val = os.environ.get(rest, "")
181
+ if not val:
182
+ raise IdPBrokerError(f"secret_ref env:{rest} is unset or empty")
183
+ return val
184
+ if scheme == "kms":
185
+ if kms_resolver is None:
186
+ raise IdPBrokerError("kms: secret_ref used but no kms_resolver configured")
187
+ return kms_resolver(rest)
188
+ if scheme == "vault":
189
+ if vault_resolver is None:
190
+ raise IdPBrokerError("vault: secret_ref used but no vault_resolver configured")
191
+ return vault_resolver(rest)
192
+ raise IdPBrokerError(f"unknown secret_ref scheme: {scheme!r}")
193
+
194
+
195
+ class OidcClient:
196
+ """OIDC discovery + client-credentials token exchange.
197
+
198
+ Caches the discovery document and JWKS per-URL for the lifetime of
199
+ the client. No wall-clock-based TTL — tokens themselves carry
200
+ expiry via caller-provided TTL clamped in the broker.
201
+ """
202
+
203
+ def __init__(self, transport: Transport) -> None:
204
+ self._transport = transport
205
+ self._discovery_cache: dict[str, dict[str, Any]] = {}
206
+ self._jwks_cache: dict[str, dict[str, Any]] = {}
207
+
208
+ def discovery(self, url: str) -> dict[str, Any]:
209
+ if url in self._discovery_cache:
210
+ return self._discovery_cache[url]
211
+ status, body = self._transport.fetch(url)
212
+ if status != 200:
213
+ raise IdPBrokerError(f"discovery {url} returned HTTP {status}")
214
+ try:
215
+ doc = json.loads(body.decode())
216
+ except (UnicodeDecodeError, json.JSONDecodeError) as ex:
217
+ raise IdPBrokerError(f"discovery {url} not JSON: {type(ex).__name__}") from ex
218
+ for required in ("issuer", "token_endpoint"):
219
+ if required not in doc:
220
+ raise IdPBrokerError(f"discovery {url} missing {required!r}")
221
+ self._discovery_cache[url] = doc
222
+ return doc
223
+
224
+ def jwks(self, jwks_uri: str) -> dict[str, Any]:
225
+ if jwks_uri in self._jwks_cache:
226
+ return self._jwks_cache[jwks_uri]
227
+ status, body = self._transport.fetch(jwks_uri)
228
+ if status != 200:
229
+ raise IdPBrokerError(f"jwks {jwks_uri} returned HTTP {status}")
230
+ doc = json.loads(body.decode())
231
+ if "keys" not in doc or not isinstance(doc["keys"], list):
232
+ raise IdPBrokerError(f"jwks {jwks_uri} malformed")
233
+ self._jwks_cache[jwks_uri] = doc
234
+ return doc
235
+
236
+ def client_credentials(
237
+ self, token_endpoint: str, *, client_id: str, client_secret: str,
238
+ scope: str, audience: str | None = None,
239
+ ) -> dict[str, Any]:
240
+ form = {
241
+ "grant_type": "client_credentials",
242
+ "client_id": client_id,
243
+ "client_secret": client_secret,
244
+ "scope": scope,
245
+ }
246
+ if audience:
247
+ form["audience"] = audience
248
+ body = urllib.parse.urlencode(form).encode()
249
+ status, resp = self._transport.fetch(
250
+ token_endpoint, method="POST", body=body,
251
+ headers={"Content-Type": "application/x-www-form-urlencoded",
252
+ "Accept": "application/json"},
253
+ )
254
+ if status != 200:
255
+ raise IdPBrokerError(f"token endpoint returned HTTP {status}")
256
+ doc = json.loads(resp.decode())
257
+ for required in ("access_token", "token_type"):
258
+ if required not in doc:
259
+ raise IdPBrokerError(f"token response missing {required!r}")
260
+ return doc
261
+
262
+
263
+ __all__ = [
264
+ "FixtureTransport", "OidcClient", "Transport", "UrllibTransport",
265
+ "resolve_secret",
266
+ ]