AAnvio
Security

Secrets & Encryption

How Anvio encrypts API keys, credential pools, and OAuth connection tokens at rest using AES-256-GCM.

5 min read

Anvio encrypts three categories of secret at rest, all using the same primitive (AES-256-GCM with a scrypt-derived key) but stored in separate files with separate passphrases/keys. This page covers the mechanics; see Authentication and Runtime OAuth for when each is used.

The shared encryption primitive

Both packages/credentials/src/encrypted-store.ts and packages/harness/src/connect/broker.ts implement the identical pattern independently:

const salt = randomBytes(16);
const iv = randomBytes(12);
const key = scryptSync(passphraseOrKey, salt, 32);       // 256-bit key
const cipher = createCipheriv('aes-256-gcm', key, iv);
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
const blob = Buffer.concat([salt, iv, tag, encrypted]).toString('base64');

Each encrypted blob is self-contained: salt (16 bytes) || iv (12 bytes) || authTag (16 bytes) || ciphertext, base64-encoded. A fresh random salt and IV are generated on every encryption call, so encrypting the same plaintext twice produces different ciphertext. Decryption reverses the layout and calls decipher.setAuthTag(tag) before finalizing — GCM's authentication tag means tampered ciphertext fails decryption rather than silently producing garbage.

1. Credential pools (model API keys)

EncryptedCredentialStore (packages/credentials/src/encrypted-store.ts) encrypts individual API keys added via anvio credentials add, keyed by ANVIO_CREDENTIALS_PASSPHRASE.

workspace/credentials/
  pools.yaml                    # Pool definitions — provider, strategy, rotation policy (NO secrets)
  encrypted/
    anthropic.enc.json          # { "key1": "<base64 salt|iv|tag|ciphertext>", "key2": "..." }
    openai.enc.json
  audit/
    usage.jsonl                 # Usage and rotation audit log (no secret values)
anvio credentials init --passphrase
anvio credentials add anthropic --id key1 --value $ANTHROPIC_API_KEY
anvio credentials rotate anthropic --id key1 --new-value $NEW_KEY
anvio credentials list
anvio credentials status anthropic
anvio credentials test anthropic

The pool manager (packages/credentials/src/pool-manager.ts, CredentialPoolManagerImpl) reads pools.yaml for metadata (provider, round_robin / least_used / random selection strategy, rotation cooldown, failover chain) and only touches EncryptedCredentialStore to fetch/store the actual key value — the YAML pool file itself never contains a plaintext secret, only an encryptedRef pointer like encrypted/anthropic.enc.json#key1.

Rate-limit handling is automatic: markRateLimited() flips a credential's status to rate_limited with a cooldown timestamp; selectCredential() restores it to active once the cooldown elapses; if the whole pool is exhausted, tryFailover() walks to spec.failover.fallbackPool (e.g. Anthropic pool exhausted → fails over to an OpenAI pool) if configured.

testPool() masks the value before returning it (${cred.value.slice(0, 4)}...) — never logs or displays the full secret.

2. Connection broker (OAuth tokens, channel/MCP grants)

ConnectionStore / ConnectionBroker (packages/harness/src/connect/broker.ts) encrypt connection payloads — runtime OAuth tokens, per-user MCP grants — keyed by ANVIO_CONNECTION_ENCRYPTION_KEY.

workspace/connections/_state/
  <channel>:<userId>:<service>.json   # { id, channel, userId, service, encryptedPayload, createdAt, expiresAt, threadIds }
  _grants.json                        # Cross-user access grants (borrower/owner/scope/expiry)
connectionId(channel, userId, service) // e.g. "slack:U123:claude-code"

Each stored connection carries its own expiresAt; read() returns null for anything already expired, and listAll() silently skips corrupt or expired entries rather than throwing. Connections are also thread-scoped — threadAllowed() restricts a credential to the threads it was granted in unless the threadIds list is empty (unrestricted).

grantAccess() supports borrowing: one user's connection can be lent to another (borrowerUserId) for a scoped thread or channel, with its own expiry, tracked in _grants.json — used for delegated/cross-agent access without duplicating the underlying OAuth token.

This is the mechanism behind anvio setup-token --claude --user alice — the resulting Claude Code OAuth token is encrypted and written under this broker, discriminated by service: claude-code, service: codex, etc., so runtime OAuth tokens never mix with MCP/channel tokens even though they use the same storage class. See Runtime OAuth for the full setup-token flow.

Enable the broker in workspace/harness/defaults.yaml:

connectBroker:
  enabled: true
  encryptionKeyEnv: ANVIO_CONNECTION_ENCRYPTION_KEY
  defaultTtlSeconds: 3600

3. Local OAuth callback host

packages/harness/src/connect/login-host.ts (startLoginHost) spins up a short-lived local HTTP server (127.0.0.1 by default) to catch an OAuth redirect's query parameters during a contextual connection flow (e.g. anvio connect login-host --provider github), then closes itself. It does not persist anything itself — the captured grant is handed to ConnectionBroker.putConnection() for encryption and storage. A 120-second default timeout (timeoutMs) rejects the waiting promise if no callback arrives.

Key management rules

  • Never commit .env, ANVIO_CREDENTIALS_PASSPHRASE, ANVIO_CONNECTION_ENCRYPTION_KEY, or any OAuth token to git.
  • Rotating ANVIO_CONNECTION_ENCRYPTION_KEY makes every existing encrypted connection blob permanently unreadable (the salt is stored per-blob, but the key itself is not derivable from anything on disk). Treat key rotation as a migration: re-run anvio setup-token / anvio connect login-host for every affected user after rotating.
  • encrypted/*.enc.json and _state/*.json files are safe to back up as-is — they're useless without the corresponding passphrase/key, but back up the passphrase/key separately from the encrypted files.
  • Never log a decrypted credential value. testPool() is the sanctioned pattern (mask to first 4 characters).

Migrating machines

# Credential pools
cp -r workspace/credentials/ /new-machine/workspace/credentials/
export ANVIO_CREDENTIALS_PASSPHRASE="same-passphrase-as-before"

# Connection broker (OAuth tokens)
rsync -av ./workspace/connections/ user@server:/opt/anvio/workspace/connections/
export ANVIO_CONNECTION_ENCRYPTION_KEY="same-key-as-before"

Both are pure file copies — no database migration step, consistent with Anvio's file-first design. The passphrase/key must travel with the files through a separate, out-of-band channel (secrets manager, not the same rsync/git operation).

Future: external secret backends

docs/12-security.md notes Vault/SSM support is targeted for Level 4. docs/33-credential-pools.md's extension guide calls out implementing a CredentialStore port for HashiCorp Vault as the intended integration point — not yet built.

TODO: No HashiCorp Vault, AWS SSM, or cloud KMS integration exists in the current codebase. The only supported secret backend today is the local AES-256-GCM file store described above, keyed by a passphrase/key you manage yourself.

Edit on GitHub

Last updated on

On this page