> ## Documentation Index
> Fetch the complete documentation index at: https://docs.baseten.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Workload identity federation

> Authenticate workloads on GitHub Actions, AWS, Google Cloud, or Azure with short-lived Baseten access tokens instead of API keys.

> [!NOTE]
>
> Workload identity federation is in **Private Preview**. To turn it on for your organization, [Contact us](mailto:support@baseten.co).

Workload identity federation lets a workload exchange the token its platform already issues, such as a GitHub Actions or Google Cloud token, for a Baseten access token that expires within 1 hour. Send the access token as a bearer token to inference endpoints and the Management API, so you don't store a long-lived API key in CI or production.

## How workload identity federation works

Tokens from an **identity provider** whose claims match a **trust rule** act as that rule's **service account**.

| Resource | What it defines | Scope | Who manages it |
| - | - | - | - |
| Identity provider | A token issuer Baseten trusts, such as GitHub Actions or an Azure tenant | Organization | Organization Admins |
| Service account | A non-human identity with a fixed set of permissions | Team, or organization for API key management | Team Admins for their teams' accounts; Organization Admins for all |
| Trust rule | Which tokens from one identity provider can act as one service account, and the longest token Baseten issues for them | Same as its service account | Same as its service account |

When a workload runs:

1. The workload requests an OpenID Connect (OIDC) token from its platform.
2. The workload sends that token and a trust rule ID to `POST /v1/auth/token`.
3. Baseten checks the token's signature, issuer, expiration, audience, and claims against the trust rule, then returns an access token for the rule's service account.
4. The workload calls Baseten with the access token until it expires, then exchanges a new platform token.

This page covers tokens coming into Baseten. To give Baseten workloads tokens for your cloud resources and Hugging Face repositories, see [OpenID Connect (OIDC) authentication](https://docs.baseten.co/organization/oidc.md).

## Prerequisites

* The Organization Admin role to add an identity provider, and the Team Admin or Organization Admin role to create service accounts and trust rules. For more information, see [Roles and permissions](https://docs.baseten.co/organization/teams.md#roles-and-permissions).
* To set up through the Management API, an API key that belongs to a user with those roles. The workloads you set up don't need an API key.

## Add an identity provider

Add the platform your workload runs on as an identity provider. Baseten supports these providers:

| Provider | Issuer | `sub` holds |
| - | - | - |
| GitHub Actions | `https://token.actions.githubusercontent.com` | `repo:<owner>/<repository>:<context>`, such as `repo:acme/models:ref:refs/heads/main` |
| Google Cloud | `https://accounts.google.com` | The Google Cloud service account's numeric unique ID |
| AWS IAM | Your account's outbound identity federation issuer, such as `https://<id>.tokens.sts.global.api.aws` | The ARN of the AWS IAM role |
| Amazon EKS | Your cluster's OIDC issuer URL | `system:serviceaccount:<namespace>:<service_account>` |
| Azure managed identity (v1) | `https://sts.windows.net/<tenant_id>/` | The managed identity's object ID |
| Azure managed identity (v2) | `https://login.microsoftonline.com/<tenant_id>/v2.0` | The managed identity's object ID |
| Azure Kubernetes Service | Your cluster's OIDC issuer URL | `system:serviceaccount:<namespace>:<service_account>` |
| Baseten | `https://oidc.baseten.co` | The [Baseten OIDC subject](https://docs.baseten.co/organization/oidc.md), starting with `v=1:org=<org_id>:` |

Use the Baseten provider to let a model running on Baseten call Baseten as a service account. The model sends its [runtime OIDC token](https://docs.baseten.co/organization/oidc.md#use-oidc-at-runtime) as the platform token, so set the trust rule's audience to `oidc.baseten.co`.

GitHub Actions, Google Cloud, and Baseten have one issuer, so add each of them once. For the other providers, add one identity provider for each account, tenant, or cluster issuer.

**To add an identity provider**:

> [tab] UI
>
> 1. Sign in to your workspace at [app.baseten.co](https://app.baseten.co) and open **Organization settings**, then choose the **Workload identity** tab.
> 2. Choose **Add identity provider**.
> 3. For **Provider**, select your platform.
> 4. If the provider asks for an **Issuer URL**, enter your account's, tenant's, or cluster's issuer.
> 5. For **Name**, enter a name that's unique in your organization, and optionally add a **Description**.
> 6. Choose **Add identity provider**.
>
> The provider appears in the list with its issuer URL.

> [tab] Management API
>
> Set `kind` to your provider's value. To see each provider's `kind` and the issuer it expects, [list the predefined identity providers](https://docs.baseten.co/reference/management-api/identity-providers/list-predefined-identity-providers.md).
>
> 1. Check the provider's settings without adding it. Run the following command:
>
>    ```bash theme={"system"}
>    curl --request POST \
>      --url https://api.baseten.co/v1/access/identity_providers/verify \
>      --header "Authorization: Bearer $BASETEN_API_KEY" \
>      --header "Content-Type: application/json" \
>      --data '{"predefined": {"kind": "GITHUB_ACTIONS"}}'
>    ```
>
>    The response has `"valid": true`, or an `error` that explains what to fix.
>
> 2. Add the provider. Run the following command:
>
>    ```bash theme={"system"}
>    curl --request POST \
>      --url https://api.baseten.co/v1/access/identity_providers \
>      --header "Authorization: Bearer $BASETEN_API_KEY" \
>      --header "Content-Type: application/json" \
>      --data '{
>        "name": "github-actions",
>        "description": "Deploys from the acme GitHub organization",
>        "predefined": {"kind": "GITHUB_ACTIONS"}
>      }'
>    ```
>
>    The response includes the provider's `id`. Use it when you create a trust rule.
>
> For a provider with its own issuer, also pass `issuer_url`. For example, replace `<issuer_url>` with your Amazon EKS cluster's OIDC issuer URL:
>
> ```json theme={"system"}
> {"predefined": {"kind": "AWS_EKS", "issuer_url": "<issuer_url>"}}
> ```
>
> For more information, see [Add an identity provider](https://docs.baseten.co/reference/management-api/identity-providers/add-an-identity-provider.md).

## Create a service account

A service account carries the permissions a workload gets. Give each workload its own service account with the smallest permission set it needs:

| Permission | Management API `type` | Allows | Belongs to |
| - | - | - | - |
| **Manage all models** | `WORKSPACE_MANAGE_ALL` | Deploying, managing, and calling the team's models | A team |
| **Call all models** | `WORKSPACE_INVOKE` | Calling the team's models | A team |
| **Export all metrics** | `WORKSPACE_EXPORT_METRICS` | Exporting the team's metrics | A team |
| **Call all Model APIs** | `WORKSPACE_INVOKE_MODEL_APIS` | Calling Model APIs | A team |
| **API key management** | `WORKSPACE_MANAGE_API_KEYS` | Creating and revoking team keys and listing or revoking keys across the organization | The organization |

**To create a service account**:

> [tab] UI
>
> 1. Sign in to your workspace at [app.baseten.co](https://app.baseten.co). For a team account, open the team's settings page. For an **API key management** account, open **Organization settings**.
> 2. Choose the **Members** tab, then under **Service accounts**, choose **Create service account**.
> 3. For **Name**, enter a name that's unique in your organization, such as `models-ci`, and optionally add a **Description**.
> 4. For **Permissions**, select the permission the workload needs.
> 5. Under **Model access** or **Model API access**, choose the models, environments, or Model APIs the account can use.
> 6. Choose **Create service account**.
>
> The account appears under **Service accounts**.

> [tab] Management API
>
> Replace `<team_id>` with the team that owns the account. Omit `team_id` only for an **API key management** account.
>
> To narrow the permission, add these fields to `preset_permissions`:
>
> * `model_ids`: for `WORKSPACE_INVOKE` or `WORKSPACE_EXPORT_METRICS`, the models the account covers.
> * `environment_names`: for `WORKSPACE_INVOKE`, the environments it can call. For `WORKSPACE_MANAGE_ALL`, the [restricted environments](https://docs.baseten.co/organization/restricted-environments.md) it can also manage.
> * `model_api_slugs`: for `WORKSPACE_INVOKE_MODEL_APIS`, the Model APIs it can call.
>
> Run the following command:
>
> ```bash theme={"system"}
> curl --request POST \
>   --url https://api.baseten.co/v1/service_accounts \
>   --header "Authorization: Bearer $BASETEN_API_KEY" \
>   --header "Content-Type: application/json" \
>   --data '{
>     "name": "models-ci",
>     "description": "Deploys models from the main branch of acme/models",
>     "team_id": "<team_id>",
>     "preset_permissions": {"type": "WORKSPACE_MANAGE_ALL"}
>   }'
> ```
>
> The response includes the service account's `id`. Use it when you create a trust rule. For more information, see [Create a service account](https://docs.baseten.co/reference/management-api/service-accounts/create-a-service-account.md).

## Create a trust rule

A trust rule names one identity provider and one service account. It accepts a token when the token's `aud` matches the rule's audience and the rule's condition evaluates to true.

### Write the condition

Write the condition as a [Common Expression Language (CEL)](https://cel.dev/) expression over the token's `claims`. It can use `has`, `size`, `startsWith`, `endsWith`, `contains`, and `int`.

Baseten rejects a condition that doesn't pin the token's subject at least this narrowly, in a top-level `&&` clause with `==`, `in`, or `startsWith`:

| Provider | Minimum subject pin |
| - | - |
| GitHub Actions | `claims.sub` equal to, or starting with, `repo:<owner>/`, plus `claims.repository_owner_id` equal to the owner's numeric ID. Someone else can register an owner name after it's deleted, but not its ID. |
| Amazon EKS, Azure Kubernetes Service | `claims.sub` equal to, or starting with, `system:serviceaccount:<namespace>:` |
| Baseten | `claims.sub` equal to, or starting with, `v=1:org=<org_id>:` |
| Google Cloud, AWS IAM, Azure managed identity | `claims.sub` equal to an exact value |

For example, this condition accepts tokens only from workflow runs on the `main` branch of `acme/models`. Find the owner's numeric ID in any GitHub Actions token's `repository_owner_id` claim, or run `gh api users/acme --jq .id`.

```text theme={"system"}
claims.repository_owner_id == '12345678' && claims.sub == 'repo:acme/models:ref:refs/heads/main'
```

> [!WARNING]
>
> A prefix accepts every workload under it. For example, `claims.sub.startsWith('repo:acme/')` accepts runs from every repository that `acme` owns, including pull request runs. Pin the full subject, and require a branch or GitHub environment for service accounts that deploy or manage models.

**To check a trust rule before you create it**:

Replace `<identity_provider_id>` with the provider's ID. The check validates the condition and audience; it doesn't test a token. Run the following command:

```bash theme={"system"}
curl --request POST \
  --url https://api.baseten.co/v1/access/trust_rules/verify \
  --header "Authorization: Bearer $BASETEN_API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
    "identity_provider_id": "<identity_provider_id>",
    "condition": "claims.repository_owner_id == '"'"'12345678'"'"' && claims.sub == '"'"'repo:acme/models:ref:refs/heads/main'"'"'",
    "audience": "https://api.baseten.co"
  }'
```

The response has `"valid": true`, or an `error` that explains what to change.

**To create a trust rule**:

Set the audience to the value your workload requests its platform token for. The examples on this page use `https://api.baseten.co`. For the Baseten provider, use `oidc.baseten.co`, the audience of a model's runtime token. Set the maximum token lifetime between 60 and 3,600 seconds; choose the shortest that covers the work done with one token, such as one deploy job.

> [tab] UI
>
> 1. Sign in to your workspace at [app.baseten.co](https://app.baseten.co) and open **Organization settings**, then choose the **Workload identity** tab and select the identity provider.
> 2. Choose **Create trust rule**.
> 3. For **Name**, enter a name that's unique in your organization, and optionally add a **Description**.
> 4. For **Identity provider**, select the provider. You can't change it later.
> 5. For **Service account**, select the account the tokens act as.
> 6. For **Condition**, enter the CEL expression.
> 7. For **Audience**, keep `https://api.baseten.co` or enter the audience your workload requests.
> 8. For **Max token lifetime**, set the longest token the rule issues. The default is 1 hour.
> 9. Choose **Create trust rule**.
>
> Copy the rule's ID. Your workload sends it during the exchange.

> [tab] Management API
>
> Replace `<identity_provider_id>` and `<service_account_id>` with the IDs from the previous sections. `max_access_token_lifetime_seconds` defaults to 3,600.
>
> Run the following command:
>
> ```bash theme={"system"}
> curl --request POST \
>   --url https://api.baseten.co/v1/access/trust_rules \
>   --header "Authorization: Bearer $BASETEN_API_KEY" \
>   --header "Content-Type: application/json" \
>   --data '{
>     "name": "models-main-deploy",
>     "identity_provider_id": "<identity_provider_id>",
>     "service_account_id": "<service_account_id>",
>     "condition": "claims.repository_owner_id == '"'"'12345678'"'"' && claims.sub == '"'"'repo:acme/models:ref:refs/heads/main'"'"'",
>     "audience": "https://api.baseten.co",
>     "max_access_token_lifetime_seconds": 900
>   }'
> ```
>
> The response includes the rule's `id`. Your workload sends it during the exchange. For more information, see [Create a trust rule](https://docs.baseten.co/reference/management-api/trust-rules/create-a-trust-rule.md).

## Exchange a token and call Baseten

### Get a platform token

Request the platform token with the audience your trust rule expects:

| Platform | How the workload gets a token |
| - | - |
| GitHub Actions | Grant the job `id-token: write` and request a token from `$ACTIONS_ID_TOKEN_REQUEST_URL`, as in the [GitHub Actions example](#deploy-from-github-actions). |
| AWS IAM | Turn on outbound identity federation for the account, then call `aws sts get-web-identity-token --audience https://api.baseten.co`. See [AWS outbound identity federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_outbound.html). |
| Amazon EKS | Mount a [projected service account token](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#serviceaccount-token-volume-projection) with `audience: https://api.baseten.co`, and read it from the mounted file. |
| Google Cloud | Request an ID token from the metadata server, or run `gcloud auth print-identity-token --audiences=https://api.baseten.co`. See [Google Cloud ID tokens](https://cloud.google.com/docs/authentication/get-id-token). |
| Azure managed identity | Request a token from the managed identity endpoint for the app ID URI your trust rule's audience names. See [Azure managed identity tokens](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-use-vm-token). |
| Azure Kubernetes Service | Use the projected service account token that [Microsoft Entra Workload ID](https://learn.microsoft.com/en-us/azure/aks/workload-identity-overview) mounts in the pod. |

### Exchange the token

The exchange request authenticates with the platform token, so it doesn't need an API key.

**To exchange a platform token for a Baseten access token**:

Replace `<platform_token>` with the platform token and `<trust_rule_id>` with the rule's ID. In this request, `audience` is the trust rule's ID, not the audience inside the platform token. `access_token_lifetime_seconds` is optional, can't exceed the rule's maximum, and defaults to it. Run the following command:

```bash theme={"system"}
curl --request POST \
  --url https://api.baseten.co/v1/auth/token \
  --header "Content-Type: application/json" \
  --data '{
    "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
    "subject_token": "<platform_token>",
    "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
    "audience": "<trust_rule_id>",
    "access_token_lifetime_seconds": 900
  }'
```

```json Response theme={"system"}
{
  "access_token": "<access_token>",
  "issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
  "token_type": "Bearer",
  "expires_in": 900
}
```

**To call a model with the access token**:

Replace `<access_token>` with the token from the response. Run the following command:

```bash theme={"system"}
curl --request POST \
  --url https://model-abc123.api.baseten.co/environments/production/predict \
  --header "Authorization: Bearer <access_token>" \
  --header "Content-Type: application/json" \
  --data '{"prompt": "What is workload identity federation?"}'
```

The access token has the service account's permissions and works with the [Management API](https://docs.baseten.co/reference/management-api/overview.md) and inference endpoints, including [Model APIs](https://docs.baseten.co/inference/model-apis/overview.md). It can't create [sandbox](https://docs.baseten.co/sandboxes/authentication.md) tokens.

### Deploy from GitHub Actions

This workflow deploys a model when you push to `main`, using the trust rule from the condition example. It stores the trust rule ID, which isn't a secret, as a repository variable in place of an API key.

**To deploy a model from GitHub Actions**:

1. In your repository, add a variable named `BASETEN_TRUST_RULE_ID` with the trust rule's ID. For more information, see [GitHub's variables documentation](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-variables).

2. Add the following workflow as `.github/workflows/deploy.yml`:

   ```yaml .github/workflows/deploy.yml theme={"system"}
   name: Deploy model
   on:
     push:
       branches: [main]

   permissions:
     contents: read
     id-token: write

   jobs:
     deploy:
       runs-on: ubuntu-latest
       steps:
         - uses: actions/checkout@v4

         - name: Exchange the GitHub token for a Baseten token
           env:
             TRUST_RULE_ID: ${{ vars.BASETEN_TRUST_RULE_ID }}
           run: |
             GITHUB_TOKEN=$(curl --silent --fail \
               --header "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
               "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://api.baseten.co" | jq -r .value)
             BASETEN_TOKEN=$(curl --silent --fail \
               --request POST https://api.baseten.co/v1/auth/token \
               --header "Content-Type: application/json" \
               --data "$(jq -n --arg token "$GITHUB_TOKEN" --arg rule "$TRUST_RULE_ID" '{
                 grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
                 subject_token: $token,
                 subject_token_type: "urn:ietf:params:oauth:token-type:jwt",
                 audience: $rule
               }')" | jq -r .access_token)
             echo "::add-mask::$BASETEN_TOKEN"
             echo "BASETEN_API_KEY=$BASETEN_TOKEN" >> "$GITHUB_ENV"

         - name: Install the Baseten CLI
           run: |
             brew tap basetenlabs/baseten
             brew trust --formula basetenlabs/baseten/baseten
             brew install baseten

         - name: Push the model
           run: baseten model push --dir ./my-model --environment production --wait
   ```

3. Push a commit to `main`. The run succeeds when the **Push the model** step finishes, because `--wait` fails the step if the deployment doesn't become active.

`id-token: write` lets the job request a GitHub token; it grants no write access to the repository. The `::add-mask::` command keeps the access token out of the job log, and the Baseten CLI reads it from `BASETEN_API_KEY`. The Truss push GitHub Action doesn't support workload identity federation. For other deploy options, see [CI/CD](https://docs.baseten.co/deployment/ci-cd.md).

## Refresh tokens in long-running applications

A long-running application needs a new access token before the current one expires. This Python helper caches the access token and exchanges a fresh platform token when 80% of the token's lifetime has passed.

```python baseten_token.py theme={"system"}
import threading
import time
from typing import Callable

import requests

TOKEN_URL = "https://api.baseten.co/v1/auth/token"


class BasetenToken:
    """Exchanges a platform token for a Baseten access token and refreshes it before expiry."""

    def __init__(self, trust_rule_id: str, get_platform_token: Callable[[], str]):
        self._trust_rule_id = trust_rule_id
        self._get_platform_token = get_platform_token
        self._lock = threading.Lock()
        self._token = None
        self._refresh_at = 0.0

    def get(self) -> str:
        with self._lock:
            if self._token is None or time.monotonic() >= self._refresh_at:
                response = requests.post(
                    TOKEN_URL,
                    json={
                        "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
                        "subject_token": self._get_platform_token(),
                        "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
                        "audience": self._trust_rule_id,
                    },
                    timeout=30,
                )
                response.raise_for_status()
                body = response.json()
                self._token = body["access_token"]
                self._refresh_at = time.monotonic() + body["expires_in"] * 0.8
            return self._token
```

Pass a function that returns a current platform token, and read the token file on every call, because the platform rotates it. For example, on Amazon EKS with a projected token mounted at `/var/run/secrets/baseten/token`, call a Model API through the OpenAI SDK:

```python theme={"system"}
import os

from openai import OpenAI

from baseten_token import BasetenToken

token = BasetenToken(
    trust_rule_id=os.environ["BASETEN_TRUST_RULE_ID"],
    get_platform_token=lambda: open("/var/run/secrets/baseten/token").read().strip(),
)
client = OpenAI(base_url="https://inference.baseten.co/v1", api_key="unused")

response = client.with_options(api_key=token.get()).chat.completions.create(
    model="zai-org/GLM-5.3",
    messages=[{"role": "user", "content": "What is workload identity federation?"}],
)
print(response.choices[0].message.content)
```

Call `client.with_options(api_key=token.get())` for each request so the client always sends a current token. The workload identity classes in the Anthropic and OpenAI SDKs exchange tokens with those providers, not with Baseten, so use this helper instead.

## Stop creating API keys

After every workload authenticates with workload identity federation, stop new API keys from being created and revoke the keys your workloads used. Turning off key creation doesn't affect existing keys; they keep working until they expire or you revoke them.

**To stop using API keys after you move to workload identity federation**:

1. [Turn off API key creation](https://docs.baseten.co/organization/api-keys.md#control-who-can-create-api-keys) for personal keys, team and API key management keys, or both.

2. In the [audit log](https://docs.baseten.co/organization/audit-logs.md), confirm that no workload has used a key since you moved to workload identity federation.

   > [!WARNING]
   >
   > Revoking a key immediately stops every workload that still sends it.

3. [Revoke keys across the organization](https://docs.baseten.co/organization/api-keys.md#view-and-revoke-keys-as-an-organization-admin) that your workloads used.

## Token lifetimes and limits

| Item | Limit |
| - | - |
| Access token lifetime | 1 second up to the trust rule's maximum; defaults to the maximum |
| Trust rule maximum token lifetime | 60 to 3,600 seconds; defaults to 3,600 |
| Platform token lifetime | At most 1 hour from `iat` to `exp`; 24 hours for Amazon EKS, Azure managed identity, and Azure Kubernetes Service |
| Platform token format | A JWT signed with RS256 or ES384, with `iss`, `aud`, `exp`, `iat`, and `sub` claims |
| Clock skew | 60 seconds |
| Identity providers | 50 per organization |
| Trust rules | 50 per identity provider |
| Condition length | 4,096 characters |

Access tokens use the same [rate limits](https://docs.baseten.co/reference/management-api/rate-limits.md) as API keys.

## Troubleshoot token exchange

Every rejected exchange returns HTTP 400 with `"error": "invalid_grant"`, whatever the cause, so the response doesn't reveal which check failed. Check each condition in order:

1. The request's `audience` is the trust rule's ID, not the platform token's audience.
2. The platform token's `iss` matches the rule's identity provider. For a provider with its own issuer, the issuer URL must match exactly, including any trailing slash.
3. The platform token's `aud` equals the rule's audience.
4. The token's claims satisfy the condition. Decode the token on your own machine to compare its `sub` and other claims; don't paste it into an online decoder.
5. The platform token hasn't expired and isn't older than its platform's limit.
6. The rule's service account is enabled. If it's disabled, re-enable it, or [update the service account](https://docs.baseten.co/reference/management-api/service-accounts/update-a-service-account.md) with `"disabled": false`.

An `invalid_request` error means the request body is malformed, and `unsupported_grant_type` means `grant_type` isn't the token exchange grant. To confirm the rule itself is valid, [verify the trust rule](https://docs.baseten.co/reference/management-api/trust-rules/verify-a-trust-rule.md).
