Skip to content

Add workload identity federation credentials - #47

Open
mingminglang-baseten wants to merge 17 commits into
mainfrom
mingming/wif-credentials
Open

mingminglang-baseten wants to merge 17 commits into
mainfrom
mingming/wif-credentials

Conversation

@mingminglang-baseten

@mingminglang-baseten mingminglang-baseten commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🚀 What

  • New WorkloadIdentityCredentials (and AsyncWorkloadIdentityCredentials) 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 expires
  • The management, inference and sandbox clients accept it through a new credentials option, the same way they accept api_key
  • The Credentials protocol has one method, access_token(options), so fields can be added to the options later
  • A failed exchange raises the same ResponseError as other management calls, with a note naming the trust rule on a refusal

Same design as the Go SDK (basetenlabs/baseten-go#85).

💻 How

  • The token cache moves into baseten/client/_token_auth.py, shared with sandbox tokens
  • If a refresh fails while the replaced token is still valid, the cache keeps using it until it expires
  • With http_client_override, credentials apply to requests made through api, sent to the override's base URL
  • Management and inference requests are sent once with the current token; only sandbox requests resend on a revoked token, as before
  • The exchange relies on httpx's default of not following redirects, as Go does; an http_client_override should not follow them either, since the body carries the identity token
  • The exchange request times out after 10 seconds, as in Go; a deadline on the whole call is the caller's

🔬 Testing

  • Unit tests for the exchange, caching and refresh, concurrent callers, error responses, redirects not being followed, a 401 not being resent, and the sandbox credentials option, sync and async
  • Existing sandbox auth tests pass on the shared cache

🤖 Generated with Claude Code

mingminglang-baseten and others added 3 commits November 16, 2026 03:19
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]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread baseten/client/_token_auth.py Resolved
Comment thread baseten/client/_inference.py Resolved
…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]>
@mingminglang-baseten
mingminglang-baseten marked this pull request as ready for review November 17, 2026 15:41
@cretz

cretz commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

I'm going to wait until basetenlabs/baseten-go#85 is fully reviewed/settled before reviewing this one (and the JS one)

@linear

linear Bot commented Nov 17, 2026

Copy link
Copy Markdown

DI-3021

mingminglang-baseten and others added 5 commits November 18, 2026 14:36
…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]>
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]>
@mingminglang-baseten
mingminglang-baseten changed the base branch from main to mingming/regen-production-spec November 19, 2026 21:17
mingminglang-baseten and others added 2 commits November 19, 2026 16:17
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]>
Base automatically changed from mingming/regen-production-spec to main November 19, 2026 22:55
mingminglang-baseten and others added 3 commits November 19, 2026 17:55
- 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]>
Comment thread baseten/client/_workload_identity.py Outdated
identity_token: IdentityTokenProvider | None = None,
base_url_override: str | None = None,
refresh_leeway: timedelta = timedelta(minutes=5),
exchange_timeout: timedelta = timedelta(seconds=10),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem exposed for a user to set in Go, should it be exposed here?

Comment thread baseten/client/_workload_identity.py Outdated
Comment on lines +247 to +249
# 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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread baseten/client/_token_auth.py Outdated
# 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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This supposed to write under lock?

import baseten.client
import baseten.client.managementapi
import baseten.client.sandboxapi
from baseten.client._token_auth import (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hrmm, was going to say use baseten.client for the public classes to import, but this is fine

Comment thread baseten/client/_workload_identity.py Outdated
Comment on lines +66 to +67
if trust_rule_id.strip() == "":
raise ValueError("trust_rule_id is required")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread baseten/client/_workload_identity.py Outdated
Comment on lines +40 to +44
IdentityTokenProvider: TypeAlias = Callable[[], str]
"""Returns the identity provider's JWT. Called on every exchange."""

AsyncIdentityTokenProvider: TypeAlias = Callable[[], Awaitable[str]]
"""Async form of :data:`IdentityTokenProvider`."""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread baseten/client/_token_auth.py Outdated
"""When the token expires."""


@dataclass(frozen=True)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would suggest making this kw_only=True due to how its used and plans to grow. Same for AccessToken

mingminglang-baseten and others added 3 commits November 20, 2026 17:36
…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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants