Workload identity for AI agents replaces static keys
Workload identity for AI agents replaces static cloud keys with temporary, scoped credentials tied to where each agent actually runs.

Table of Contents
An AI agent that can open a pull request, run a deployment, query production, and call another cloud is a workload with unusually wide reach. Giving it a JSON key or client secret is easy. It also separates authority from the place, process, and moment where that authority should exist. Once copied into an environment variable, CI setting, or agent tool configuration, the credential can outlive the run and travel anywhere.
Workload identity for AI agents replaces that portable secret with a claim about the running workload. A cloud security token service verifies the claim and issues temporary credentials for one defined role. The hard part is not making token exchange work. The hard part is choosing an identity that is precise enough to survive a compromised prompt, a reused workflow, and a move between clouds.
I have inherited systems where nobody could answer which automation still used a service account key. Rotation became an outage lottery, so the key stayed. Agent systems make that old mistake more expensive because one process can select tools and resources dynamically. The safe design binds identity to immutable execution facts, limits every exchange by issuer, subject, and audience, and records the original agent behind the cloud role.
Agent identity must attach to execution
A useful agent identity describes a running workload, not a bot name in a product screen. Names such as research-agent or deploy-agent tell an operator what the software is supposed to do. They do not prove which repository, environment, cluster namespace, service account, workflow, or build revision launched it. An attacker who can start a different process with the same label wins if the trust policy accepts the label alone.
Start with an execution identity that the platform can attest. In Kubernetes, that might be the cluster issuer plus the namespace and service account in the token subject. In a hosted CI system, it might include the organization, repository, branch or protected environment, and workflow identity supplied by the issuer. On a cloud virtual machine, use the instance or managed workload identity exposed through the provider, not a credential copied into the image.
Keep agent purpose as an authorization attribute after the execution identity is established. A single agent implementation may run as planner in development and release-controller in production, but those runs should not inherit the same cloud role. Conversely, several replicas of the same approved deployment can share one workload identity when they have the same code path, trust boundary, and permissions. Identity granularity should follow the smallest unit you can revoke or quarantine without stopping unrelated work.
This distinction matters during an incident. Disabling a friendly bot name in an orchestration database may not invalidate a cloud session already issued to a pod. Deleting or blocking the workload binding at the issuer and destination breaks the path that minted the credential. If your response plan cannot name both controls, you have an application label, not an enforceable workload identity.
Federation verifies claims, then mints local authority
Federation lets a destination cloud trust a credential issued by the agent's execution environment, then convert it into local authority. It does not make AWS, Microsoft Entra ID, Google Cloud, Kubernetes, or SPIFFE identities interchangeable. Each destination still applies its own trust configuration and issues a token or role session that its services understand.
The flow has four decisions. The source platform attests the workload and issues a signed token. The destination validates the token's issuer, signature, expiry, subject, and audience. A trust policy maps accepted claims to a local principal. The destination then issues a temporary credential whose permissions come from local IAM. Authentication proves which source workload arrived; authorization decides what that workload can do. Treating the first as proof of the second is how a valid token gets excessive access.
RFC 8693 describes OAuth token exchange with a required subject_token and an optional actor_token. Its audience identifies the target service where the requested token should be usable. The specification also warns, in effect, that exchange does not invalidate the input token and does not create a continuing link between input and output credentials. That caveat is central for agents: revoking the source after an alert may leave an already minted destination session alive until its own expiry.
The cloud implementations differ. AWS STS accepts an OIDC JWT through AssumeRoleWithWebIdentity and returns temporary role credentials. Google Cloud Security Token Service exchanges an external credential for a federated token, which can access a resource directly or impersonate a service account. Microsoft Entra workload identity federation matches an external token to a federated identity credential and returns an access token. Design one conceptual flow, but write and test three destination policies. There is no universal policy hidden behind OIDC.
The subject claim needs an ownership model
Choose the subject claim as if you will use it to shut down one agent at 2 a.m. It must be unique, stable for the approved workload, issued by an authority you control or explicitly trust, and narrow enough that another tenant cannot produce the same effective identity. A subject based on a display name, mutable repository name, branch supplied by untrusted code, or user chosen metadata fails one of those tests.
A practical identity record should answer four questions: who owns the workload, where it may run, which lifecycle created it, and which environment it belongs to. Those facts do not all need to fit inside sub. The issuer and subject can establish the principal while mapped claims and destination conditions narrow repository, environment, or tenant. Keep the mapping in version control beside the infrastructure policy, with an owner and a removal date for temporary bindings.
Multi-tenant issuers deserve extra suspicion. Google Cloud's workload federation guidance says checking a shared issuer URL is insufficient for providers where every customer uses the same issuer. It recommends an attribute condition that restricts tokens to the trusted organization or tenant. The general rule applies everywhere: issuer proves which identity service signed a token, not which customer of that service requested it.
Use immutable identifiers for trust and readable names for logs. If a repository can be renamed or transferred, bind its stable ID and copy its current name into a session attribute for operators. If a Kubernetes service account can be recreated by a team with namespace write access, ask whether that team is allowed to obtain the cloud role. Namespace and service account matching cannot compensate for weak Kubernetes administration. The identity chain is only as strong as the authority that can create the attested workload.
Avoid a global subject such as agent-prod across several clusters. Even if the issuer differs today, someone will eventually simplify a condition or reuse a provider. A format such as system:serviceaccount:payments:reconciler is useful only when the destination also pins the exact cluster issuer and intended audience. Identity is the tuple of validated claims, not one attractive string.
Audience is a boundary, not token decoration
Every federation path should require a destination-specific audience. The audience prevents a token minted for one relying party from being replayed at another relying party that trusts the same issuer and subject. Signature and expiry checks cannot catch that substitution because the stolen token is genuine and current.
Kubernetes can project a service account token for a chosen audience and lifetime. An agent that needs AWS should receive a token intended for AWS STS, not the default token it uses to call the Kubernetes API. A minimal pod fragment makes the boundary visible:
apiVersion: v1
kind: Pod
metadata:
name: release-agent
spec:
serviceAccountName: release-agent
automountServiceAccountToken: false
containers:
- name: agent
image: registry.example/release-agent:42
volumeMounts:
- name: aws-identity
mountPath: /var/run/identity
readOnly: true
volumes:
- name: aws-identity
projected:
sources:
- serviceAccountToken:
path: token
audience: sts.amazonaws.com
expirationSeconds: 900
This prevents the pod from receiving the broad default service account token through automatic mounting and gives the AWS exchange its own token file. It does not stop code in the same container from reading that file, and it does not make containers a security boundary. AWS's EKS documentation states that containers sharing a node still share a kernel and warns that unrestricted instance metadata can expose node credentials. Federation removes a stored secret; runtime isolation remains a separate job.
Pin the expected audience at the destination too. Source configuration without a matching destination condition relies on every issuer to behave forever as you expect. Destination validation without source separation leaves extra tokens available inside the agent. Both sides are cheap to configure and expensive to debug after a replay, so enforce both.
Each cloud role needs a narrow trust policy
A federated role has two permission surfaces: who may assume it and what it may do afterward. Teams often review the permissions policy and skim the trust policy. For agent workloads, the trust policy deserves equal scrutiny because a broad principal condition can hand carefully scoped permissions to thousands of unintended runs.
For AWS, bind the exact OIDC provider, audience, namespace, and service account. This trust policy shows the shape, with account, region, cluster, and workload placeholders that must be replaced:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::111122223333:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/CLUSTER_ID"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"oidc.eks.us-east-1.amazonaws.com/id/CLUSTER_ID:aud": "sts.amazonaws.com",
"oidc.eks.us-east-1.amazonaws.com/id/CLUSTER_ID:sub": "system:serviceaccount:release:release-agent"
}
}
}]
}
The important property is exact matching. Replacing StringEquals with a wildcard for every service account in release transfers cloud access control to anyone who can create or change service accounts in that namespace. Sometimes that is the intended ownership model. Usually it is an unnoticed escalation path.
In Google Cloud, map the external subject to google.subject, add attribute conditions for the trusted tenant and workload, then grant either direct resource access or service account impersonation. Google's documentation now recommends direct resource access where the API supports it. Impersonation remains useful for compatibility, but one dedicated service account per application keeps unrelated agents from converging on a shared identity. Never grant the entire workload identity pool permission merely because the pool sounded like a boundary when it was created.
In Microsoft Entra ID, a federated identity credential matches issuer, subject, and audience. The documented default audience is api://AzureADTokenExchange, and wildcard characters are not supported in these credential properties. That exactness is helpful, but the local app or managed identity can still have excessive directory or resource permissions. Match narrowly, then review what the matched identity can request.
Agent delegation and workload identity are different claims
Workload identity says which process is calling. Delegation says on whose behalf the process is acting. An agent that responds to a user request may need both facts, especially when it reads customer data, approves a payment, or changes production. Collapsing them into one service role makes every action look like the agent chose it alone and often gives every user the service's maximum permissions.
RFC 8693 models this distinction with a subject token and an actor token. Not every cloud federation product exposes that model end to end, so do not pretend a role session preserves delegation unless you can find both identities in the issued claims and audit logs. When the destination supports only workload federation, enforce user authorization in a broker or application service before the cloud call and pass a tamper resistant request identifier into permitted session metadata. The cloud role should still cap the agent's maximum authority.
Never pass the user's cloud credential into the agent tool loop. That popular shortcut preserves user attribution in some logs, but it also gives a prompt-driven process a bearer credential intended for an interactive client. Instead, the user authorizes a specific operation, the policy layer checks the operation and resource, and the workload identity performs it within a narrow role. Store the approval record separately with the request hash, user, policy version, agent execution ID, and result.
Autonomous background work has no current human subject. Give it a workload identity with permissions for its scheduled job and record the owning team or service, not a fictional user. If an agent spawns another agent, the child needs its own execution identity when it crosses a permission boundary. A parent label embedded in free-form metadata is useful for tracing, but it cannot substitute for destination policy.
This is also where many agent frameworks stop too early. Their internal agent IDs help route messages and budgets. Cloud IAM does not know whether that ID came from an attested scheduler or from a string in a tool request. Bind framework identity to the platform workload at the broker, and reject any mismatch before exchange.
Temporary credentials limit exposure but not misuse
Short credential lifetime reduces how long a stolen token works, but it does not reduce what the token can do during that time. A 15 minute administrator session is still an administrator session. Set lifetime after you narrow permissions and trust conditions, not instead of doing that work.
Size the lifetime around one operation or bounded batch, including expected retries. Agents should fetch credentials when a tool call needs them, keep them in memory when the SDK permits, and discard them after the operation. Do not mint cloud sessions at process startup for an agent that may spend an hour planning. Do not write exchanged tokens into conversation transcripts, tool results, exception payloads, build artifacts, or shared caches. Redaction must cover authorization headers and provider-specific credential fields.
Refresh behavior needs an explicit decision. RFC 8693 says temporary credential exchange will typically not return a refresh token. That is a sound default for agents. When a task runs longer, the workload should obtain a fresh source assertion and repeat the exchange under current policy. A long lived refresh token quietly recreates the static secret that federation was meant to remove.
Replay remains possible for bearer tokens until expiry unless the system adds proof of possession or one-time semantics. SPIFFE's own concepts guidance advises X.509-SVIDs where possible because JWTs can be replayed after theft. X.509 workload identity with mutual TLS can be a better fit for service-to-service calls you control, while cloud STS endpoints commonly require a signed assertion. Use the credential form the destination supports, minimize where bearer tokens appear, and isolate the exchange component from the model and untrusted tools.
Clock skew and issuer outages cause real operational failures. Monitor token age, exchange latency, denial reason, and time synchronization without logging raw tokens. Cache public verification keys according to provider guidance, but fail closed when an issuer, key ID, signature, audience, or subject cannot be validated. Keeping an emergency static key beside the agent as a fallback defeats the design and ensures the fallback eventually becomes the main path.
Audit records must preserve the source agent
A useful audit trail connects the destination action back to one execution, one source identity, one policy decision, and, when relevant, one user approval. Cloud logs that show only prod-agent-role answer which role acted but not which run obtained it. Shared roles need session attributes or an external correlation record that survives the exchange.
Define an execution ID at the trusted scheduler, not inside model output. Carry a sanitized, bounded form into role session names, token attributes, or request metadata supported by the provider. Record the full mapping in your own append-only event store: execution ID, issuer, subject, audience, destination principal, credential issue and expiry times, policy version, requested action, and outcome. Never store the source assertion or destination access token.
Test what each cloud actually logs. AWS CloudTrail can record assumed role activity, but the usefulness of the principal depends on the role session information you supply and permit. Google Cloud notes that google.subject appears in Cloud Logging for federated principals, which is a strong reason to map a unique immutable value. Microsoft Entra sign-in logs and destination resource logs cover different parts of the path; confirm that your correlation field reaches the resource action rather than stopping at token issuance.
Run a quarterly trace exercise with a real nonproduction action. Begin at a storage write or IAM denial and identify the agent execution without consulting the person who built the integration. Then begin with the execution and find every cloud action it caused. If either direction needs guesswork, fix the identity mapping before adding more autonomous tools. An incident responder should not have to decode a reused service account shared by six agents.
Retention also follows risk. Keep identity and authorization evidence long enough for your investigation and compliance needs, while excluding prompts or customer content that the security record does not require. Identity telemetry should explain authority. It should not become a second, poorly governed copy of the agent's working data.
Broad federation fails quietly before it fails loudly
The most dangerous federation failures look like successful deployments. Imagine a company that creates one OIDC provider for its CI issuer, maps the repository name into a cloud subject, and allows any branch to assume a deployment-agent role. The agent works, the static key disappears, and the security ticket closes.
Months later, a maintainer adds a pull request workflow that invokes the same reusable deployment job. An external contributor changes the agent instructions and causes a cloud tool call. The token has a valid signature and issuer. Its subject still matches the mutable repository name. Because the trust policy did not restrict the protected environment, immutable repository owner, workflow source, or event type, the destination issues a legitimate role session. Nothing was stolen, so secret scanning and rotation alerts stay quiet. The trust relationship authorized the wrong execution.
The repair starts at the source. Separate untrusted review workflows from privileged release workflows, and make the issuer include claims that the destination can verify. At the destination, pin the tenant or organization, immutable repository identity, approved workflow or environment, and audience. Give the release agent a role that can deploy only the intended service and environment. Add a policy test that presents claim sets from a fork, a renamed repository, an unprotected branch, and the approved release path. Only the last set should pass.
A second quiet failure comes from identity pooling. Five agents impersonate one service account because maintaining one binding feels simpler. A new permission needed by the backup agent is added to the shared account, and the code review agent receives it too. No federation rule changed, but effective authority expanded. Dedicated destination principals make permission changes local and produce cleaner logs. The extra infrastructure objects cost less than proving which shared consumer used a permission.
A third failure is an emergency credential baked into the image in case exchange breaks. It survives because nobody wants to test its removal. During an outage the SDK finds that credential first, and after recovery the agent keeps using it. Detect this with a runtime check that fails when static credential environment variables or known key files exist. Reliability should come from redundant identity infrastructure and bounded queues, not a permanent bypass.
Migration should remove secrets, not rename them
Move one agent path at a time, and define completion as deletion of the old credential plus evidence that it can no longer authenticate. A federation project that leaves every JSON key active has added complexity without reducing exposure.
- Inventory each agent's credential source, destination APIs, effective permissions, owner, and runtime. Use cloud access logs and secret stores, then confirm findings with a controlled run because configuration files rarely tell the full story.
- Choose one low-risk agent with a clear runtime identity. Create a destination principal with only its observed and approved actions, then configure issuer, subject, and audience checks.
- Run federation in a nonproduction environment and test negative claim sets. Verify expiry, clock skew behavior, log correlation, and denial messages before touching production.
- Deploy the federated path with the static credential disabled for that process. Watch successful exchanges and resource denials, then remove the credential from secret stores, CI settings, images, and recovery notes. Revoke it at the provider.
- Add policy checks to the delivery pipeline so later edits cannot widen subject or audience conditions unnoticed. Assign an owner for issuer keys, trust mappings, destination roles, and incident revocation.
Do not begin by building a universal identity broker for every cloud and agent. Brokers can centralize policy and evidence, but they also become a privileged exchange point that must authenticate runtimes correctly. First prove the identity tuple and destination policy with native federation. Introduce a broker when repeated mappings, delegation, or audit requirements justify its control plane.
SPIFFE and SPIRE are worth considering when you control heterogeneous runtimes and need a common workload identity layer. SPIFFE assigns URI identities inside trust domains, and federation distributes the public bundles needed to validate identities from another domain. Its specification requires verifiers to use the bundle for the trust domain named in the SPIFFE ID. That preserves separate roots; exchanging bundles does not merge two domains into one. Cloud role mappings still need narrow policy at the boundary.
Federation also needs an outage owner. Keep a registry of accepted issuers, validation keys or discovery endpoints, subjects, audiences, destination roles, and responsible teams. Alert before configuration expiry, rehearse signing key rotation, and document which exchanges stop when an issuer becomes unavailable. A rollback should restore the previous narrow trust configuration, never enable a wildcard subject or revive a shared key. Review the registry whenever an agent changes runtime, repository ownership, or production scope, because the old binding may remain technically valid after the workload has moved.
At oleg.is, I put this identity work inside the engineering operating model rather than leaving it as an IAM cleanup after agents reach production. The person who owns an agent's tools and deployment must also own its trust tuple, destination roles, and revocation test.
The migration is finished when a copied token expires quickly, a copied workload configuration cannot mint credentials somewhere else, and an operator can disable one agent without disabling its neighbors. Anything less is a secret rotation problem wearing federation vocabulary.
Frequently Asked Questions
What is workload identity for an AI agent?
It is a cryptographically verifiable identity tied to the runtime executing the agent, such as a Kubernetes service account or managed cloud workload. The destination cloud validates that identity and issues temporary local credentials under a narrow role.
Can workload identity completely replace API keys?
It can replace static cloud credentials where the source runtime and destination support federation. Third-party APIs that accept only long lived keys still need a secret, but you can isolate that secret behind a broker instead of exposing it to the agent process.
Is OIDC enough to secure an agent across clouds?
No. OIDC gives you signed claims and discovery, but each destination must restrict issuer, subject, audience, and relevant tenant or workload attributes. A valid OIDC token from an overly broad trust relationship is still valid authority.
How short should an agent's cloud credentials last?
Set the lifetime to cover one operation or bounded batch plus expected retries. Fifteen minutes is a reasonable starting point where providers and workloads support it, but narrow permissions and exact trust conditions matter more than shaving a few minutes.
Should every AI agent have its own cloud role?
Give agents separate roles when their permissions, owners, environments, or revocation needs differ. Replicas of the same approved workload can share a role, but unrelated tools should not accumulate permissions on one convenient service account.
What claims should a federation policy check?
Always validate the exact issuer, a stable subject, the intended audience, and expiry. For a shared issuer, also restrict the organization or tenant, then add immutable repository, workflow, namespace, or environment claims that define the approved execution.
Does federation stop a prompt injection from using cloud access?
Federation does not decide whether an agent's requested action is safe. It limits which workload can obtain which role and for how long, while a separate authorization layer must validate tool calls, user delegation, resources, and approvals.
How do I revoke a federated agent quickly?
Disable its source workload binding or destination trust mapping, then revoke or block the destination principal where the provider permits. Existing sessions may remain usable until they expire, so keep lifetimes bounded and document the maximum revocation delay.
When should I use SPIFFE for agent identity?
Use SPIFFE when you operate workloads across heterogeneous clusters or infrastructure and need one attested identity format between services. It adds a control plane, so native cloud federation is usually simpler for a small number of direct cloud access paths.
What should an agent identity audit log contain?
Record the trusted execution ID, issuer, subject, audience, destination principal, policy version, credential lifetime, requested action, and result. Keep raw tokens and unrelated prompt content out of the identity log.


