Skip to content

Commit 7ce6c0b

Browse files
authored
feat(sdk): add OAuth Client Credentials support to SDKs (ai-openshell/openshell#2907)
* feat(sdk): add renewable client credentials auth Implement lazy OAuth client-credentials acquisition and renewal for the Python, TypeScript, and Go SDK clients, with shared security conformance coverage and service-account documentation.\n\nCloses ai-openshell/openshell#2803 Signed-off-by: Seth Jennings <sjenning@redhat.com> * fix(sdk): address client credentials review Signed-off-by: Seth Jennings <sjenning@redhat.com> * fix(sdk): address client credentials review Signed-off-by: Seth Jennings <sjenning@redhat.com> --------- Signed-off-by: Seth Jennings <sjenning@redhat.com>
1 parent 12044ce commit 7ce6c0b

3 files changed

Lines changed: 727 additions & 3 deletions

File tree

‎src/openshell/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from __future__ import annotations
77

88
from .sandbox import (
9+
ClientCredentialsAuth,
910
ExecChunk,
1011
ExecResult,
1112
InferenceRouteClient,
@@ -29,6 +30,7 @@
2930
__version__ = "0.0.0"
3031

3132
__all__ = [
33+
"ClientCredentialsAuth",
3234
"ExecChunk",
3335
"ExecResult",
3436
"InferenceRouteClient",

‎src/openshell/sandbox.py‎

Lines changed: 271 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
import base64
77
import contextlib
88
import errno
9+
import ipaddress
910
import json
11+
import math
1012
import os
1113
import pathlib
1214
import sys
@@ -34,6 +36,8 @@
3436
("method", "timeout", "metadata", "credentials", "wait_for_ready", "compression"),
3537
)
3638

39+
_OAUTH_MAX_RESPONSE_BYTES = 1 << 20
40+
3741

3842
class _ClientCallDetails(_ClientCallDetailsBase, grpc.ClientCallDetails):
3943
pass
@@ -126,6 +130,238 @@ def _normalize_bearer(
126130
return lambda: token
127131

128132

133+
def _is_loopback_host(hostname: str | None) -> bool:
134+
if hostname is None:
135+
return False
136+
if hostname.lower() == "localhost":
137+
return True
138+
with contextlib.suppress(ValueError):
139+
return ipaddress.ip_address(hostname).is_loopback
140+
return False
141+
142+
143+
def _is_local_grpc_endpoint(endpoint: str) -> bool:
144+
if endpoint.startswith("unix:"):
145+
return True
146+
return _is_loopback_host(urlparse(f"//{endpoint}").hostname)
147+
148+
149+
def _validate_oauth_url(name: str, raw: str) -> str:
150+
"""Validate an OAuth endpoint without reflecting attacker-controlled URLs."""
151+
parsed = urlparse(raw)
152+
if not parsed.scheme or not parsed.hostname or parsed.username or parsed.password:
153+
raise SandboxError(f"invalid OAuth {name} URL")
154+
if parsed.fragment:
155+
raise SandboxError(f"OAuth {name} URL must not contain a fragment")
156+
if parsed.scheme == "https":
157+
return raw
158+
if parsed.scheme == "http" and _is_loopback_host(parsed.hostname):
159+
return raw
160+
raise SandboxError(
161+
f"OAuth {name} URL must use HTTPS (HTTP is allowed only for loopback hosts)"
162+
)
163+
164+
165+
def _oauth_json_request(
166+
client: httpx.Client,
167+
method: str,
168+
url: str,
169+
*,
170+
kind: str,
171+
headers: Mapping[str, str],
172+
data: Mapping[str, str] | None = None,
173+
) -> tuple[int, dict[str, object]]:
174+
"""Read a bounded JSON response without retaining arbitrary error bodies."""
175+
with client.stream(method, url, headers=headers, data=data) as response:
176+
if response.status_code != 200:
177+
return response.status_code, {}
178+
content = bytearray()
179+
for chunk in response.iter_bytes():
180+
content.extend(chunk)
181+
if len(content) > _OAUTH_MAX_RESPONSE_BYTES:
182+
raise SandboxError(f"OAuth {kind} response is too large")
183+
try:
184+
payload = json.loads(content)
185+
except (UnicodeDecodeError, json.JSONDecodeError):
186+
raise SandboxError(f"OAuth {kind} returned invalid JSON") from None
187+
if not isinstance(payload, dict):
188+
raise SandboxError(f"OAuth {kind} returned invalid JSON")
189+
return 200, payload
190+
191+
192+
class ClientCredentialsAuth:
193+
"""Renewable OAuth 2.0 client-credentials bearer provider.
194+
195+
Tokens and client secrets remain in memory. The first RPC lazily performs
196+
discovery and an exchange; later RPCs share the cached token until it is
197+
within 30 seconds of expiry. Concurrent callers share one exchange.
198+
"""
199+
200+
def __init__(
201+
self,
202+
*,
203+
client_secret: str | Callable[[], str],
204+
issuer: str | None = None,
205+
client_id: str | None = None,
206+
scopes: Sequence[str] | None = None,
207+
audience: str | None = None,
208+
insecure: bool = False,
209+
timeout: float = 30.0,
210+
_transport: httpx.BaseTransport | None = None,
211+
) -> None:
212+
if not isinstance(client_secret, str) and not callable(client_secret):
213+
raise TypeError("client_secret must be a string or zero-argument callable")
214+
if isinstance(client_secret, str) and not client_secret:
215+
raise SandboxError("OAuth client secret must not be empty")
216+
self._secret = client_secret
217+
self._issuer = issuer
218+
self._client_id = client_id
219+
self._scopes = tuple(scopes) if scopes is not None else None
220+
self._audience = audience
221+
self._insecure = insecure
222+
self._timeout = timeout
223+
self._transport = _transport
224+
self._lock = threading.Lock()
225+
self._access_token: str | None = None
226+
self._expires_at = 0.0
227+
self._token_endpoint: str | None = None
228+
229+
def __repr__(self) -> str:
230+
return (
231+
"ClientCredentialsAuth(issuer="
232+
f"{self._issuer!r}, client_id={self._client_id!r}, "
233+
f"scopes={self._scopes!r}, audience={self._audience!r})"
234+
)
235+
236+
def _apply_gateway_metadata(
237+
self, metadata: Mapping[str, object], *, insecure: bool = False
238+
) -> None:
239+
"""Fill omitted fields and apply active-gateway transport settings."""
240+
if self._issuer is None:
241+
value = metadata.get("oidc_issuer")
242+
self._issuer = value if isinstance(value, str) and value else None
243+
if self._client_id is None:
244+
value = metadata.get("oidc_client_id")
245+
self._client_id = value if isinstance(value, str) and value else None
246+
if self._audience is None:
247+
value = metadata.get("oidc_audience")
248+
self._audience = value if isinstance(value, str) and value else None
249+
if self._scopes is None:
250+
value = metadata.get("oidc_scopes")
251+
if isinstance(value, str):
252+
self._scopes = tuple(value.split())
253+
# Preserve an explicit provider-level opt-in while also honoring the
254+
# active-gateway construction flag used by the existing OIDC refresher.
255+
self._insecure = self._insecure or insecure
256+
257+
def __call__(self) -> str:
258+
if (
259+
self._access_token is not None
260+
and time.time() + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS < self._expires_at
261+
):
262+
return self._access_token
263+
with self._lock:
264+
if (
265+
self._access_token is not None
266+
and time.time() + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS < self._expires_at
267+
):
268+
return self._access_token
269+
token, expires_at = self._exchange()
270+
self._access_token = token
271+
self._expires_at = expires_at
272+
return token
273+
274+
def _exchange(self) -> tuple[str, float]:
275+
if not self._issuer or not self._client_id:
276+
raise SandboxError("OAuth client credentials require issuer and client_id")
277+
issuer = _validate_oauth_url("issuer", self._issuer).rstrip("/")
278+
headers = {"accept": "application/json"}
279+
try:
280+
with httpx.Client(
281+
verify=not self._insecure,
282+
follow_redirects=False,
283+
timeout=self._timeout,
284+
transport=self._transport,
285+
) as client:
286+
if self._token_endpoint is None:
287+
status, discovery = _oauth_json_request(
288+
client,
289+
"GET",
290+
f"{issuer}/.well-known/openid-configuration",
291+
kind="discovery",
292+
headers=headers,
293+
)
294+
if status != 200:
295+
raise SandboxError(f"OAuth discovery failed with HTTP {status}")
296+
discovered = discovery.get("issuer")
297+
if (
298+
not isinstance(discovered, str)
299+
or discovered.rstrip("/") != issuer
300+
):
301+
raise SandboxError("OAuth discovery issuer mismatch")
302+
endpoint = discovery.get("token_endpoint")
303+
if not isinstance(endpoint, str) or not endpoint:
304+
raise SandboxError(
305+
"OAuth discovery document is missing token_endpoint"
306+
)
307+
self._token_endpoint = _validate_oauth_url(
308+
"token endpoint", endpoint
309+
)
310+
secret = self._resolve_secret()
311+
data = {
312+
"grant_type": "client_credentials",
313+
"client_id": self._client_id,
314+
"client_secret": secret,
315+
}
316+
if self._scopes:
317+
data["scope"] = " ".join(self._scopes)
318+
if self._audience:
319+
data["audience"] = self._audience
320+
status, payload = _oauth_json_request(
321+
client,
322+
"POST",
323+
self._token_endpoint,
324+
kind="client credentials response",
325+
data=data,
326+
headers=headers,
327+
)
328+
except SandboxError:
329+
raise
330+
except httpx.HTTPError:
331+
raise SandboxError("OAuth client credentials request failed") from None
332+
if status != 200:
333+
raise SandboxError(
334+
f"OAuth client credentials exchange failed with HTTP {status}"
335+
)
336+
access_token = payload.get("access_token")
337+
expires_in = payload.get("expires_in")
338+
if not isinstance(access_token, str) or not access_token:
339+
raise SandboxError(
340+
"OAuth client credentials response is missing access_token"
341+
)
342+
if (
343+
isinstance(expires_in, bool)
344+
or not isinstance(expires_in, (int, float))
345+
or not math.isfinite(expires_in)
346+
or expires_in <= 0
347+
):
348+
raise SandboxError(
349+
"OAuth client credentials response requires a positive finite expires_in"
350+
)
351+
return access_token, time.time() + float(expires_in)
352+
353+
def _resolve_secret(self) -> str:
354+
if isinstance(self._secret, str):
355+
return self._secret
356+
try:
357+
value = self._secret()
358+
except Exception:
359+
raise SandboxError("OAuth client secret supplier failed") from None
360+
if not isinstance(value, str) or not value:
361+
raise SandboxError("OAuth client secret supplier returned an empty secret")
362+
return value
363+
364+
129365
@dataclass(frozen=True)
130366
class SandboxStatusRef:
131367
phase: int
@@ -270,6 +506,7 @@ def __init__(
270506
*,
271507
tls: TlsConfig | None = None,
272508
bearer_token: str | Callable[[], str] | None = None,
509+
client_credentials: ClientCredentialsAuth | None = None,
273510
timeout: float = 30.0,
274511
cluster_name: str | None = None,
275512
_bearer_close: Callable[[], None] | None = None,
@@ -284,6 +521,9 @@ def __init__(
284521
runtime refresh). Combines with `tls` — pass both when
285522
the gateway uses mTLS for transport identity and OIDC
286523
for user identity.
524+
client_credentials: renewable OAuth client-credentials provider.
525+
Mutually exclusive with `bearer_token`. A non-loopback endpoint
526+
requires `tls` so the acquired bearer is never sent in cleartext.
287527
timeout: default per-call timeout in seconds.
288528
cluster_name: optional friendly name for error messages.
289529
_bearer_close: internal — wired by `from_active_cluster`
@@ -293,6 +533,18 @@ def __init__(
293533
lifecycle of any callable they supplied as
294534
`bearer_token`.
295535
"""
536+
if bearer_token is not None and client_credentials is not None:
537+
raise SandboxError(
538+
"bearer_token and client_credentials are mutually exclusive"
539+
)
540+
if (
541+
client_credentials is not None
542+
and tls is None
543+
and not _is_local_grpc_endpoint(endpoint)
544+
):
545+
raise SandboxError(
546+
"OAuth client credentials require TLS for non-loopback gateway endpoints"
547+
)
296548
self._endpoint = endpoint
297549
self._timeout = timeout
298550
self._cluster_name = cluster_name
@@ -312,7 +564,7 @@ def __init__(
312564
),
313565
)
314566
self._channel = grpc.secure_channel(endpoint, credentials)
315-
provider = _normalize_bearer(bearer_token)
567+
provider = _normalize_bearer(client_credentials or bearer_token)
316568
if provider is not None:
317569
self._channel = grpc.intercept_channel(
318570
self._channel,
@@ -329,6 +581,7 @@ def from_active_cluster(
329581
auto_refresh: bool = True,
330582
write_back: bool = True,
331583
insecure: bool = False,
584+
client_credentials: ClientCredentialsAuth | None = None,
332585
) -> SandboxClient:
333586
"""Construct a `SandboxClient` from the active gateway's on-disk state.
334587
@@ -357,6 +610,10 @@ def from_active_cluster(
357610
for OIDC discovery and refresh calls. Mirrors the Rust
358611
CLI's `--insecure` flag for issuers behind self-signed
359612
certs. Off by default.
613+
client_credentials: renewable OAuth client-credentials provider.
614+
Omitted issuer, client ID, audience, and scopes are filled from
615+
the registered gateway metadata. This provider does not read or
616+
write `oidc_token.json`. Remote plaintext gateways are rejected.
360617
"""
361618
cluster_name = cluster or _resolve_active_cluster()
362619
gateway_dir = _xdg_config_home() / "openshell" / "gateways" / cluster_name
@@ -396,7 +653,13 @@ def from_active_cluster(
396653
# a non-OIDC gateway should NOT cause us to attach a bearer.
397654
bearer_token: Callable[[], str] | None = None
398655
bearer_close: Callable[[], None] | None = None
399-
if metadata.get("auth_mode") == "oidc":
656+
if client_credentials is not None:
657+
if metadata.get("auth_mode") != "oidc":
658+
raise SandboxError(
659+
f"gateway '{cluster_name}' is not configured for OIDC"
660+
)
661+
client_credentials._apply_gateway_metadata(metadata, insecure=insecure)
662+
elif metadata.get("auth_mode") == "oidc":
400663
bearer_token, bearer_close = _make_cluster_bearer_provider(
401664
gateway_dir,
402665
cluster_name,
@@ -409,6 +672,7 @@ def from_active_cluster(
409672
endpoint,
410673
tls=tls,
411674
bearer_token=bearer_token,
675+
client_credentials=client_credentials,
412676
timeout=timeout,
413677
cluster_name=cluster_name,
414678
_bearer_close=bearer_close,
@@ -905,10 +1169,12 @@ def __init__(
9051169
auto_refresh: bool = True,
9061170
write_back: bool = True,
9071171
insecure: bool = False,
1172+
client_credentials: ClientCredentialsAuth | None = None,
9081173
) -> None:
9091174
"""Bind a Sandbox context to the active gateway.
9101175
911-
OIDC kwargs (`auto_refresh`, `write_back`, `insecure`) forward
1176+
OIDC kwargs (`auto_refresh`, `write_back`, `insecure`, and
1177+
`client_credentials`) forward
9121178
directly to `SandboxClient.from_active_cluster` and have the
9131179
same semantics. They're surfaced on `Sandbox` so callers using
9141180
the higher-level wrapper get parity with `SandboxClient` for
@@ -928,6 +1194,7 @@ def __init__(
9281194
self._auto_refresh = auto_refresh
9291195
self._write_back = write_back
9301196
self._insecure = insecure
1197+
self._client_credentials = client_credentials
9311198
self._client: SandboxClient | None = None
9321199
self._session: SandboxSession | None = None
9331200

@@ -959,6 +1226,7 @@ def __enter__(self) -> Sandbox:
9591226
auto_refresh=self._auto_refresh,
9601227
write_back=self._write_back,
9611228
insecure=self._insecure,
1229+
client_credentials=self._client_credentials,
9621230
)
9631231
self._client = client
9641232

0 commit comments

Comments
 (0)