Skip to content
64 changes: 64 additions & 0 deletions litellm/proxy/client/cli/commands/encryption.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""CLI commands for the at-rest credential encryption migration."""

import click
import rich

from ...http_client import HTTPClient


@click.group()
def encryption():
"""Migrate at-rest credentials to AES-256-GCM and attest residual state."""
pass


@encryption.command(name="migrate")
@click.option(
"--check",
"check_only",
is_flag=True,
default=False,
help="Read-only residual scan (no writes). Reports legacy values remaining.",
)
@click.option(
"--dry-run",
is_flag=True,
default=False,
help="Run the full migration walkers without writing any changes.",
)
@click.pass_context
def migrate(ctx: click.Context, check_only: bool, dry_run: bool):
"""Re-encrypt at-rest credentials into the AES-256-GCM (v2:gcm:) format.

Requires the proxy to be started with
``general_settings.encryption_algorithm: aes-256-gcm``. Idempotent and
resumable — safe to re-run after an interruption.

Examples:
litellm-proxy encryption migrate --check # attestation scan, no writes
litellm-proxy encryption migrate # perform the migration
"""
client = HTTPClient(ctx.obj["base_url"], ctx.obj["api_key"])

if check_only:
response = client.request(
"GET", "/credentials/migrate-encryption/check"
)
else:
response = client.request(
"POST",
"/credentials/migrate-encryption",
json={},
params={"dry_run": "true"} if dry_run else None,
)

rich.print_json(data=response)

report = response.get("report", {}) if isinstance(response, dict) else {}
residual = report.get("residual_legacy")
if residual is not None and residual > 0:
rich.print(
f"[yellow]Residual legacy values remaining: {residual}[/yellow]"
)
elif residual == 0:
rich.print("[green]No legacy values remaining (residual_legacy == 0).[/green]")
3 changes: 3 additions & 0 deletions litellm/proxy/client/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .commands.auth import get_stored_api_key, login, logout, whoami
from .commands.chat import chat
from .commands.credentials import credentials
from .commands.encryption import encryption
from .commands.http import http
from .commands.keys import keys

Expand Down Expand Up @@ -103,6 +104,8 @@ def version(ctx: click.Context):
cli.add_command(models)
# Add the credentials command group
cli.add_command(credentials)
# Add the encryption migration command group
cli.add_command(encryption)
# Add the chat command group
cli.add_command(chat)
# Add the http command group
Expand Down
76 changes: 76 additions & 0 deletions litellm/proxy/common_utils/encrypt_decrypt_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@

from litellm._logging import verbose_proxy_logger

# Versioned ciphertext marker for AES-256-GCM values.
# Format: "v2:gcm:" + base64url(nonce(12) || ciphertext || tag(16)).
# Legacy XSalsa20-Poly1305 (nacl) values carry no marker; the colon in the
# prefix can never appear in base64url(nacl output), so the prefix check is an
# unambiguous discriminator between the two formats on read.
_V2_GCM_PREFIX = "v2:gcm:"

# general_settings key selecting the at-rest encryption algorithm for new writes.
# Default preserves the legacy algorithm so existing deployments are byte-for-byte
# unchanged until they explicitly opt in. Decrypt is always format-detecting, so
# flipping this flag forward (or back) never strands previously-written data.
_ENCRYPTION_ALGORITHM_SETTING = "encryption_algorithm"
_ALGO_AES_GCM = "aes-256-gcm"
_ALGO_XSALSA20 = "xsalsa20-poly1305"


def _get_salt_key():
from litellm.proxy.proxy_server import master_key
Expand All @@ -16,11 +31,67 @@ def _get_salt_key():
return salt_key


def _get_encryption_algorithm() -> str:
"""
Resolve the configured at-rest encryption algorithm for *new writes*.

Read from ``general_settings.encryption_algorithm`` at write time. Defaults to
the legacy XSalsa20-Poly1305 algorithm so deployments that have not opted in
keep producing byte-for-byte identical ciphertext.
"""
try:
from litellm.proxy.proxy_server import general_settings

algo = general_settings.get(_ENCRYPTION_ALGORITHM_SETTING, _ALGO_XSALSA20)
except Exception:
# general_settings may not be importable in some contexts (e.g. SDK-only
# use of these helpers). Fall back to the legacy algorithm.
return _ALGO_XSALSA20

if isinstance(algo, str) and algo.lower() == _ALGO_AES_GCM:
return _ALGO_AES_GCM
return _ALGO_XSALSA20


def _derive_key(signing_key: str) -> bytes:
"""Derive a 32-byte key from the salt/master key (shared by both algorithms)."""
import hashlib

return hashlib.sha256(signing_key.encode()).digest()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


def _encrypt_aes_gcm(value: str, signing_key: str) -> str:
"""Encrypt under AES-256-GCM and return the versioned ``v2:gcm:`` string."""
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

nonce = os.urandom(12)
# AESGCM.encrypt returns ciphertext || tag(16); wire format is nonce || that.
blob = AESGCM(_derive_key(signing_key)).encrypt(nonce, value.encode("utf-8"), None)
return _V2_GCM_PREFIX + base64.urlsafe_b64encode(nonce + blob).decode("utf-8")


def _decrypt_aes_gcm(value: str, signing_key: str) -> str:
"""Decrypt a versioned ``v2:gcm:`` string produced by :func:`_encrypt_aes_gcm`."""
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

raw = base64.urlsafe_b64decode(value[len(_V2_GCM_PREFIX) :])
# An empty plaintext still serializes to nonce(12) || tag(16) = 28 bytes, so a
# short/empty buffer here is a corrupt value: let AESGCM.decrypt raise and be
# swallowed by decrypt_value_helper (returns None/original), same as legacy.
nonce, blob = raw[:12], raw[12:]
return AESGCM(_derive_key(signing_key)).decrypt(nonce, blob, None).decode("utf-8")


def encrypt_value_helper(value: str, new_encryption_key: Optional[str] = None):
signing_key = new_encryption_key or _get_salt_key()

try:
if isinstance(value, str):
if _get_encryption_algorithm() == _ALGO_AES_GCM:
# AES path: the v2:gcm: output is already a base64url string, so it
# is returned directly with no extra base64 wrapper.
return _encrypt_aes_gcm(value=value, signing_key=signing_key) # type: ignore

encrypted_value = encrypt_value(value=value, signing_key=signing_key) # type: ignore
# Use urlsafe_b64encode for URL-safe base64 encoding (replaces + with - and / with _)
encrypted_value = base64.urlsafe_b64encode(encrypted_value).decode("utf-8")
Expand All @@ -46,6 +117,11 @@ def decrypt_value_helper(

try:
if isinstance(value, str):
# Versioned AES-256-GCM values are detected before any base64 decode.
# The prefix is the algorithm tag the legacy nacl format never carried.
if value.startswith(_V2_GCM_PREFIX):
return _decrypt_aes_gcm(value=value, signing_key=signing_key) # type: ignore

# Try URL-safe base64 decoding first (new format)
# Fall back to standard base64 decoding for backwards compatibility (old format)
try:
Expand Down
Loading
Loading