Repository navigation
Add workload identity federation credentials - #47
mingminglang-baseten wants to merge 17 commits into
Conversation
WorkloadIdentityCredentials and AsyncWorkloadIdentityCredentials exchange an identity provider's JWT for a short-lived Baseten access token under a trust rule (RFC 8693 token exchange at POST /v1/auth/token), cache it, and replace it before it expires. The management and inference clients accept them, or any AccessTokenSource, as `credentials` in place of `api_key`, send the token only to their own API host, and resend a request whose token is refused when the source can drop it. The token cache and the resend-on-refusal auth move from the sandbox package into baseten.client._token_auth, which the sandbox token source now uses too. Refusal also covers a 401 whose WWW-Authenticate names error="invalid_token", and the refresh margin is capped at half a token's lifetime. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The management and inference clients fetch a token from their credentials and send each request once; a 401 is returned to the caller as is, since on inference it can come from the model itself. Sandbox requests keep their resend on a refused token, and the shared auth now drops the refused token itself, even when the request cannot be sent again. The credentials protocol is now Credentials / AsyncCredentials, named after the client option, with one access_token method taking AccessTokenOptions so fields can be added without breaking implementations. The separate invalidation protocol is gone. The refresh margin is refresh_leeway everywhere. A refused exchange raises the management API's ResponseError with the full body; an invalid_grant refusal adds a note naming the trust rule and the possible causes. The exchange never follows redirects, since its body carries the identity token. The sandbox clients accept credentials directly, mutually exclusive with api_key and token_provider, and mint sandbox tokens with them. The workload identity usage moves from the README into the credentials docstring, matching how other client options are documented. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
The auth origin check can leak bearer tokens over HTTP by ignoring the scheme, while preconfigured client overrides can trigger errors or leave requests unauthenticated because the wrong origin is used.
2 open issues
What changed in this PR
Adds workload identity federation as an alternative to API keys in the Python SDK, following the Go SDK’s design.
Changes:
- Introduces sync and async credentials that exchange identity tokens for cached, short-lived access tokens.
- Adds credential support to management, inference, and sandbox clients, with shared token caching and sandbox revocation handling.
- Adds tests for exchange behavior, refresh, concurrency, redirects, errors, and client integration.
| File | Description |
|---|---|
tests/sandbox/test_client.py |
Tests credential-based sandbox token minting and auth validation. |
tests/sandbox/test_auth.py |
Updates shared-cache tests and revocation expectations. |
tests/client/test_workload_identity.py |
Tests credential exchange, refresh, safety, and client integration. |
tests/client/test_token_auth.py |
Tests shared caching, concurrency, and token invalidation. |
baseten/sandbox/_client.py |
Accepts credentials for minting sandbox tokens. |
baseten/sandbox/_auth.py |
Reuses shared token caching and authentication logic. |
baseten/client/_workload_identity.py |
Implements sync and async workload identity credentials. |
baseten/client/_token_auth.py |
Defines credential protocols, caches, and auth handlers. |
baseten/client/_management.py |
Adds credentials to management clients. |
baseten/client/_inference.py |
Adds credentials to inference clients. |
baseten/client/__init__.py |
Exports and documents the new authentication types. |
Review effort: Balanced
…en credentials The token caches now give a caller that joined a failed mint one more try, shared with the others that joined it, instead of one full mint per waiter in turn. When a refresh fails, the replaced token is used while still unexpired. Access tokens are left out of reprs, the credentials origin check compares the scheme, and a client given both credentials and an HTTP client override sends the token to that client's base URL. The exchange timeout is a timedelta like the other durations, the async credentials read the token file off the event loop, and blank trust rule IDs and empty token file paths are refused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I'm going to wait until basetenlabs/baseten-go#85 is fully reviewed/settled before reviewing this one (and the JS one) |
…back to sandbox A 401 with WWW-Authenticate: Bearer realm="baseten", error="invalid_token" comes only from Baseten's auth layer, so the client passes that token as refused_token on the next access_token call and the workload identity credentials drop it. The refused request is not sent again. TokenAuth, AsyncTokenAuth and is_token_refused had only the sandbox client left as a caller, so they move into the sandbox package. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The production management spec now documents POST /v1/auth/token, so the workload identity exchange builds its body from the generated TokenExchangeRequest. The exchange keeps its own request so it can refuse redirects, which the generated client leaves to the HTTP client. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The regeneration moves to its own PR; the exchange body switches to the generated type once that lands. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Matches baseten-go: the exchange goes through the generated post_auth_token, and redirects are left to the HTTP client, which does not follow them by default. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- exchange_timeout now bounds a whole sync exchange, including the identity token provider, as in Go; httpx alone bounds each phase. - The exchange no longer inherits an http_client_override's own auth. - Every exchange failure notes the trust rule it was for. - The async exchange no longer relabels a provider's own TimeoutError. - Taking the refused token is atomic across threads. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- An empty api_key next to credentials counts as unset, as in Go. - Identity token provider and file errors get the same trust rule note as other exchange failures. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| identity_token: IdentityTokenProvider | None = None, | ||
| base_url_override: str | None = None, | ||
| refresh_leeway: timedelta = timedelta(minutes=5), | ||
| exchange_timeout: timedelta = timedelta(seconds=10), |
There was a problem hiding this comment.
This doesn't seem exposed for a user to set in Go, should it be exposed here?
| # httpx bounds each phase of a request rather than the whole of it, and | ||
| # nothing bounds the identity token provider, so the exchange runs on | ||
| # its own thread and is abandoned when it overruns. |
There was a problem hiding this comment.
I don't think we should be starting threads for the user. If the only reason is timeout enforcement, IMO we can do it on httpx and can document caller is expected to do whole-call timeouts (would even be ok if we didn't use asyncio.timeout in async one for consistency, but that is less of a concern since it doesn't carry the overhead this does). If we did feel the need to use separate threads here, I think we'd have to talk about accepting a thread pool executor and such, but I'd rather avoid it and just document whole-call timeout is user problem.
| # 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): | ||
| self._refused = token |
There was a problem hiding this comment.
This supposed to write under lock?
| import baseten.client | ||
| import baseten.client.managementapi | ||
| import baseten.client.sandboxapi | ||
| from baseten.client._token_auth import ( |
There was a problem hiding this comment.
Hrmm, was going to say use baseten.client for the public classes to import, but this is fine
| if trust_rule_id.strip() == "": | ||
| raise ValueError("trust_rule_id is required") |
There was a problem hiding this comment.
Pedantic, stripping seems to be a bit of overkill and is inconsistent with Go/JS, just a if not trust_rule_id: is good enough
| IdentityTokenProvider: TypeAlias = Callable[[], str] | ||
| """Returns the identity provider's JWT. Called on every exchange.""" | ||
|
|
||
| AsyncIdentityTokenProvider: TypeAlias = Callable[[], Awaitable[str]] | ||
| """Async form of :data:`IdentityTokenProvider`.""" |
There was a problem hiding this comment.
I am trusting both here and in Go that we will never need to provide some structured input to the implementers of these? I didn't think about it in Go, but if it's unlikely, no worries
| """When the token expires.""" | ||
|
|
||
|
|
||
| @dataclass(frozen=True) |
There was a problem hiding this comment.
Would suggest making this kw_only=True due to how its used and plans to grow. Same for AccessToken
…n under the lock, plain trust rule check Co-Authored-By: Claude Opus 5.5 <[email protected]>
The exchange's HTTP request times out after a fixed 10 seconds, as in Go. Co-Authored-By: Claude Opus 5.5 <[email protected]>
So fields can be added later without breaking providers. Co-Authored-By: Claude Opus 5.5 <[email protected]>


🚀 What
WorkloadIdentityCredentials(andAsyncWorkloadIdentityCredentials) exchange an OIDC identity token (for example a Kubernetes projected service account token) for a short-lived Baseten access token under a trust rule, and refresh it before it expirescredentialsoption, the same way they acceptapi_keyCredentialsprotocol has one method,access_token(options), so fields can be added to the options laterResponseErroras other management calls, with a note naming the trust rule on a refusalSame design as the Go SDK (basetenlabs/baseten-go#85).
💻 How
baseten/client/_token_auth.py, shared with sandbox tokenshttp_client_override,credentialsapply to requests made throughapi, sent to the override's base URLhttp_client_overrideshould not follow them either, since the body carries the identity token🔬 Testing
credentialsoption, sync and async🤖 Generated with Claude Code