Back to blog
·7 min read·BitAtlas Team

Agent Key Rotation: Automating Secrets Lifecycle for AI Infrastructure

How to automate cryptographic key rotation and secrets lifecycle management for AI agent infrastructure — from vault integration to zero-downtime rotation strategies.

key rotationsecrets lifecyclekey managementagent securityoperationsvaultAI agentscryptography

AI agents are not stateless scripts you fire once and forget. They run continuously, hold long-lived credentials, accumulate state, and talk to dozens of downstream services. Every API key, database password, and encryption key they carry is a liability — and if you're not rotating those secrets on a schedule, you're accumulating risk with every passing day.

This post covers the practical mechanics of automating cryptographic key rotation and secrets lifecycle management for agent infrastructure. We'll look at what rotation actually means for agents (it's more complex than for static services), the patterns that work in production, and how encrypted agent state storage fits into the picture.

Why Key Rotation Is Harder for Agents

Rotating credentials for a traditional web server is straightforward: update the secret, deploy the new config, done. Agents make this messier in three ways.

Long-running processes. An agent that's been running for six hours may have cached credentials in memory that a config update won't touch. You need a mechanism for in-process refresh, not just environment variable replacement.

Distributed identity. In multi-agent systems, a dozen agent instances may share a single service account key. Rotating it means coordinating across all instances simultaneously, or accepting a window where some agents use the old key and some use the new.

Encrypted state. If your agent uses client-side encryption to protect its state (which you should be doing), the encryption key is itself a secret that needs rotation — but rotating it means re-encrypting existing state, not just swapping out a credential.

Understanding these three dimensions is the prerequisite for building a rotation system that actually works.

The Four Phases of Secrets Lifecycle

Think of every secret your agent holds as moving through four phases:

  1. Generation — the secret is created with a defined algorithm, length, and entropy source.
  2. Distribution — the secret reaches the agent securely, without traversing logs or environment variables in plaintext.
  3. Rotation — the secret is replaced with a new value before it expires or is compromised.
  4. Revocation — the old secret is invalidated immediately if it's suspected to be compromised.

Most teams focus only on generation and distribution, then treat rotation as an afterthought. In practice, rotation and revocation are the phases that determine your actual security posture.

Vault-Based Rotation: The Right Abstraction

HashiCorp Vault (and its managed equivalents) solves the distribution and rotation problem at the same time. Instead of your agent reading credentials from environment variables, it reads them from Vault at startup and on a TTL-based refresh cycle.

import { VaultClient } from '@hashicorp/vault-client';

const vault = new VaultClient({ endpoint: process.env.VAULT_ADDR });

async function getAgentCredentials(secretPath: string) {
  const secret = await vault.read(secretPath);
  return {
    value: secret.data.value,
    expiresAt: Date.now() + (secret.lease_duration * 1000),
  };
}

async function refreshIfExpiring(credential: Credential) {
  const bufferMs = 60_000; // refresh 60s before expiry
  if (credential.expiresAt - Date.now() < bufferMs) {
    return getAgentCredentials(credential.path);
  }
  return credential;
}

The key design principle here is that your agent never holds a credential for longer than its lease duration. Vault handles the actual rotation on the backend; your agent just re-fetches on a schedule. This decouples rotation from deployment.

For dynamic secrets (database credentials, cloud IAM tokens), Vault can generate short-lived credentials on demand — credentials that automatically expire after a configurable TTL. An agent that gets a database password with a 1-hour TTL is a fundamentally different risk profile than one holding a static credential.

Zero-Downtime Rotation for Encryption Keys

Rotating API keys and database credentials is relatively easy because the old key can simply be invalidated. Rotating encryption keys is harder: you have existing data encrypted under the old key, and you need to re-encrypt it under the new key without downtime.

The standard pattern is key versioning with gradual migration:

interface VersionedKey {
  id: string;       // e.g. "key-v3"
  version: number;
  material: CryptoKey;
  createdAt: number;
  retiredAt?: number;
}

async function decrypt(ciphertext: ArrayBuffer, keyId: string): Promise<ArrayBuffer> {
  const key = await keyStore.get(keyId);
  return crypto.subtle.decrypt({ name: 'AES-GCM', iv: extractIv(ciphertext) }, key.material, ciphertext);
}

async function encrypt(plaintext: ArrayBuffer): Promise<{ ciphertext: ArrayBuffer; keyId: string }> {
  const activeKey = await keyStore.getActive(); // always encrypt with current key
  const ciphertext = await crypto.subtle.encrypt(
    { name: 'AES-GCM', iv: crypto.getRandomValues(new Uint8Array(12)) },
    activeKey.material,
    plaintext
  );
  return { ciphertext, keyId: activeKey.id };
}

The encrypt function always uses the current active key. The decrypt function accepts any key version. This means:

  • New data is always encrypted under the latest key
  • Existing data continues to be readable under its original key version
  • A background job can re-encrypt old data at its own pace, without blocking the agent

Once all data has been migrated to the new key, the old key can be retired. At that point, decryption using the old key ID fails, which is the desired behavior.

Automating Rotation with Policy Engines

Manual rotation is a process that gets skipped under pressure. The only rotation you can count on is automated rotation.

For Vault-backed infrastructure, you can define rotation policies as code:

# Set a 30-day automatic rotation schedule for agent API keys
vault write auth/token/roles/agent-role \
  token_ttl=24h \
  token_max_ttl=720h \
  token_period=24h \
  renewable=true

For encryption keys stored in a KMS (AWS KMS, Google Cloud KMS, or Azure Key Vault), automatic rotation is typically a checkbox in the console or a single API call:

# Enable automatic annual rotation on AWS KMS
aws kms enable-key-rotation --key-id alias/agent-encryption-key

The challenge is that KMS automatic rotation only works for KMS-managed keys used for envelope encryption. If you're doing client-side encryption (which BitAtlas is built around), you control the key material and need to implement rotation yourself — which is why the versioned key pattern above matters.

Secrets Lifecycle in Practice: What to Monitor

Rotation is only half the problem. You also need visibility into the state of your secrets inventory:

  • Age of each secret — secrets that haven't rotated in 90+ days are a red flag
  • Last rotation timestamp — to detect when automated rotation fails silently
  • Number of services sharing a credential — secrets shared across many services are high blast-radius
  • Rotation failure rate — if rotation is failing, the schedule is decorative

Build alerts for these signals, not dashboards you'll look at quarterly. A secret that was supposed to rotate yesterday and didn't is an incident waiting to happen.

Where Encrypted Agent State Fits

Agent key rotation and encrypted agent state storage are deeply intertwined. If your agent's state is stored in plaintext, a stolen encryption key (or the absence of one) doesn't matter — the data is already exposed. But if you're using client-side encryption for agent state, your data encryption key becomes the single most important secret your agent holds.

That's the argument for treating the data encryption key with the same rigor as a database password: it should have a short TTL, it should rotate automatically, it should be versioned, and rotation failures should alert immediately.

BitAtlas stores agent state with client-side encryption, which means the key material stays out of our infrastructure entirely. But that puts the burden of key lifecycle management on you. The patterns in this post — vault-backed distribution, versioned encryption keys, gradual migration, automated policy enforcement — are the foundation for doing that responsibly.

Rotation isn't glamorous. It's infrastructure plumbing that nobody notices when it works. But when it fails, or when it was never set up, the consequences are expensive. Get it automated early, before your agent fleet gets large enough that manual rotation becomes impossible.

Encrypt your agent's data today

BitAtlas gives your AI agents AES-256-GCM encrypted storage with zero-knowledge guarantees. Free tier, no credit card required.