diff --git a/baseten/client/__init__.py b/baseten/client/__init__.py index a866705..9e3f193 100644 --- a/baseten/client/__init__.py +++ b/baseten/client/__init__.py @@ -5,6 +5,9 @@ for the inference API. :class:`SandboxClient` and :class:`AsyncSandboxClient` reach one sandbox's execution API directly; the higher-level surface lives in :mod:`baseten.sandbox`. + +To authenticate without an API key, pass :class:`WorkloadIdentityCredentials` +or :class:`AsyncWorkloadIdentityCredentials` as a client's ``credentials``. """ from baseten.client._inference import ( @@ -22,15 +25,37 @@ SandboxClient, SandboxClientOptions, ) +from baseten.client._token_auth import ( + AccessToken, + AccessTokenOptions, + AsyncCredentials, + Credentials, +) +from baseten.client._workload_identity import ( + AsyncIdentityTokenProvider, + AsyncWorkloadIdentityCredentials, + IdentityTokenProvider, + IdentityTokenProviderContext, + WorkloadIdentityCredentials, +) __all__ = [ + "AccessToken", + "AccessTokenOptions", + "AsyncCredentials", + "AsyncIdentityTokenProvider", "AsyncInferenceClient", "AsyncManagementClient", "AsyncSandboxClient", + "AsyncWorkloadIdentityCredentials", + "Credentials", + "IdentityTokenProvider", + "IdentityTokenProviderContext", "InferenceClient", "InferenceClientOptions", "ManagementClient", "ManagementClientOptions", "SandboxClient", "SandboxClientOptions", + "WorkloadIdentityCredentials", ] diff --git a/baseten/client/_inference.py b/baseten/client/_inference.py index 4f87a2b..9976bd2 100644 --- a/baseten/client/_inference.py +++ b/baseten/client/_inference.py @@ -7,6 +7,14 @@ import httpx import baseten.client.inferenceapi +from baseten.client._token_auth import ( + AsyncCredentials, + AsyncCredentialsAuth, + Credentials, + CredentialsAuth, + check_client_auth, + credentials_origin, +) from baseten.client._user_agent import with_user_agent @@ -18,8 +26,8 @@ class InferenceClientOptions: was constructed with. """ - api_key: str - """API key for authentication.""" + api_key: str | None + """API key for authentication, or ``None`` when *credentials* is set.""" headers: Mapping[str, str] | None = None """Additional headers to send on every request.""" @@ -37,6 +45,9 @@ class InferenceClientOptions: """Explicit base URL override. When set, *model_id*, *chain_id*, and *environment* are ignored.""" + credentials: Credentials | AsyncCredentials | None = None + """Supplies short-lived access tokens, used in place of *api_key*.""" + @property def base_url(self) -> str: """The resolved base URL for the inference API.""" @@ -88,7 +99,8 @@ def default_base_url( def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: Credentials | None = None, headers: Mapping[str, str] | None = None, model_id: str | None = None, chain_id: str | None = None, @@ -100,7 +112,13 @@ def __init__( """Create a new synchronous inference client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Supplies short-lived access tokens in place of an + API key, such as :class:`WorkloadIdentityCredentials`. A token + is fetched for every request, so a long-lived client picks up + refreshed tokens. It is sent only to this client's API host, + and each request is sent once. headers: Additional headers to send on every request. model_id: Model ID. Mutually exclusive with *chain_id*. chain_id: Chain ID. Mutually exclusive with *model_id*. @@ -110,11 +128,16 @@ def __init__( http_client_override: Pre-configured httpx client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = InferenceClientOptions( api_key=api_key, headers=headers, @@ -122,17 +145,29 @@ def __init__( chain_id=chain_id, environment=environment, base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else CredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.Client( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -146,7 +181,7 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.inferenceapi.ApiClient(self._http_client) + self._api = baseten.client.inferenceapi.ApiClient(self._http_client, auth=auth) @property def options(self) -> InferenceClientOptions: @@ -205,7 +240,8 @@ def default_base_url( def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: AsyncCredentials | None = None, headers: Mapping[str, str] | None = None, model_id: str | None = None, chain_id: str | None = None, @@ -217,7 +253,10 @@ def __init__( """Create a new asynchronous inference client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Supplies short-lived access tokens, as for + :class:`InferenceClient`. headers: Additional headers to send on every request. model_id: Model ID. Mutually exclusive with *chain_id*. chain_id: Chain ID. Mutually exclusive with *model_id*. @@ -227,11 +266,16 @@ def __init__( http_client_override: Pre-configured httpx async client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = InferenceClientOptions( api_key=api_key, headers=headers, @@ -239,17 +283,29 @@ def __init__( chain_id=chain_id, environment=environment, base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else AsyncCredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.AsyncClient( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -263,7 +319,9 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.inferenceapi.AsyncApiClient(self._http_client) + self._api = baseten.client.inferenceapi.AsyncApiClient( + self._http_client, auth=auth + ) @property def options(self) -> InferenceClientOptions: diff --git a/baseten/client/_management.py b/baseten/client/_management.py index 85dcda2..4e70910 100644 --- a/baseten/client/_management.py +++ b/baseten/client/_management.py @@ -7,6 +7,14 @@ import httpx import baseten.client.managementapi +from baseten.client._token_auth import ( + AsyncCredentials, + AsyncCredentialsAuth, + Credentials, + CredentialsAuth, + check_client_auth, + credentials_origin, +) from baseten.client._user_agent import with_user_agent @@ -18,8 +26,8 @@ class ManagementClientOptions: was constructed with. """ - api_key: str - """API key for authentication.""" + api_key: str | None + """API key for authentication, or ``None`` when *credentials* is set.""" headers: Mapping[str, str] | None = None """Additional headers to send on every request.""" @@ -27,6 +35,9 @@ class ManagementClientOptions: base_url_override: str | None = None """Explicit base URL override, or ``None`` to use the default.""" + credentials: Credentials | AsyncCredentials | None = None + """Supplies short-lived access tokens, used in place of *api_key*.""" + @property def base_url(self) -> str: """The resolved base URL for the management API.""" @@ -50,7 +61,8 @@ def default_base_url(cls) -> str: def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: Credentials | None = None, headers: Mapping[str, str] | None = None, base_url_override: str | None = None, http_client_override: httpx.Client | None = None, @@ -59,31 +71,56 @@ def __init__( """Create a new synchronous management client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Supplies short-lived access tokens in place of an + API key, such as :class:`WorkloadIdentityCredentials`. A token + is fetched for every request, so a long-lived client picks up + refreshed tokens. It is sent only to this client's API host, + and each request is sent once. headers: Additional headers to send on every request. base_url_override: Override the default base URL. When ``None``, :meth:`default_base_url` is used. http_client_override: Pre-configured httpx client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = ManagementClientOptions( - api_key=api_key, headers=headers, base_url_override=base_url_override + api_key=api_key, + headers=headers, + base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else CredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.Client( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -97,7 +134,7 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.managementapi.ApiClient(self._http_client) + self._api = baseten.client.managementapi.ApiClient(self._http_client, auth=auth) @property def options(self) -> ManagementClientOptions: @@ -145,7 +182,8 @@ def default_base_url(cls) -> str: def __init__( self, *, - api_key: str, + api_key: str | None = None, + credentials: AsyncCredentials | None = None, headers: Mapping[str, str] | None = None, base_url_override: str | None = None, http_client_override: httpx.AsyncClient | None = None, @@ -154,31 +192,53 @@ def __init__( """Create a new asynchronous management client. Args: - api_key: API key for authentication. + api_key: API key for authentication. Exactly one of *api_key* and + *credentials* is required. + credentials: Supplies short-lived access tokens, as for + :class:`ManagementClient`. headers: Additional headers to send on every request. base_url_override: Override the default base URL. When ``None``, :meth:`default_base_url` is used. http_client_override: Pre-configured httpx async client. When provided, the caller is responsible for setting base URL and all headers. + *credentials* still apply, but only to requests made + through :attr:`api`, which sends a token to this client's + base URL (or, if it has none, the resolved base URL). + Requests sent on the HTTP client directly carry none. close_http_client_on_close: Whether :meth:`close` should close the underlying HTTP client. Defaults to ``True`` when the client is created internally, ``False`` when *http_client_override* is provided. """ + check_client_auth(api_key=api_key, credentials=credentials, headers=headers) self._options = ManagementClientOptions( - api_key=api_key, headers=headers, base_url_override=base_url_override + api_key=api_key, + headers=headers, + base_url_override=base_url_override, + credentials=credentials, + ) + auth = ( + None + if credentials is None + else AsyncCredentialsAuth( + credentials, + origin=credentials_origin( + http_client_override, lambda: self._options.base_url + ), + ) ) if http_client_override is None: request_headers: dict[str, str] = {**(headers or {})} # Empty api_key is an advanced opt-out from sending Authorization. - if api_key != "": + if api_key: request_headers["Authorization"] = f"Bearer {api_key}" # No read timeout, matching the JS and Go clients. self._http_client = httpx.AsyncClient( base_url=self._options.base_url, headers=with_user_agent(request_headers), timeout=httpx.Timeout(5.0, read=None), + auth=auth, ) self.close_http_client_on_close = ( True @@ -192,7 +252,9 @@ def __init__( if close_http_client_on_close is None else close_http_client_on_close ) - self._api = baseten.client.managementapi.AsyncApiClient(self._http_client) + self._api = baseten.client.managementapi.AsyncApiClient( + self._http_client, auth=auth + ) @property def options(self) -> ManagementClientOptions: diff --git a/baseten/client/_token_auth.py b/baseten/client/_token_auth.py new file mode 100644 index 0000000..450ebf7 --- /dev/null +++ b/baseten/client/_token_auth.py @@ -0,0 +1,442 @@ +"""What every short-lived Baseten token needs. + +A cache that mints a new token shortly before the current one expires, and an +:class:`httpx.Auth` that sends a token from :class:`Credentials`. +""" + +from __future__ import annotations + +import asyncio +import inspect +import threading +from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapping +from dataclasses import dataclass, field +from datetime import UTC, datetime, timedelta +from typing import Protocol + +import httpx + + +@dataclass(frozen=True, kw_only=True) +class AccessToken: + """A short-lived Baseten access token, sent as ``Authorization: Bearer``.""" + + token: str = field(repr=False) + """The bearer token, left out of the repr so logging it does not leak it.""" + + expires_at: datetime + """When the token expires.""" + + +@dataclass(frozen=True, kw_only=True) +class AccessTokenOptions: + """What :class:`Credentials` are told about the token they are asked for.""" + + refused_token: str | None = field(default=None, repr=False) + """A token Baseten refused before its stated expiry. + + Credentials that cache tokens must not return it again. + """ + + +class Credentials(Protocol): + """Supplies a current Baseten access token. + + A client given one as ``credentials`` calls it before every request, so + the credentials decide when to refresh. + """ + + def access_token(self, options: AccessTokenOptions) -> AccessToken: + """Return a current access token.""" + ... + + +class AsyncCredentials(Protocol): + """Async form of :class:`Credentials`.""" + + async def access_token(self, options: AccessTokenOptions) -> AccessToken: + """Return a current access token.""" + ... + + +def _utc_now() -> datetime: + return datetime.now(UTC) + + +@dataclass(frozen=True) +class _CachedToken: + token: AccessToken + refresh_at: datetime + + +def _cached( + token: AccessToken, *, minted_at: datetime, refresh_leeway: timedelta +) -> _CachedToken: + """Cache *token* until *refresh_leeway* before expiry, capped at half its lifetime. + + The cap keeps a token whose lifetime is shorter than the leeway from being + minted again on every call. + """ + lifetime = max(token.expires_at - minted_at, timedelta(0)) + return _CachedToken( + token=token, + refresh_at=token.expires_at - min(refresh_leeway, lifetime / 2), + ) + + +class _Mint: + """One call to a :class:`TokenCache`'s mint; its result is set before *done*.""" + + def __init__(self) -> None: + self.done = threading.Event() + self.result: _CachedToken | None = None + self.error: BaseException | None = None + + +class TokenCache: + """Holds one token and mints a new one when it is due for refresh. + + Safe for use from several threads. Concurrent callers share one mint, + which runs on the thread of the caller that started it. *mint* must bound + its own duration, since every waiting caller waits on it. + """ + + def __init__( + self, + *, + mint: Callable[[], AccessToken], + refresh_leeway: timedelta, + now: Callable[[], datetime] = _utc_now, + ) -> None: + """Create an empty cache; the first mint happens on first use.""" + self._mint = mint + self._refresh_leeway = refresh_leeway + self._now = now + self._lock = threading.Lock() + self._current: _Mint | None = None + # The token last dropped for being due for refresh. Still valid until + # it expires, so it stands in when the refresh fails. + self._previous: AccessToken | None = None + + def token(self) -> AccessToken: + """Return the cached token, minting one when none is cached or it is due.""" + joined_failure = False + while True: + with self._lock: + mint = self._current + started = mint is None + if mint is None: + mint = _Mint() + self._current = mint + if started: + self._run_mint(mint) + else: + mint.done.wait() + if mint.error is not None: + # Interrupted rather than failed, so the starter's own + # exception is not raised on another thread. + if not started and not isinstance(mint.error, Exception): + continue + # Another caller's failed mint gets one more try, which may + # be this caller's own or one shared with other such callers; + # the failed one already left the cache. + if not started and not joined_failure: + joined_failure = True + continue + fallback = self._fallback() + if fallback is not None: + return fallback + raise mint.error + assert mint.result is not None + # A token this caller just minted is used even if already due, so + # a skewed clock cannot loop here forever. + if started or self._now() < mint.result.refresh_at: + return mint.result.token + with self._lock: + if self._current is mint: + self._current = None + self._previous = mint.result.token + + def invalidate(self, token: str) -> None: + """Drop *token* if it is still the cached one.""" + with self._lock: + if self._previous is not None and self._previous.token == token: + self._previous = None + current = self._current + # Compared by value, so a refusal of an older token never discards + # a newer one another caller already minted. One still minting is + # newer than any token a caller could have sent. + if ( + current is not None + and current.result is not None + and current.result.token.token == token + ): + self._current = None + + def _fallback(self) -> AccessToken | None: + # A refresh that fails while the replaced token is still valid falls + # back to it, so a brief outage of the minting endpoint does not fail + # requests the old token can still serve. + with self._lock: + previous = self._previous + if previous is not None and self._now() < previous.expires_at: + return previous + return None + + def _run_mint(self, mint: _Mint) -> None: + """Run *mint*, keeping a ``KeyboardInterrupt`` or the like propagating.""" + try: + minted_at = self._now() + mint.result = _cached( + self._mint(), minted_at=minted_at, refresh_leeway=self._refresh_leeway + ) + with self._lock: + self._previous = None + except BaseException as e: + mint.error = e + # Not cached, so the next caller tries again. + with self._lock: + if self._current is mint: + self._current = None + if not isinstance(e, Exception): + raise + finally: + mint.done.set() + + +class AsyncTokenCache: + """Async form of :class:`TokenCache`. + + The shared mint runs as its own task, so one caller being cancelled does + not cancel the mint the others wait on. + """ + + def __init__( + self, + *, + mint: Callable[[], Awaitable[AccessToken]], + refresh_leeway: timedelta, + now: Callable[[], datetime] = _utc_now, + ) -> None: + """Create an empty cache; the first mint happens on first use.""" + self._mint = mint + self._refresh_leeway = refresh_leeway + self._now = now + self._current: asyncio.Task[_CachedToken] | None = None + # As in TokenCache. + self._previous: AccessToken | None = None + + async def token(self) -> AccessToken: + """Return the cached token, as :meth:`TokenCache.token` does.""" + joined_failure = False + while True: + task = self._current + started = task is None + if task is None: + task = asyncio.create_task(self._run_mint()) + # Retrieved here so a failure no caller is left to see is not + # reported as never retrieved. + task.add_done_callback(lambda t: t.cancelled() or t.exception()) + self._current = task + try: + minted = await asyncio.shield(task) + except Exception: + # As in TokenCache: at most one more try after joining + # another caller's failed mint. + if not started and not joined_failure: + joined_failure = True + continue + previous = self._previous + if previous is not None and self._now() < previous.expires_at: + return previous + raise + # A token this caller just minted is used even if already due, so + # a skewed clock cannot loop here forever. + if started or self._now() < minted.refresh_at: + return minted.token + if self._current is task: + self._current = None + self._previous = minted.token + + def invalidate(self, token: str) -> None: + """Drop *token* if it is still the cached one.""" + if self._previous is not None and self._previous.token == token: + self._previous = None + current = self._current + # Compared by value, so a refusal of an older token never discards a + # newer one another caller already minted. + if ( + current is not None + and current.done() + and not current.cancelled() + and current.exception() is None + and current.result().token.token == token + ): + self._current = None + + async def _run_mint(self) -> _CachedToken: + try: + minted_at = self._now() + minted = _cached( + await self._mint(), + minted_at=minted_at, + refresh_leeway=self._refresh_leeway, + ) + except BaseException: + # Not cached, so the next caller tries again. + if self._current is asyncio.current_task(): + self._current = None + raise + self._previous = None + return minted + + +class CredentialsAuth(httpx.Auth): + """Sends a token from :class:`Credentials` on each request to one origin. + + A token is fetched for every request, so a long-lived client picks up + refreshed tokens. Each request is sent once; a refusal is returned to the + caller as is, and when Baseten refused the token, the next request asks + the credentials for a new one. + """ + + def __init__(self, credentials: Credentials, *, origin: str) -> None: + """Create the auth. + + Args: + credentials: Supplies the token. + origin: Only requests to this URL's scheme, host and port that + carry no Authorization of their own are authenticated, so a + token never reaches another host through a shared HTTP client. + """ + if inspect.iscoroutinefunction(credentials.access_token): + raise TypeError( + "credentials.access_token is async; use the client's async form" + ) + self._credentials = credentials + self._origin = httpx.URL(origin) + # The last token Baseten refused, passed to the next access_token call + # so the credentials replace it. + self._refused: str | None = None + # Taken and cleared together, since requests on several threads share + # this auth. + self._refused_lock = threading.Lock() + + def sync_auth_flow( + self, request: httpx.Request + ) -> Generator[httpx.Request, httpx.Response, None]: + """Send the request with the current token.""" + if not _applies_to(request, self._origin): + yield request + return + with self._refused_lock: + refused, self._refused = self._refused, None + options = AccessTokenOptions(refused_token=refused) + token = _non_empty(self._credentials.access_token(options)) + _set_authorization(request, token) + response = yield request + # The request is not sent again, since it may have side effects; only + # the next request gets a new token. + if refused_by_baseten(response): + with self._refused_lock: + self._refused = token + + +class AsyncCredentialsAuth(httpx.Auth): + """Async form of :class:`CredentialsAuth`.""" + + def __init__(self, credentials: AsyncCredentials, *, origin: str) -> None: + """Create the auth, as :class:`CredentialsAuth` does.""" + if not inspect.iscoroutinefunction(credentials.access_token): + raise TypeError( + "credentials.access_token must be async; use the client's sync form" + ) + self._credentials = credentials + self._origin = httpx.URL(origin) + self._refused: str | None = None + + async def async_auth_flow( + self, request: httpx.Request + ) -> AsyncGenerator[httpx.Request, httpx.Response]: + """Send the request with the current token.""" + if not _applies_to(request, self._origin): + yield request + return + options = AccessTokenOptions(refused_token=self._refused) + self._refused = None + token = _non_empty(await self._credentials.access_token(options)) + _set_authorization(request, token) + response = yield request + if refused_by_baseten(response): + self._refused = token + + +def refused_by_baseten(response: httpx.Response) -> bool: + """Report whether Baseten's auth layer refused the request's access token. + + It signals that with this challenge. A model's own error response cannot + carry it, since its headers are not forwarded. + """ + if response.status_code != 401: + return False + return any( + challenge.startswith("Bearer ") + and 'realm="baseten"' in challenge + and 'error="invalid_token"' in challenge + for challenge in response.headers.get_list("WWW-Authenticate") + ) + + +def credentials_origin( + http_client_override: httpx.Client | httpx.AsyncClient | None, + base_url: Callable[[], str], +) -> str: + """Return the origin a client's credentials are sent to. + + The API client sends its requests to *http_client_override*'s base URL + when it has one, so that is where the token must go; *base_url* is + called only otherwise, since an inference client given an override may + have no model or chain to compute one from. + """ + if http_client_override is not None and http_client_override.base_url.host: + return str(http_client_override.base_url) + return base_url() + + +def _applies_to(request: httpx.Request, origin: httpx.URL) -> bool: + # Scheme too, so a token meant for https is never sent in the clear. + return ( + request.url.scheme == origin.scheme + and request.url.host == origin.host + and request.url.port == origin.port + and "Authorization" not in request.headers + ) + + +def _set_authorization(request: httpx.Request, token: str | None) -> None: + if token is not None: + request.headers["Authorization"] = f"Bearer {token}" + + +def _non_empty(token: AccessToken) -> str: + if token.token == "": + raise ValueError("the credentials returned an empty access token") + return token.token + + +def check_client_auth( + *, + api_key: str | None, + credentials: object | None, + headers: Mapping[str, str] | None, +) -> None: + """Check that a client is given exactly one way to authenticate.""" + # An empty api_key next to credentials counts as unset, as in Go. + if api_key and credentials is not None: + raise ValueError("api_key and credentials are mutually exclusive") + if api_key is None and credentials is None: + raise ValueError("one of api_key or credentials is required") + if credentials is not None and any( + key.lower() == "authorization" for key in headers or {} + ): + raise ValueError("headers must not set Authorization when credentials is set") diff --git a/baseten/client/_workload_identity.py b/baseten/client/_workload_identity.py new file mode 100644 index 0000000..e082b96 --- /dev/null +++ b/baseten/client/_workload_identity.py @@ -0,0 +1,341 @@ +from __future__ import annotations + +import asyncio +import json +import os +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any, TypeAlias + +import httpx + +from baseten.client._management import ManagementClient +from baseten.client._token_auth import ( + AccessToken, + AccessTokenOptions, + AsyncTokenCache, + TokenCache, + _utc_now, +) +from baseten.client._user_agent import with_user_agent +from baseten.client.managementapi import ( + ApiClient, + AsyncApiClient, + ResponseError, + TokenExchangeRequest, + TokenExchangeResponse, +) + +# Sends a request as is, so the exchange never picks up an HTTP client's own +# auth, such as another client's credentials. +_NO_AUTH = httpx.Auth() + +# The exchange takes an RFC 8693 request naming the trust rule as its audience. +_TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" +_JWT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:jwt" +# As in the Go SDK. httpx applies it to each phase of the request. +_EXCHANGE_TIMEOUT = httpx.Timeout(10) + + +@dataclass(frozen=True, kw_only=True) +class IdentityTokenProviderContext: + """Passed to an :data:`IdentityTokenProvider`. + + Empty for now; fields may be added in later versions. + """ + + +IdentityTokenProvider: TypeAlias = Callable[[IdentityTokenProviderContext], str] +"""Returns the identity provider's JWT. Called on every exchange.""" + +AsyncIdentityTokenProvider: TypeAlias = Callable[ + [IdentityTokenProviderContext], Awaitable[str] +] +"""Async form of :data:`IdentityTokenProvider`.""" + + +class _Exchange: + """The parts of an exchange shared by the sync and async credentials.""" + + def __init__( + self, + *, + trust_rule_id: str, + identity_token_file: str | os.PathLike[str] | None, + has_identity_token: bool, + base_url_override: str | None, + refresh_leeway: timedelta, + ) -> None: + if (identity_token_file is None) == (not has_identity_token): + raise ValueError( + "exactly one of identity_token_file and identity_token is required" + ) + if identity_token_file is not None and os.fspath(identity_token_file) == "": + raise ValueError("identity_token_file must not be empty") + if not trust_rule_id: + raise ValueError("trust_rule_id is required") + if refresh_leeway < timedelta(0): + raise ValueError("refresh_leeway must not be negative") + self.trust_rule_id = trust_rule_id + self.identity_token_file = ( + None if identity_token_file is None else Path(identity_token_file) + ) + base_url = (base_url_override or ManagementClient.default_base_url()).rstrip( + "/" + ) + self.base_url = base_url + self.headers = with_user_agent({}) + + def read_identity_token_file(self) -> str: + assert self.identity_token_file is not None + # Re-read on every exchange, since such files are rotated in place. + token = self.identity_token_file.read_text().strip() + if token == "": + raise ValueError(f"identity token file {self.identity_token_file} is empty") + return token + + def request(self, identity_token: str) -> TokenExchangeRequest: + token = identity_token.strip() + if token == "": + raise ValueError("the identity token provider returned an empty token") + return TokenExchangeRequest( + grant_type=_TOKEN_EXCHANGE_GRANT_TYPE, + subject_token=token, + subject_token_type=_JWT_TOKEN_TYPE, + audience=self.trust_rule_id, + ) + + def api_kwargs(self) -> dict[str, Any]: + # The identity token in the body is what authenticates. + return { + "base_url": self.base_url, + "headers": self.headers, + "timeout": _EXCHANGE_TIMEOUT, + "auth": _NO_AUTH, + } + + def add_context(self, error: Exception) -> None: + error.add_note( + f"while exchanging an identity token under trust rule {self.trust_rule_id}" + ) + if ( + isinstance(error, ResponseError) + and _oauth_error(error.body) == "invalid_grant" + ): + # The server sends every refusal as the same invalid_grant, so the + # note covers each possible cause. + error.add_note( + "workload identity token exchange refused for trust rule " + f"{self.trust_rule_id} (the trust rule may not exist or may " + "not match the identity token's issuer, audience, or claims, " + "or the identity token may have expired)" + ) + + def parse( + self, response: TokenExchangeResponse, *, issued_at: datetime + ) -> AccessToken: + if response.access_token == "": + raise ValueError( + "workload identity token exchange: the response carried no access_token" + ) + if response.token_type.lower() != "bearer": + raise ValueError( + "workload identity token exchange: unsupported token_type " + f"{response.token_type!r}" + ) + if response.expires_in <= 0: + raise ValueError( + f"workload identity token exchange: invalid expires_in {response.expires_in!r}" + ) + return AccessToken( + token=response.access_token, + expires_at=issued_at + timedelta(seconds=response.expires_in), + ) + + +def _oauth_error(body: str) -> object: + try: + decoded = json.loads(body) + except ValueError: + return None + return decoded.get("error") if isinstance(decoded, dict) else None + + +class WorkloadIdentityCredentials: + """Exchanges an identity provider's JWT for Baseten access tokens. + + OIDC workload identity federation: instead of an API key, a workload + exchanges its identity provider's token (for example a projected + Kubernetes service account token) for a short-lived Baseten access token + under a trust rule. Pass the credentials to a client as ``credentials``:: + + from baseten.client import ManagementClient, WorkloadIdentityCredentials + + credentials = WorkloadIdentityCredentials( + trust_rule_id="my-trust-rule-id", + identity_token_file="/var/run/secrets/tokens/baseten", + ) + with ManagementClient(credentials=credentials) as client: + print(client.api.get_organizations_me().org_id) + + The exchange happens on first use; the access token is cached in memory + and replaced shortly before it expires. Safe for use from several threads; + concurrent callers share one exchange. Everything is passed explicitly; no + environment variables are read. A refused exchange raises + :class:`baseten.client.managementapi.ResponseError`. Only the exchange's + HTTP request has a timeout, of 10 seconds; *identity_token* and reading + *identity_token_file* have none, so a caller that needs the whole call + bounded sets its own deadline. + """ + + def __init__( + self, + *, + trust_rule_id: str, + identity_token_file: str | os.PathLike[str] | None = None, + identity_token: IdentityTokenProvider | None = None, + base_url_override: str | None = None, + refresh_leeway: timedelta = timedelta(minutes=5), + http_client_override: httpx.Client | None = None, + ) -> None: + """Validate the options. Baseten is not contacted until first use. + + Args: + trust_rule_id: The Baseten trust rule the identity token is + exchanged under. + identity_token_file: A file holding the identity provider's JWT, + such as a projected Kubernetes service account token. Re-read + on every exchange, since such files are rotated in place. + Exactly one of *identity_token_file* and *identity_token* is + required. + identity_token: Returns the identity provider's JWT. Called on + every exchange with an :class:`IdentityTokenProviderContext`. + base_url_override: Management API base URL the exchange is sent + to. ``None`` uses :meth:`ManagementClient.default_base_url`. + Must point at the same Baseten environment as the clients + given these credentials, since a token is accepted only by + the environment that issued it. + refresh_leeway: How long before expiry the access token is + replaced, capped at half the token's lifetime so a short-lived + token is still reused. + http_client_override: HTTP client to send the exchange with. + ``None`` uses a new one per exchange. It should not follow + redirects, since the request body carries the identity token. + """ + self._exchange = _Exchange( + trust_rule_id=trust_rule_id, + identity_token_file=identity_token_file, + has_identity_token=identity_token is not None, + base_url_override=base_url_override, + refresh_leeway=refresh_leeway, + ) + self._identity_token = identity_token + self._http_client = http_client_override + # Replaced in tests. + self._now: Callable[[], datetime] = _utc_now + self._cache = TokenCache( + mint=self._exchange_token, + refresh_leeway=refresh_leeway, + now=lambda: self._now(), + ) + + def access_token(self, options: AccessTokenOptions) -> AccessToken: + """Return a current access token, exchanging for a new one when due.""" + if options.refused_token is not None: + self._cache.invalidate(options.refused_token) + return self._cache.token() + + def _exchange_token(self) -> AccessToken: + try: + if self._identity_token is not None: + identity_token = self._identity_token(IdentityTokenProviderContext()) + else: + identity_token = self._exchange.read_identity_token_file() + request = self._exchange.request(identity_token) + # Taken before sending, so the computed expiry errs early. + issued_at = self._now() + if self._http_client is not None: + response = ApiClient( + self._http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + else: + with httpx.Client() as http_client: + response = ApiClient( + http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + return self._exchange.parse(response, issued_at=issued_at) + except Exception as e: + self._exchange.add_context(e) + raise + + +class AsyncWorkloadIdentityCredentials: + """Async form of :class:`WorkloadIdentityCredentials`, for async clients. + + Concurrent tasks share one exchange, and one task being cancelled does not + cancel the exchange the others wait on. + """ + + def __init__( + self, + *, + trust_rule_id: str, + identity_token_file: str | os.PathLike[str] | None = None, + identity_token: AsyncIdentityTokenProvider | None = None, + base_url_override: str | None = None, + refresh_leeway: timedelta = timedelta(minutes=5), + http_client_override: httpx.AsyncClient | None = None, + ) -> None: + """Validate the options, as :class:`WorkloadIdentityCredentials` does.""" + self._exchange = _Exchange( + trust_rule_id=trust_rule_id, + identity_token_file=identity_token_file, + has_identity_token=identity_token is not None, + base_url_override=base_url_override, + refresh_leeway=refresh_leeway, + ) + self._identity_token = identity_token + self._http_client = http_client_override + # Replaced in tests. + self._now: Callable[[], datetime] = _utc_now + self._cache = AsyncTokenCache( + mint=self._exchange_token, + refresh_leeway=refresh_leeway, + now=lambda: self._now(), + ) + + async def access_token(self, options: AccessTokenOptions) -> AccessToken: + """Return a current access token, exchanging for a new one when due.""" + if options.refused_token is not None: + self._cache.invalidate(options.refused_token) + return await self._cache.token() + + async def _exchange_token(self) -> AccessToken: + try: + if self._identity_token is not None: + identity_token = await self._identity_token( + IdentityTokenProviderContext() + ) + else: + # Off the event loop, since the file system can be slow. + identity_token = await asyncio.to_thread( + self._exchange.read_identity_token_file + ) + request = self._exchange.request(identity_token) + # Taken before sending, so the computed expiry errs early. + issued_at = self._now() + if self._http_client is not None: + response = await AsyncApiClient( + self._http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + else: + async with httpx.AsyncClient() as http_client: + response = await AsyncApiClient( + http_client, **self._exchange.api_kwargs() + ).post_auth_token(request=request) + return self._exchange.parse(response, issued_at=issued_at) + except Exception as e: + self._exchange.add_context(e) + raise diff --git a/baseten/sandbox/_auth.py b/baseten/sandbox/_auth.py index 740bcdf..96d05fc 100644 --- a/baseten/sandbox/_auth.py +++ b/baseten/sandbox/_auth.py @@ -1,16 +1,21 @@ from __future__ import annotations import asyncio -import threading import time from collections.abc import AsyncGenerator, Awaitable, Callable, Generator from dataclasses import dataclass -from datetime import UTC, datetime, timedelta +from datetime import timedelta from typing import TypeAlias import httpx import baseten.client.managementapi +from baseten.client._token_auth import ( + AccessToken, + AsyncTokenCache, + TokenCache, + _set_authorization, +) @dataclass(kw_only=True) @@ -40,10 +45,11 @@ class SandboxTokenProviderContext: """Async form of :data:`SandboxTokenProvider`.""" # Refresh this long before the token's stated expiry, to allow for clock skew -# between this machine and the server, and for time spent in flight. +# between this machine and the server, and for time spent in flight. Capped at +# half the token's lifetime. _TOKEN_EXPIRY_LEEWAY = timedelta(seconds=60) -# A few resends cover a new token being invalidated in the same event as the +# A few retries cover a new token being invalidated in the same event as the # old one. Past that, the rejection is returned, since tokens that keep getting # rejected point at something a new token cannot fix. _TOKEN_INVALIDATION_MAX_RETRIES = 2 @@ -53,7 +59,7 @@ class SandboxTokenProviderContext: # after the event can fall before the cutoff and be rejected too, so after the # first resend, each one waits this long to be minted past it. A module # variable so tests can shorten it. -_token_revoked_retry_delay = 1.0 +_token_revoked_retry_delay_sec = 1.0 TOKEN_MINT_TIMEOUT = 30.0 """Seconds that one token exchange may take. @@ -62,77 +68,57 @@ class SandboxTokenProviderContext: from holding up every later caller. """ - -@dataclass(frozen=True) -class _MintedToken: - """A token minted from an API key, with its expiry.""" - - token: str - expires_at: datetime - - def fresh(self) -> bool: - """Report whether the token is far enough from expiry to use.""" - return datetime.now(UTC) < self.expires_at - _TOKEN_EXPIRY_LEEWAY +_SANDBOX_TOKEN_REQUEST = baseten.client.managementapi.CreateTokenRequest( + scopes=["sandboxes"] +) class TokenSource: """Where each request's bearer token comes from. - Either a caller's token provider, or a token minted from an API key and - cached until shortly before it expires. The API key is exchanged for a - token because the sandbox APIs do not accept API keys directly. Should that - change, only this class changes. + Either a caller's token provider, or a token minted through *mint_api* and + cached until shortly before it expires. *mint_api* authenticates with an + API key or credentials, which are exchanged for a token because the + sandbox APIs do not accept them directly. Should that change, only this + class changes. """ def __init__( self, *, - api_key: str, token_provider: SandboxTokenProvider | None, - mint_api: baseten.client.managementapi.ApiClient, + mint_api: baseten.client.managementapi.ApiClient | None, ) -> None: - """Create a token source. ``mint_api`` authenticates with the API key.""" - if token_provider is not None and api_key != "": - raise ValueError("api_key must be empty when token_provider is set") + """Create a token source. + + With neither *token_provider* nor *mint_api*, no Authorization is + sent, which is the advanced opt-out of an empty API key. + """ self._provider = token_provider - self._mint_api = mint_api if api_key != "" else None - self._lock = threading.Lock() - self._cached: _MintedToken | None = None + self._cache = ( + None + if token_provider is not None or mint_api is None + else _token_cache(mint_api) + ) def token(self, revoked_token: str | None = None) -> str | None: - """Return the token for a request. + """Return the token for a request, or ``None`` to send no Authorization. - ``None`` means no Authorization is sent, which is the advanced opt-out - of an empty API key with no token provider. + ``revoked_token`` is the token the previous attempt was refused with, + if any. """ if self._provider is not None: return self._provider( SandboxTokenProviderContext(revoked_token=revoked_token) ) - if self._mint_api is None: + if self._cache is None: return None - # Held across the mint, so a burst on a cold cache sends one exchange. - with self._lock: - cached = self._cached - if cached is not None and cached.fresh(): - return cached.token - minted = self._mint_api.post_token( - request=baseten.client.managementapi.CreateTokenRequest( - scopes=["sandboxes"] - ) - ) - self._cached = _MintedToken( - token=minted.token, expires_at=minted.expires_at - ) - return minted.token + return self._cache.token().token def invalidate(self, token: str) -> None: """Drop a token the server rejected, so the next request gets a new one.""" - with self._lock: - # Compared by value, so a rejection of an older token never - # discards a newer one another request already minted. - if self._cached is not None and self._cached.token == token: - self._cached = None + if self._cache is not None: + self._cache.invalidate(token) class AsyncTokenSource: @@ -141,17 +127,16 @@ class AsyncTokenSource: def __init__( self, *, - api_key: str, token_provider: AsyncSandboxTokenProvider | None, - mint_api: baseten.client.managementapi.AsyncApiClient, + mint_api: baseten.client.managementapi.AsyncApiClient | None, ) -> None: - """Create a token source. ``mint_api`` authenticates with the API key.""" - if token_provider is not None and api_key != "": - raise ValueError("api_key must be empty when token_provider is set") + """Create a token source, as :class:`TokenSource` does.""" self._provider = token_provider - self._mint_api = mint_api if api_key != "" else None - self._cached: _MintedToken | None = None - self._minting: asyncio.Task[_MintedToken] | None = None + self._cache = ( + None + if token_provider is not None or mint_api is None + else _async_token_cache(mint_api) + ) async def token(self, revoked_token: str | None = None) -> str | None: """Return the token for a request, as :meth:`TokenSource.token` does.""" @@ -159,51 +144,23 @@ async def token(self, revoked_token: str | None = None) -> str | None: return await self._provider( SandboxTokenProviderContext(revoked_token=revoked_token) ) - if self._mint_api is None: + if self._cache is None: return None - cached = self._cached - if cached is not None and cached.fresh(): - return cached.token - # Every caller shares one mint, so a burst on a cold cache sends one - # exchange. Shielded, since one caller being cancelled must not cancel - # the mint the others are waiting on. - if self._minting is None: - self._minting = asyncio.create_task(self._mint(self._mint_api)) - # Retrieved here so a failure no caller is left to see is not - # reported as never retrieved. - self._minting.add_done_callback( - lambda task: task.cancelled() or task.exception() - ) - minted = await asyncio.shield(self._minting) - return minted.token + return (await self._cache.token()).token - async def invalidate(self, token: str) -> None: + def invalidate(self, token: str) -> None: """Drop a token the server rejected, so the next request gets a new one.""" - # Compared by value, so a rejection of an older token never discards a - # newer one another request already minted. - if self._cached is not None and self._cached.token == token: - self._cached = None - - async def _mint( - self, mint_api: baseten.client.managementapi.AsyncApiClient - ) -> _MintedToken: - """Exchange the API key for a token and cache it.""" - try: - minted = await mint_api.post_token( - request=baseten.client.managementapi.CreateTokenRequest( - scopes=["sandboxes"] - ) - ) - self._cached = _MintedToken( - token=minted.token, expires_at=minted.expires_at - ) - return self._cached - finally: - self._minting = None + if self._cache is not None: + self._cache.invalidate(token) class TokenAuth(httpx.Auth): - """Authenticates every request with a token from a :class:`TokenSource`.""" + """Authenticates every request with a token from a :class:`TokenSource`. + + When the server rejects the token as revoked (see :func:`is_token_revoked`), + the request is sent again with a new one when its body can be, at most + twice. + """ def __init__(self, tokens: TokenSource) -> None: """Create the auth.""" @@ -214,23 +171,25 @@ def sync_auth_flow( ) -> Generator[httpx.Request, httpx.Response, None]: """Send the request, again with a new token if its token was revoked.""" replayable = _is_replayable(request) - revoked_token: str | None = None + revoked: str | None = None for retry in range(_TOKEN_INVALIDATION_MAX_RETRIES + 1): - token = self.tokens.token(revoked_token) + token = self.tokens.token(revoked) _set_authorization(request, token) response = yield request - if token is None or not replayable or not _is_token_revoked(response): - return - if retry == _TOKEN_INVALIDATION_MAX_RETRIES: + if token is None or not is_token_revoked(response): return + # Dropped even when the request is not sent again, so later + # requests do not reuse it. self.tokens.invalidate(token) - revoked_token = token + if not replayable or retry == _TOKEN_INVALIDATION_MAX_RETRIES: + return + revoked = token if retry > 0: - time.sleep(_token_revoked_retry_delay) + time.sleep(_token_revoked_retry_delay_sec) class AsyncTokenAuth(httpx.Auth): - """Authenticates every request with a token from an :class:`AsyncTokenSource`.""" + """Async form of :class:`TokenAuth`.""" def __init__(self, tokens: AsyncTokenSource) -> None: """Create the auth.""" @@ -241,19 +200,34 @@ async def async_auth_flow( ) -> AsyncGenerator[httpx.Request, httpx.Response]: """Send the request, again with a new token if its token was revoked.""" replayable = _is_replayable(request) - revoked_token: str | None = None + revoked: str | None = None for retry in range(_TOKEN_INVALIDATION_MAX_RETRIES + 1): - token = await self.tokens.token(revoked_token) + token = await self.tokens.token(revoked) _set_authorization(request, token) response = yield request - if token is None or not replayable or not _is_token_revoked(response): + if token is None or not is_token_revoked(response): return - if retry == _TOKEN_INVALIDATION_MAX_RETRIES: + self.tokens.invalidate(token) + if not replayable or retry == _TOKEN_INVALIDATION_MAX_RETRIES: return - await self.tokens.invalidate(token) - revoked_token = token + revoked = token if retry > 0: - await asyncio.sleep(_token_revoked_retry_delay) + await asyncio.sleep(_token_revoked_retry_delay_sec) + + +def is_token_revoked(response: httpx.Response) -> bool: + """Report whether the server rejected a request's token as revoked. + + It can do so before the token's stated expiry, for example after a role + change. The request was rejected before any work was done, so sending it + again with a new token is safe even when it has side effects. + """ + # Both the control plane and sandboxes send this header, while their + # bodies differ. + return ( + response.status_code == 401 + and response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED" + ) def _is_replayable(request: httpx.Request) -> bool: @@ -263,21 +237,21 @@ def _is_replayable(request: httpx.Request) -> bool: return isinstance(request.stream, httpx.ByteStream) -def _set_authorization(request: httpx.Request, token: str | None) -> None: - """Set the request's bearer token, or leave Authorization unset for ``None``.""" - if token is not None: - request.headers["Authorization"] = f"Bearer {token}" +def _token_cache(mint_api: baseten.client.managementapi.ApiClient) -> TokenCache: + return TokenCache( + mint=lambda: _access_token(mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST)), + refresh_leeway=_TOKEN_EXPIRY_LEEWAY, + ) -def _is_token_revoked(response: httpx.Response) -> bool: - """Report whether the server rejected a request's token as revoked. +def _async_token_cache( + mint_api: baseten.client.managementapi.AsyncApiClient, +) -> AsyncTokenCache: + async def mint() -> AccessToken: + return _access_token(await mint_api.post_token(request=_SANDBOX_TOKEN_REQUEST)) - The request was rejected before any work was done, so sending it again - with a new token is safe even when it has side effects. - """ - # Both the control plane and sandboxes send this header, while their - # bodies differ. - return ( - response.status_code == 401 - and response.headers.get("x-blaxel-error-code") == "TOKEN_REVOKED" - ) + return AsyncTokenCache(mint=mint, refresh_leeway=_TOKEN_EXPIRY_LEEWAY) + + +def _access_token(minted: baseten.client.managementapi.Token) -> AccessToken: + return AccessToken(token=minted.token, expires_at=minted.expires_at) diff --git a/baseten/sandbox/_client.py b/baseten/sandbox/_client.py index f8bdbc4..607b629 100644 --- a/baseten/sandbox/_client.py +++ b/baseten/sandbox/_client.py @@ -17,6 +17,13 @@ import baseten.client import baseten.client.managementapi import baseten.client.sandboxapi +from baseten.client._token_auth import ( + AsyncCredentials, + AsyncCredentialsAuth, + Credentials, + CredentialsAuth, + check_client_auth, +) from baseten.client._user_agent import with_user_agent from baseten.sandbox._auth import ( TOKEN_MINT_TIMEOUT, @@ -83,8 +90,8 @@ class SandboxClientOptions: was constructed with. """ - api_key: str - """API key for authentication.""" + api_key: str | None = None + """API key for authentication, or ``None`` when another way is set.""" team_id: str | None = None """Team to act in, or ``None`` for the caller's only team.""" @@ -92,6 +99,9 @@ class SandboxClientOptions: token_provider: SandboxTokenProvider | AsyncSandboxTokenProvider | None = None """Provider of each request's bearer token, in place of the API key.""" + credentials: Credentials | AsyncCredentials | None = None + """Supplies short-lived access tokens, used in place of *api_key*.""" + base_url_override: str | None = None """Explicit base URL override, or ``None`` to use the default.""" @@ -153,9 +163,10 @@ class SandboxClient: def __init__( self, *, - api_key: str, + api_key: str | None = None, team_id: str | None = None, token_provider: SandboxTokenProvider | None = None, + credentials: Credentials | None = None, base_url_override: str | None = None, headers: Mapping[str, str] | None = None, retry: SandboxRetryOptions | None = None, @@ -167,13 +178,17 @@ def __init__( """Create a new sandbox client. Args: - api_key: API key for authentication. Empty, together with - *token_provider*, is the advanced opt-out of API key - authentication. + api_key: API key for authentication. Exactly one of *api_key*, + *credentials*, and *token_provider* is required. Empty, on its + own, is the advanced opt-out of sending Authorization. team_id: Team to act in. ``None`` uses the caller's only team, and is an error for callers in more than one team. token_provider: Returns the bearer token for each request, instead - of one derived from the API key, which must then be empty. + of one derived from an API key or credentials. + credentials: Supplies short-lived access tokens in place of an + API key, such as + :class:`~baseten.client.WorkloadIdentityCredentials`. Sandbox + tokens are requested with them. base_url_override: Override the management API's base URL, which defaults to ``https://api.baseten.co``. headers: Additional headers to send on every request. @@ -203,10 +218,17 @@ def __init__( threads end once the sandbox is no longer referenced. """ self._executor = executor + _check_auth( + api_key=api_key, + credentials=credentials, + token_provider=token_provider, + headers=headers, + ) self._options = SandboxClientOptions( api_key=api_key, team_id=team_id, token_provider=token_provider, + credentials=credentials, base_url_override=base_url_override, headers=headers, retry=retry, @@ -229,16 +251,22 @@ def __init__( else close_http_client_on_close ) self._request_headers = with_user_agent(headers or {}) - mint_api = baseten.client.managementapi.ApiClient( - self._http_client, - base_url=self._options.base_url, - headers={**self._request_headers, "Authorization": f"Bearer {api_key}"}, - timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), - ) - self._auth = TokenAuth( - TokenSource( - api_key=api_key, token_provider=token_provider, mint_api=mint_api + mint_api = None + if api_key or credentials is not None: + mint_headers = dict(self._request_headers) + if api_key: + mint_headers["Authorization"] = f"Bearer {api_key}" + mint_api = baseten.client.managementapi.ApiClient( + self._http_client, + base_url=self._options.base_url, + auth=None + if credentials is None + else CredentialsAuth(credentials, origin=self._options.base_url), + headers=mint_headers, + timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), ) + self._auth = TokenAuth( + TokenSource(token_provider=token_provider, mint_api=mint_api) ) self._raw_api = baseten.client.managementapi.ApiClient( self._http_client, @@ -562,9 +590,10 @@ class AsyncSandboxClient: def __init__( self, *, - api_key: str, + api_key: str | None = None, team_id: str | None = None, token_provider: AsyncSandboxTokenProvider | None = None, + credentials: AsyncCredentials | None = None, base_url_override: str | None = None, headers: Mapping[str, str] | None = None, retry: SandboxRetryOptions | None = None, @@ -575,13 +604,17 @@ def __init__( """Create a new async sandbox client. Args: - api_key: API key for authentication. Empty, together with - *token_provider*, is the advanced opt-out of API key - authentication. + api_key: API key for authentication. Exactly one of *api_key*, + *credentials*, and *token_provider* is required. Empty, on its + own, is the advanced opt-out of sending Authorization. team_id: Team to act in. ``None`` uses the caller's only team, and is an error for callers in more than one team. token_provider: Returns the bearer token for each request, instead - of one derived from the API key, which must then be empty. + of one derived from an API key or credentials. + credentials: Supplies short-lived access tokens in place of an + API key, such as + :class:`~baseten.client.AsyncWorkloadIdentityCredentials`. Sandbox + tokens are requested with them. base_url_override: Override the management API's base URL, which defaults to ``https://api.baseten.co``. headers: Additional headers to send on every request. @@ -603,10 +636,17 @@ def __init__( client is created internally, ``False`` when *http_client_override* is provided. """ + _check_auth( + api_key=api_key, + credentials=credentials, + token_provider=token_provider, + headers=headers, + ) self._options = SandboxClientOptions( api_key=api_key, team_id=team_id, token_provider=token_provider, + credentials=credentials, base_url_override=base_url_override, headers=headers, retry=retry, @@ -629,16 +669,22 @@ def __init__( else close_http_client_on_close ) self._request_headers = with_user_agent(headers or {}) - mint_api = baseten.client.managementapi.AsyncApiClient( - self._http_client, - base_url=self._options.base_url, - headers={**self._request_headers, "Authorization": f"Bearer {api_key}"}, - timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), - ) - self._auth = AsyncTokenAuth( - AsyncTokenSource( - api_key=api_key, token_provider=token_provider, mint_api=mint_api + mint_api = None + if api_key or credentials is not None: + mint_headers = dict(self._request_headers) + if api_key: + mint_headers["Authorization"] = f"Bearer {api_key}" + mint_api = baseten.client.managementapi.AsyncApiClient( + self._http_client, + base_url=self._options.base_url, + auth=None + if credentials is None + else AsyncCredentialsAuth(credentials, origin=self._options.base_url), + headers=mint_headers, + timeout=httpx.Timeout(TOKEN_MINT_TIMEOUT), ) + self._auth = AsyncTokenAuth( + AsyncTokenSource(token_provider=token_provider, mint_api=mint_api) ) self._raw_api = baseten.client.managementapi.AsyncApiClient( self._http_client, @@ -888,3 +934,21 @@ def _use_http2(http2: bool | None) -> bool: 'http2=True requires the h2 package, installed with "httpx[http2]"' ) return available + + +def _check_auth( + *, + api_key: str | None, + credentials: object | None, + token_provider: object | None, + headers: Mapping[str, str] | None, +) -> None: + """Check that a client is given exactly one way to authenticate.""" + if sum((bool(api_key), credentials is not None, token_provider is not None)) > 1: + raise ValueError( + "only one of api_key, credentials, and token_provider may be set" + ) + if api_key is None and credentials is None and token_provider is None: + raise ValueError("one of api_key, credentials, or token_provider is required") + if credentials is not None: + check_client_auth(api_key=None, credentials=credentials, headers=headers) diff --git a/tests/client/test_token_auth.py b/tests/client/test_token_auth.py new file mode 100644 index 0000000..330f29b --- /dev/null +++ b/tests/client/test_token_auth.py @@ -0,0 +1,320 @@ +from __future__ import annotations + +import asyncio +import threading +import time +from datetime import UTC, datetime, timedelta + +import httpx +import pytest + +from baseten.client import AccessToken +from baseten.client._token_auth import ( + AsyncTokenCache, + TokenCache, + _applies_to, + _cached, +) + +# How long each mint in the concurrency tests takes, long enough for every +# caller to be waiting on the first one. +_SLOW_MINT_SEC = 0.2 + + +class _Clock: + def __init__(self) -> None: + self.now = datetime(2026, 1, 1, tzinfo=UTC) + + def __call__(self) -> datetime: + return self.now + + +class _Mints: + """Issues ``token-`` valid for *lifetime* from the clock's time.""" + + def __init__(self, clock: _Clock, lifetime: timedelta) -> None: + self.clock = clock + self.lifetime = lifetime + self.count = 0 + self.failures = 0 + + def mint(self) -> AccessToken: + self.count += 1 + if self.failures > 0: + self.failures -= 1 + raise RuntimeError("mint failed") + return AccessToken( + token=f"token-{self.count}", expires_at=self.clock() + self.lifetime + ) + + async def mint_async(self) -> AccessToken: + return self.mint() + + +def _cache( + lifetime: timedelta, refresh_leeway: timedelta +) -> tuple[TokenCache, _Clock, _Mints]: + clock = _Clock() + mints = _Mints(clock, lifetime) + cache = TokenCache(mint=mints.mint, refresh_leeway=refresh_leeway, now=clock) + return cache, clock, mints + + +class TestTokenCache: + def test_refreshes_before_expiry(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + assert cache.token().token == "token-1" + clock.now += timedelta(minutes=54, seconds=59) + assert cache.token().token == "token-1" + clock.now += timedelta(seconds=1) + assert cache.token().token == "token-2" + assert mints.count == 2 + + def test_refresh_capped_at_half_lifetime(self) -> None: + # Without the cap, a five-minute margin on a one-minute token would + # mint on every call. + cache, clock, mints = _cache(timedelta(minutes=1), timedelta(minutes=5)) + cache.token() + clock.now += timedelta(seconds=29) + cache.token() + assert mints.count == 1 + clock.now += timedelta(seconds=1) + cache.token() + assert mints.count == 2 + + def test_returns_just_minted_token_even_if_due(self) -> None: + cache, _, mints = _cache(timedelta(0), timedelta(minutes=1)) + assert cache.token().token == "token-1" + assert cache.token().token == "token-2" + assert mints.count == 2 + + def test_invalidate_keeps_newer_token(self) -> None: + cache, _, _ = _cache(timedelta(hours=1), timedelta(minutes=1)) + cache.token() + cache.invalidate("token-0") + assert cache.token().token == "token-1" + cache.invalidate("token-1") + assert cache.token().token == "token-2" + + def test_failed_mint_is_not_cached(self) -> None: + cache, _, mints = _cache(timedelta(hours=1), timedelta(minutes=1)) + mints.failures = 1 + with pytest.raises(RuntimeError): + cache.token() + assert cache.token().token == "token-2" + + def test_waiter_on_failed_mint_tries_its_own(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + mints.failures = 1 + release = threading.Event() + first_minting = threading.Event() + + def mint() -> AccessToken: + first_minting.set() + release.wait() + return mints.mint() + + cache = TokenCache(mint=mint, refresh_leeway=timedelta(minutes=1), now=clock) + errors: list[BaseException] = [] + results: list[str] = [] + + def first() -> None: + try: + cache.token() + except RuntimeError as e: + errors.append(e) + + first_thread = threading.Thread(target=first) + first_thread.start() + first_minting.wait() + waiter = threading.Thread(target=lambda: results.append(cache.token().token)) + waiter.start() + release.set() + first_thread.join() + waiter.join() + assert len(errors) == 1 + assert results == ["token-2"] + + def test_concurrent_callers_on_failing_mint_share_one_retry(self) -> None: + calls = 0 + + def mint() -> AccessToken: + nonlocal calls + calls += 1 + time.sleep(_SLOW_MINT_SEC) + raise RuntimeError("mint failed") + + cache = TokenCache(mint=mint, refresh_leeway=timedelta(minutes=1)) + errors: list[BaseException] = [] + + def call() -> None: + try: + cache.token() + except RuntimeError as e: + errors.append(e) + + threads = [threading.Thread(target=call) for _ in range(8)] + started = time.monotonic() + for thread in threads: + thread.start() + for thread in threads: + thread.join() + elapsed = time.monotonic() - started + assert len(errors) == 8 + # One failed mint, then one retry shared by everyone who joined it, + # rather than one mint per caller in turn. + assert calls == 2 + assert elapsed < 3 * _SLOW_MINT_SEC + + def test_failed_refresh_falls_back_to_previous_token(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + assert cache.token().token == "token-1" + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-1" + assert cache.token().token == "token-3" + # The successful mint dropped the fallback. + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-3" + + def test_no_fallback_once_previous_expired(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + cache.token() + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-1" + clock.now += timedelta(minutes=4) + mints.failures = 1 + with pytest.raises(RuntimeError): + cache.token() + + def test_invalidate_clears_previous_token(self) -> None: + cache, clock, mints = _cache(timedelta(hours=1), timedelta(minutes=5)) + cache.token() + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert cache.token().token == "token-1" + cache.invalidate("token-1") + mints.failures = 1 + with pytest.raises(RuntimeError): + cache.token() + + +class TestAsyncTokenCache: + @pytest.mark.asyncio + async def test_refreshes_and_caps(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(minutes=1)) + cache = AsyncTokenCache( + mint=mints.mint_async, refresh_leeway=timedelta(minutes=5), now=clock + ) + assert (await cache.token()).token == "token-1" + clock.now += timedelta(seconds=29) + assert (await cache.token()).token == "token-1" + clock.now += timedelta(seconds=1) + assert (await cache.token()).token == "token-2" + + @pytest.mark.asyncio + async def test_shares_one_mint_and_waiter_retries_after_failure(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + release = asyncio.Event() + + async def mint() -> AccessToken: + await release.wait() + return mints.mint() + + cache = AsyncTokenCache( + mint=mint, refresh_leeway=timedelta(minutes=1), now=clock + ) + mints.failures = 1 + first = asyncio.create_task(cache.token()) + waiters = [asyncio.create_task(cache.token()) for _ in range(3)] + await asyncio.sleep(0) + release.set() + with pytest.raises(RuntimeError): + await first + assert [(await w).token for w in waiters] == ["token-2"] * 3 + assert mints.count == 2 + + @pytest.mark.asyncio + async def test_invalidate_keeps_newer_token(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + cache = AsyncTokenCache( + mint=mints.mint_async, refresh_leeway=timedelta(minutes=1), now=clock + ) + await cache.token() + cache.invalidate("token-0") + assert (await cache.token()).token == "token-1" + cache.invalidate("token-1") + assert (await cache.token()).token == "token-2" + + @pytest.mark.asyncio + async def test_concurrent_callers_on_failing_mint_share_one_retry(self) -> None: + calls = 0 + + async def mint() -> AccessToken: + nonlocal calls + calls += 1 + await asyncio.sleep(_SLOW_MINT_SEC) + raise RuntimeError("mint failed") + + cache = AsyncTokenCache(mint=mint, refresh_leeway=timedelta(minutes=1)) + started = time.monotonic() + results = await asyncio.gather( + *(cache.token() for _ in range(8)), return_exceptions=True + ) + elapsed = time.monotonic() - started + assert all(isinstance(result, RuntimeError) for result in results) + assert calls == 2 + assert elapsed < 3 * _SLOW_MINT_SEC + + @pytest.mark.asyncio + async def test_failed_refresh_falls_back_to_previous_token(self) -> None: + clock = _Clock() + mints = _Mints(clock, timedelta(hours=1)) + cache = AsyncTokenCache( + mint=mints.mint_async, refresh_leeway=timedelta(minutes=5), now=clock + ) + await cache.token() + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert (await cache.token()).token == "token-1" + cache.invalidate("token-1") + mints.failures = 1 + with pytest.raises(RuntimeError): + await cache.token() + assert (await cache.token()).token == "token-4" + clock.now += timedelta(minutes=56) + mints.failures = 1 + assert (await cache.token()).token == "token-4" + clock.now += timedelta(minutes=4) + mints.failures = 1 + with pytest.raises(RuntimeError): + await cache.token() + + +@pytest.mark.parametrize( + ("url", "applies"), + [ + ("https://api.test/x", True), + ("http://api.test/x", False), + ("https://api.test:8443/x", False), + ("https://other.test/x", False), + ], +) +def test_applies_only_to_origin(url: str, applies: bool) -> None: + origin = httpx.URL("https://api.test") + assert _applies_to(httpx.Request("GET", url), origin) is applies + + +def test_access_token_repr_hides_token() -> None: + token = AccessToken( + token="secret-bearer", expires_at=datetime(2026, 1, 1, tzinfo=UTC) + ) + assert "secret-bearer" not in repr(token) + cached = _cached(token, minted_at=token.expires_at, refresh_leeway=timedelta(0)) + assert "secret-bearer" not in repr(cached) diff --git a/tests/client/test_workload_identity.py b/tests/client/test_workload_identity.py new file mode 100644 index 0000000..aaf9cd8 --- /dev/null +++ b/tests/client/test_workload_identity.py @@ -0,0 +1,621 @@ +from __future__ import annotations + +import asyncio +import json +import socket +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import httpx +import pytest + +from baseten.client import ( + AccessToken, + AccessTokenOptions, + AsyncInferenceClient, + AsyncManagementClient, + AsyncWorkloadIdentityCredentials, + IdentityTokenProviderContext, + InferenceClient, + ManagementClient, + WorkloadIdentityCredentials, + _workload_identity, +) +from baseten.client.managementapi import ResponseError + +_ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" +_BASE_URL = "https://api.test" +_ORG = { + "org_id": "o", + "created_at": "2026-01-01T00:00:00Z", + "allow_personal_api_keys": True, + "allow_service_account_api_keys": True, +} +_OPTIONS = AccessTokenOptions() +_CONTEXT = "while exchanging an identity token under trust rule rule-1" + + +class _Server: + """Stands in for ``POST /v1/auth/token``, issuing ``access-``. + + Other requests record their Authorization and get *respond*'s response. + """ + + def __init__(self, *, expires_in: int = 3600) -> None: + self.expires_in = expires_in + self.assertions: list[str] = [] + self.exchange_response: Callable[[], httpx.Response] | None = None + self.respond: Callable[[httpx.Request], httpx.Response] = lambda request: ( + httpx.Response(200, json=_ORG) + ) + self.authorizations: list[str | None] = [] + + def handle(self, request: httpx.Request) -> httpx.Response: + if request.url.path != "/v1/auth/token": + self.authorizations.append(request.headers.get("Authorization")) + return self.respond(request) + assert request.method == "POST" + assert request.headers["Content-Type"] == "application/json" + assert "Authorization" not in request.headers + body = json.loads(request.content) + assert body.keys() == { + "grant_type", + "subject_token", + "subject_token_type", + "audience", + } + assert body["grant_type"] == "urn:ietf:params:oauth:grant-type:token-exchange" + assert body["subject_token_type"] == "urn:ietf:params:oauth:token-type:jwt" + assert body["audience"] == "rule-1" + self.assertions.append(body["subject_token"]) + if self.exchange_response is not None: + return self.exchange_response() + return httpx.Response( + 200, + json={ + "access_token": f"access-{len(self.assertions)}", + "token_type": "Bearer", + "expires_in": self.expires_in, + "issued_token_type": _ACCESS_TOKEN_TYPE, + }, + ) + + async def handle_async(self, request: httpx.Request) -> httpx.Response: + return self.handle(request) + + def credentials(self, **kwargs) -> WorkloadIdentityCredentials: + kwargs.setdefault("trust_rule_id", "rule-1") + if "identity_token_file" not in kwargs: + kwargs.setdefault("identity_token", lambda _: "idp-jwt") + return WorkloadIdentityCredentials( + base_url_override=_BASE_URL, + http_client_override=httpx.Client( + transport=httpx.MockTransport(self.handle) + ), + **kwargs, + ) + + def async_credentials(self, **kwargs) -> AsyncWorkloadIdentityCredentials: + kwargs.setdefault("trust_rule_id", "rule-1") + + async def identity_token(_: IdentityTokenProviderContext) -> str: + return "idp-jwt" + + if "identity_token_file" not in kwargs: + kwargs.setdefault("identity_token", identity_token) + return AsyncWorkloadIdentityCredentials( + base_url_override=_BASE_URL, + http_client_override=httpx.AsyncClient( + transport=httpx.MockTransport(self.handle_async) + ), + **kwargs, + ) + + +class _Clock: + def __init__(self) -> None: + self.now = datetime.now(UTC) + + def __call__(self) -> datetime: + return self.now + + +def _with_clock(credentials): + clock = _Clock() + credentials._now = clock + return clock + + +def _error_response(status: int, body: str) -> Callable[[], httpx.Response]: + return lambda: httpx.Response(status, text=body) + + +class TestWorkloadIdentityCredentials: + def test_exchanges_and_caches(self) -> None: + server = _Server() + credentials = server.credentials() + before = datetime.now(UTC) + token = credentials.access_token(_OPTIONS) + assert token.token == "access-1" + assert token.expires_at >= before + timedelta(hours=1) + assert credentials.access_token(_OPTIONS).token == "access-1" + assert server.assertions == ["idp-jwt"] + + def test_refreshes_within_leeway(self) -> None: + server = _Server(expires_in=600) + credentials = server.credentials(refresh_leeway=timedelta(minutes=1)) + clock = _with_clock(credentials) + credentials.access_token(_OPTIONS) + clock.now += timedelta(minutes=8, seconds=59) + assert credentials.access_token(_OPTIONS).token == "access-1" + clock.now += timedelta(seconds=1) + assert credentials.access_token(_OPTIONS).token == "access-2" + + def test_leeway_capped_at_half_lifetime(self) -> None: + # The default five-minute leeway exceeds the lifetime; without the cap + # every call would exchange. + server = _Server(expires_in=60) + credentials = server.credentials() + clock = _with_clock(credentials) + credentials.access_token(_OPTIONS) + clock.now += timedelta(seconds=29) + credentials.access_token(_OPTIONS) + assert len(server.assertions) == 1 + clock.now += timedelta(seconds=1) + credentials.access_token(_OPTIONS) + assert len(server.assertions) == 2 + + def test_rereads_token_file_on_every_exchange(self, tmp_path: Path) -> None: + server = _Server(expires_in=600) + path = tmp_path / "token" + path.write_text("jwt-one\n") + credentials = server.credentials(identity_token_file=path) + clock = _with_clock(credentials) + credentials.access_token(_OPTIONS) + path.write_text("jwt-two") + clock.now += timedelta(minutes=10) + credentials.access_token(_OPTIONS) + assert server.assertions == ["jwt-one", "jwt-two"] + + def test_missing_token_file(self, tmp_path: Path) -> None: + server = _Server() + credentials = server.credentials(identity_token_file=tmp_path / "missing") + with pytest.raises(FileNotFoundError): + credentials.access_token(_OPTIONS) + assert server.assertions == [] + + def test_empty_token_file(self, tmp_path: Path) -> None: + path = tmp_path / "token" + path.write_text("\n") + credentials = _Server().credentials(identity_token_file=path) + with pytest.raises(ValueError, match="is empty"): + credentials.access_token(_OPTIONS) + + def test_invalid_grant_is_explained_and_not_cached(self) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response( + 400, json={"error": "invalid_grant"} + ) + credentials = server.credentials() + with pytest.raises(ResponseError) as exc_info: + credentials.access_token(_OPTIONS) + assert exc_info.value.status_code == 400 + assert exc_info.value.body == '{"error":"invalid_grant"}' + context, hint = exc_info.value.__notes__ + assert context == _CONTEXT + assert "trust rule rule-1" in hint + assert "may have expired" in hint + with pytest.raises(ResponseError): + credentials.access_token(_OPTIONS) + assert len(server.assertions) == 2 + + def test_non_json_error_keeps_whole_body(self) -> None: + body = "" + "x" * 2000 + "" + server = _Server() + server.exchange_response = _error_response(502, body) + with pytest.raises(ResponseError) as exc_info: + server.credentials().access_token(_OPTIONS) + assert (exc_info.value.status_code, exc_info.value.body) == (502, body) + assert exc_info.value.__notes__ == [_CONTEXT] + + def test_other_error_status(self) -> None: + server = _Server() + server.exchange_response = _error_response(429, '{"error":"rate_limited"}') + with pytest.raises(ResponseError, match="HTTP 429") as exc_info: + server.credentials().access_token(_OPTIONS) + assert exc_info.value.__notes__ == [_CONTEXT] + + def test_identity_token_is_given_a_context(self) -> None: + received: list[object] = [] + + def identity_token(context: IdentityTokenProviderContext) -> str: + received.append(context) + return "idp-jwt" + + _Server().credentials(identity_token=identity_token).access_token(_OPTIONS) + assert received == [IdentityTokenProviderContext()] + + def test_identity_token_errors_note_the_trust_rule(self) -> None: + def identity_token(_: IdentityTokenProviderContext) -> str: + raise OSError("idp unreachable") + + with pytest.raises(OSError, match="idp unreachable") as exc_info: + _Server().credentials(identity_token=identity_token).access_token(_OPTIONS) + assert exc_info.value.__notes__ == [_CONTEXT] + + def test_ignores_the_http_clients_own_auth(self) -> None: + class Leaky(httpx.Auth): + def auth_flow(self, request): + request.headers["Authorization"] = "Bearer other-client" + yield request + + server = _Server() + credentials = WorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=lambda _: "idp-jwt", + base_url_override=_BASE_URL, + http_client_override=httpx.Client( + auth=Leaky(), transport=httpx.MockTransport(server.handle) + ), + ) + assert credentials.access_token(_OPTIONS).token == "access-1" + + def test_does_not_follow_redirects(self) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response( + 307, headers={"Location": "https://elsewhere.test/v1/auth/token"} + ) + credentials = WorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=lambda _: "idp-jwt", + base_url_override=_BASE_URL, + http_client_override=httpx.Client( + transport=httpx.MockTransport(server.handle) + ), + ) + with pytest.raises(ResponseError, match="HTTP 307"): + credentials.access_token(_OPTIONS) + assert server.assertions == ["idp-jwt"] + + def test_exchange_timeout(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(_workload_identity, "_EXCHANGE_TIMEOUT", httpx.Timeout(0.1)) + # Accepts the connection but never answers it. + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen() + host, port = listener.getsockname() + credentials = WorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=lambda _: "idp-jwt", + base_url_override=f"http://{host}:{port}", + ) + with pytest.raises(httpx.TimeoutException): + credentials.access_token(_OPTIONS) + + @pytest.mark.parametrize( + ("body", "match"), + [ + ( + {"access_token": "", "token_type": "Bearer", "expires_in": 60}, + "no access_token", + ), + ( + {"access_token": "a", "token_type": "MAC", "expires_in": 60}, + "unsupported token_type", + ), + ( + {"access_token": "a", "token_type": "Bearer", "expires_in": 0}, + "invalid expires_in", + ), + ], + ) + def test_malformed_success(self, body: dict[str, object], match: str) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response( + 200, json={**body, "issued_token_type": _ACCESS_TOKEN_TYPE} + ) + with pytest.raises(ValueError, match=match): + server.credentials().access_token(_OPTIONS) + + @pytest.mark.parametrize( + "kwargs", + [ + {"trust_rule_id": "r"}, + {"trust_rule_id": "r", "identity_token_file": "/f", "identity_token": str}, + {"trust_rule_id": "", "identity_token": str}, + {"trust_rule_id": "r", "identity_token_file": ""}, + { + "trust_rule_id": "r", + "identity_token": str, + "refresh_leeway": timedelta(seconds=-1), + }, + ], + ) + def test_validates_options(self, kwargs: dict[str, object]) -> None: + with pytest.raises(ValueError): + WorkloadIdentityCredentials(**kwargs) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + + +class TestAsyncWorkloadIdentityCredentials: + @pytest.mark.asyncio + async def test_concurrent_callers_share_one_exchange(self) -> None: + server = _Server() + release = asyncio.Event() + + async def handle(request: httpx.Request) -> httpx.Response: + await release.wait() + return server.handle(request) + + credentials = AsyncWorkloadIdentityCredentials( + trust_rule_id="rule-1", + identity_token=server.async_credentials()._identity_token, + base_url_override=_BASE_URL, + http_client_override=httpx.AsyncClient( + transport=httpx.MockTransport(handle) + ), + ) + tasks = [ + asyncio.create_task(credentials.access_token(_OPTIONS)) for _ in range(32) + ] + await asyncio.sleep(0) + release.set() + tokens = await asyncio.gather(*tasks) + assert {token.token for token in tokens} == {"access-1"} + assert len(server.assertions) == 1 + + @pytest.mark.asyncio + async def test_cancelled_waiter_does_not_cancel_exchange(self) -> None: + server = _Server() + release = asyncio.Event() + + async def identity_token(_: IdentityTokenProviderContext) -> str: + await release.wait() + return "idp-jwt" + + credentials = server.async_credentials(identity_token=identity_token) + cancelled = asyncio.create_task(credentials.access_token(_OPTIONS)) + waiting = asyncio.create_task(credentials.access_token(_OPTIONS)) + await asyncio.sleep(0) + cancelled.cancel() + release.set() + assert (await waiting).token == "access-1" + with pytest.raises(asyncio.CancelledError): + await cancelled + + @pytest.mark.asyncio + async def test_invalid_grant_is_explained(self) -> None: + server = _Server() + server.exchange_response = lambda: httpx.Response( + 400, json={"error": "invalid_grant"} + ) + with pytest.raises(ResponseError) as exc_info: + await server.async_credentials().access_token(_OPTIONS) + assert exc_info.value.status_code == 400 + context, hint = exc_info.value.__notes__ + assert context == _CONTEXT + assert "trust rule rule-1" in hint + + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("response", "match"), + [ + (httpx.Response(200, text=""), "unexpected content type"), + (httpx.Response(200, json=["a"]), "validation error"), + ( + httpx.Response( + 200, + json={ + "access_token": "a", + "token_type": "Bearer", + "expires_in": 0, + "issued_token_type": _ACCESS_TOKEN_TYPE, + }, + ), + "invalid expires_in", + ), + ], + ) + async def test_malformed_success( + self, response: httpx.Response, match: str + ) -> None: + server = _Server() + server.exchange_response = lambda: response + with pytest.raises(ValueError, match=match): + await server.async_credentials().access_token(_OPTIONS) + + @pytest.mark.asyncio + async def test_rereads_token_file(self, tmp_path: Path) -> None: + server = _Server(expires_in=600) + path = tmp_path / "token" + path.write_text("jwt-one") + credentials = server.async_credentials(identity_token_file=path) + clock = _with_clock(credentials) + await credentials.access_token(_OPTIONS) + path.write_text("jwt-two") + clock.now += timedelta(minutes=10) + await credentials.access_token(_OPTIONS) + assert server.assertions == ["jwt-one", "jwt-two"] + + +def _management(server: _Server, credentials) -> ManagementClient: + client = ManagementClient(credentials=credentials, base_url_override=_BASE_URL) + client.http_client._transport = httpx.MockTransport(server.handle) # type: ignore[attr-defined] + return client + + +class TestClientsWithCredentials: + def test_send_the_current_token(self) -> None: + server = _Server(expires_in=600) + credentials = server.credentials() + clock = _with_clock(credentials) + management = _management(server, credentials) + management.api.get_organizations_me() + clock.now += timedelta(hours=1) + management.api.get_organizations_me() + inference = InferenceClient( + credentials=credentials, base_url_override=_BASE_URL + ) + inference.http_client._transport = httpx.MockTransport(server.handle) # type: ignore[attr-defined] + inference.http_client.get("/anything") + assert server.authorizations == [ + "Bearer access-1", + "Bearer access-2", + "Bearer access-2", + ] + + @pytest.mark.asyncio + async def test_async_clients_send_the_current_token(self) -> None: + server = _Server() + credentials = server.async_credentials() + management = AsyncManagementClient( + credentials=credentials, base_url_override=_BASE_URL + ) + management.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] + await management.api.get_organizations_me() + inference = AsyncInferenceClient( + credentials=credentials, base_url_override=_BASE_URL + ) + inference.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] + await inference.http_client.get("/anything") + assert server.authorizations == ["Bearer access-1", "Bearer access-1"] + + @pytest.mark.parametrize( + ("challenge", "second"), + [ + ('Bearer realm="baseten", error="invalid_token"', "Bearer access-2"), + ('Bearer realm="model", error="invalid_token"', "Bearer access-1"), + ('Bearer realm="baseten"', "Bearer access-1"), + (None, "Bearer access-1"), + ], + ids=[ + "baseten_refusal", + "other_realm", + "authentication_required", + "no_challenge", + ], + ) + def test_sends_each_request_once(self, challenge: str | None, second: str) -> None: + # Only a refusal from Baseten's auth layer makes the next request use a + # new token; the refused request itself is the caller's to see. + server = _Server() + server.respond = _refuse_once(challenge) + management = _management(server, server.credentials()) + with pytest.raises(ResponseError, match="HTTP 401"): + management.api.get_organizations_me() + management.api.get_organizations_me() + assert server.authorizations == ["Bearer access-1", second] + + @pytest.mark.asyncio + async def test_async_replaces_token_baseten_refused(self) -> None: + server = _Server() + server.respond = _refuse_once('Bearer realm="baseten", error="invalid_token"') + inference = AsyncInferenceClient( + credentials=server.async_credentials(), base_url_override=_BASE_URL + ) + inference.http_client._transport = httpx.MockTransport(server.handle_async) # type: ignore[attr-defined] + response = await inference.http_client.get("/predict") + assert response.status_code == 401 + await inference.http_client.get("/predict") + assert server.authorizations == ["Bearer access-1", "Bearer access-2"] + + def test_accepts_own_credentials(self) -> None: + seen: list[AccessTokenOptions] = [] + + class Own: + def access_token(self, options: AccessTokenOptions) -> AccessToken: + seen.append(options) + return AccessToken( + token="own", expires_at=datetime.now(UTC) + timedelta(hours=1) + ) + + server = _Server() + _management(server, Own()).api.get_organizations_me() + assert server.authorizations == ["Bearer own"] + assert seen == [AccessTokenOptions()] + + def test_leaves_other_hosts_alone(self) -> None: + server = _Server() + management = _management(server, server.credentials()) + management.http_client.put("https://storage.test/presigned") + management.http_client.get( + "/explicit", headers={"Authorization": "Bearer mine"} + ) + assert server.authorizations == [None, "Bearer mine"] + assert server.assertions == [] + + def test_redirect_to_other_host_drops_token(self) -> None: + server = _Server() + server.respond = lambda request: ( + httpx.Response(302, headers={"Location": "https://sub.api.test/landing"}) + if request.url.path == "/start" + else httpx.Response(200) + ) + management = _management(server, server.credentials()) + management.http_client.get("/start", follow_redirects=True) + assert server.authorizations == ["Bearer access-1", None] + + def test_management_with_http_client_override(self) -> None: + server = _Server() + http_client = httpx.Client( + base_url=_BASE_URL, transport=httpx.MockTransport(server.handle) + ) + # No base_url_override: the token goes where the override sends + # requests, not to the default base URL. + management = ManagementClient( + credentials=server.credentials(), http_client_override=http_client + ) + management.api.get_organizations_me() + # Only the API client authenticates; the HTTP client is the caller's. + management.http_client.get("/direct") + assert server.authorizations == ["Bearer access-1", None] + + def test_inference_with_http_client_override(self) -> None: + server = _Server() + server.respond = lambda request: httpx.Response(202) + http_client = httpx.Client( + base_url="https://model-x.api.test", + transport=httpx.MockTransport(server.handle), + ) + # Neither model_id nor chain_id, which only the default URL needs. + inference = InferenceClient( + credentials=server.credentials(), http_client_override=http_client + ) + inference.api.wake(env_name="production") + assert server.authorizations == ["Bearer access-1"] + + def test_validates_auth_options(self) -> None: + credentials = _Server().credentials() + with pytest.raises(ValueError, match="mutually exclusive"): + ManagementClient(api_key="k", credentials=credentials) + # An empty api_key counts as unset, as in Go. + ManagementClient(api_key="", credentials=credentials).close() + with pytest.raises(ValueError, match="required"): + ManagementClient() + for name in ["Authorization", "authorization"]: + with pytest.raises(ValueError, match="Authorization"): + ManagementClient(credentials=credentials, headers={name: "Bearer x"}) + with pytest.raises(ValueError, match="mutually exclusive"): + InferenceClient(api_key="k", credentials=credentials, model_id="m") + InferenceClient(credentials=credentials, model_id="m").close() + with pytest.raises(TypeError, match="async"): + AsyncManagementClient(credentials=credentials) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + with pytest.raises(TypeError, match="async"): + ManagementClient(credentials=_Server().async_credentials()) # type: ignore[arg-type] # ty: ignore[invalid-argument-type] + + +def _refuse_once( + challenge: str | None, +) -> Callable[[httpx.Request], httpx.Response]: + """Answer the first request with a 401 carrying *challenge*, then succeed.""" + calls = 0 + + def respond(request: httpx.Request) -> httpx.Response: + nonlocal calls + calls += 1 + if calls == 1: + headers = {} if challenge is None else {"WWW-Authenticate": challenge} + return httpx.Response(401, headers=headers) + return httpx.Response(200, json=_ORG) + + return respond diff --git a/tests/sandbox/test_auth.py b/tests/sandbox/test_auth.py index 3969b56..db1e3a0 100644 --- a/tests/sandbox/test_auth.py +++ b/tests/sandbox/test_auth.py @@ -17,6 +17,7 @@ AsyncTokenSource, TokenAuth, TokenSource, + is_token_revoked, ) @@ -26,7 +27,7 @@ def _revoked(request: httpx.Request | None = None) -> httpx.Response: @pytest.fixture(autouse=True) def no_revoked_retry_delay(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(baseten.sandbox._auth, "_token_revoked_retry_delay", 0.0) + monkeypatch.setattr(baseten.sandbox._auth, "_token_revoked_retry_delay_sec", 0.0) class _Server: @@ -69,13 +70,14 @@ def handle(self, request: httpx.Request) -> httpx.Response: def tokens(self, *, api_key: str = "key", provider=None) -> TokenSource: return TokenSource( - api_key=api_key, token_provider=provider, mint_api=baseten.client.managementapi.ApiClient( httpx.Client(transport=httpx.MockTransport(self.handle)), base_url="https://api.test", headers={"Authorization": f"Bearer {api_key}"}, - ), + ) + if api_key + else None, ) @@ -89,8 +91,9 @@ def test_mints_with_api_key_and_reuses_token(self) -> None: assert server.mints[0].headers["Authorization"] == "Bearer key" assert json.loads(server.mints[0].content) == {"scopes": ["sandboxes"]} - def test_refreshes_within_a_minute_of_expiry(self) -> None: - server = _Server(expires_in=timedelta(seconds=30)) + def test_refreshes_at_expiry(self) -> None: + # Refresh timing within the lifetime is covered by the token cache tests. + server = _Server(expires_in=timedelta(0)) tokens = server.tokens() assert tokens.token() == "token-1" assert tokens.token() == "token-2" @@ -147,10 +150,6 @@ def provider(context: SandboxTokenProviderContext) -> str: assert tokens.token(revoked_token="provided-1") == "provided-2" assert [context.revoked_token for context in contexts] == [None, "provided-1"] - def test_rejects_api_key_alongside_provider(self) -> None: - with pytest.raises(ValueError, match="api_key must be empty"): - _Server().tokens(provider=lambda context: "token") - def test_no_token_for_empty_api_key_without_provider(self) -> None: server = _Server() assert server.tokens(api_key="").token() is None @@ -226,6 +225,14 @@ def test_resends_with_new_token_after_revocation(self) -> None: "Bearer token-2", ] + def test_does_not_resend_after_invalid_token_challenge(self) -> None: + server = _Server() + server.respond = lambda request: httpx.Response( + 401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'} + ) + assert _get(server, server.tokens()).status_code == 401 + assert server.authorizations == ["Bearer token-1"] + def test_tells_caching_provider_which_token_was_revoked(self) -> None: server = _Server() server.respond = lambda request: ( @@ -245,30 +252,34 @@ def test_returns_revocation_after_two_resends( ) -> None: delays: list[float] = [] monkeypatch.setattr( - baseten.sandbox._auth.time, "sleep", lambda seconds: delays.append(seconds) + baseten.sandbox._auth.time, + "sleep", + lambda seconds: delays.append(seconds), ) server = _Server(respond=_revoked) response = _get(server, server.tokens()) assert response.status_code == 401 assert len(server.requests) == 3 # Only the second resend waits, to be minted past the revocation. - assert delays == [baseten.sandbox._auth._token_revoked_retry_delay] + assert delays == [baseten.sandbox._auth._token_revoked_retry_delay_sec] def test_does_not_resend_other_401(self) -> None: server = _Server(respond=lambda request: httpx.Response(401)) assert _get(server, server.tokens()).status_code == 401 assert len(server.requests) == 1 - def test_does_not_resend_stream_body(self) -> None: + def test_does_not_resend_stream_body_but_drops_its_token(self) -> None: server = _Server(respond=_revoked) + tokens = server.tokens() with httpx.Client(transport=httpx.MockTransport(server.handle)) as client: response = client.post( "https://sbx.test/upload", content=iter([b"chunk"]), - auth=TokenAuth(server.tokens()), + auth=TokenAuth(tokens), ) assert response.status_code == 401 assert len(server.requests) == 1 + assert tokens.token() == "token-2" def test_sends_no_authorization_without_token(self) -> None: server = _Server() @@ -335,11 +346,25 @@ async def handle(request: httpx.Request) -> httpx.Response: return server.handle(request) return AsyncTokenSource( - api_key=api_key, token_provider=provider, mint_api=baseten.client.managementapi.AsyncApiClient( httpx.AsyncClient(transport=httpx.MockTransport(handle)), base_url="https://api.test", headers={"Authorization": f"Bearer {api_key}"}, - ), + ) + if api_key + else None, ) + + +@pytest.mark.parametrize( + ("status", "headers", "revoked"), + [ + (401, {"x-blaxel-error-code": "TOKEN_REVOKED"}, True), + (401, {"WWW-Authenticate": 'Bearer error="invalid_token"'}, False), + (401, {}, False), + (403, {"x-blaxel-error-code": "TOKEN_REVOKED"}, False), + ], +) +def test_is_token_revoked(status: int, headers: dict[str, str], revoked: bool) -> None: + assert is_token_revoked(httpx.Response(status, headers=headers)) is revoked diff --git a/tests/sandbox/test_client.py b/tests/sandbox/test_client.py index 2cceea0..d3e233f 100644 --- a/tests/sandbox/test_client.py +++ b/tests/sandbox/test_client.py @@ -10,6 +10,7 @@ import pytest import baseten.sandbox._client +from baseten.client import AccessToken, AccessTokenOptions from baseten.sandbox import ( AsyncSandboxClient, SandboxAPIError, @@ -34,6 +35,7 @@ def __init__(self) -> None: self.requests: list[httpx.Request] = [] self.authorizations: list[str | None] = [] self.mints = 0 + self.mint_authorizations: list[str | None] = [] self.routes: dict[ tuple[str, str], Callable[[httpx.Request], httpx.Response] ] = {} @@ -67,6 +69,7 @@ def route( def handle(self, request: httpx.Request) -> httpx.Response: if request.url.path == "/v1/token": self.mints += 1 + self.mint_authorizations.append(request.headers.get("Authorization")) return httpx.Response( 200, json={ @@ -102,6 +105,18 @@ async def handle(request: httpx.Request) -> httpx.Response: ) +class _Credentials: + def access_token(self, options: AccessTokenOptions) -> AccessToken: + return AccessToken( + token="access-token", expires_at=datetime.now(UTC) + timedelta(hours=1) + ) + + +class _AsyncCredentials: + async def access_token(self, options: AccessTokenOptions) -> AccessToken: + return _Credentials().access_token(options) + + def _record(name: str = "sbx", **fields: Any) -> dict[str, Any]: return { "name": name, @@ -378,6 +393,37 @@ def test_deletes_and_returns_record(self) -> None: ) assert api.client().delete(name="sbx").status == "DELETING" + def test_mints_sandbox_token_with_credentials(self) -> None: + api = _Api() + api.route("GET", "/v1/sandboxes/instances/sbx", _record()) + client = SandboxClient( + credentials=_Credentials(), + base_url_override="https://api.test", + http_client_override=httpx.Client( + transport=httpx.MockTransport(api.handle) + ), + ) + client.get(name="sbx") + assert api.mint_authorizations == ["Bearer access-token"] + assert api.authorizations == ["Bearer token-1"] + + def test_validates_auth_options(self) -> None: + def provider(context: object) -> str: + return "t" + + with pytest.raises(ValueError, match="only one of"): + SandboxClient(api_key="key", credentials=_Credentials()) + with pytest.raises(ValueError, match="only one of"): + SandboxClient(api_key="key", token_provider=provider) + with pytest.raises(ValueError, match="only one of"): + SandboxClient(credentials=_Credentials(), token_provider=provider) + with pytest.raises(ValueError, match="required"): + SandboxClient() + with pytest.raises(ValueError, match="Authorization"): + SandboxClient( + credentials=_Credentials(), headers={"authorization": "Bearer x"} + ) + def test_closes_only_its_own_http_client(self) -> None: own = SandboxClient(api_key="key", http2=False) own.close() @@ -436,6 +482,25 @@ async def test_converts_error_responses(self) -> None: await api.async_client().delete(name="sbx") assert info.value.code == "NOT_FOUND" + @pytest.mark.asyncio + async def test_mints_sandbox_token_with_credentials(self) -> None: + api = _Api() + api.route("GET", "/v1/sandboxes/instances/sbx", _record()) + + async def handle(request: httpx.Request) -> httpx.Response: + return api.handle(request) + + client = AsyncSandboxClient( + credentials=_AsyncCredentials(), + base_url_override="https://api.test", + http_client_override=httpx.AsyncClient( + transport=httpx.MockTransport(handle) + ), + ) + await client.get(name="sbx") + assert api.mint_authorizations == ["Bearer access-token"] + assert api.authorizations == ["Bearer token-1"] + @pytest.mark.asyncio async def test_closes_only_its_own_http_client(self) -> None: own = AsyncSandboxClient(api_key="key", http2=False)